-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathBack.ts
More file actions
2511 lines (2181 loc) · 79.1 KB
/
Copy pathBack.ts
File metadata and controls
2511 lines (2181 loc) · 79.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Express, Request, Response } from 'express';
import type { AnySchemaObject } from 'ajv';
import type { Writable } from 'stream';
import type { ZodType } from 'zod';
import { ActionCheckSource, AdminForthFilterOperators, AdminForthSortDirections, AllowedActionsEnum, AdminForthResourcePages,
type AdminForthComponentDeclaration,
type AdminUser, type AllowedActionsResolved,
type AdminForthBulkActionCommon,
type AdminForthForeignResourceCommon,
type AdminForthResourceColumnCommon,
type AdminForthResourceInputCommon,
type AdminForthComponentDeclarationFull,
type AdminForthConfigMenuItem,
type AdminForthMenuContribution,
type AnnouncementBadgeResponse,
type AdminForthResourceColumnInputCommon,
type ColumnMinMaxValue,
} from './Common.js';
export const PERIOD_UNITS = ['s', 'm', 'h', 'd'] as const;
export type PeriodUnit = typeof PERIOD_UNITS[number];
export type PeriodString = `${bigint}${PeriodUnit}`;
export type RateLimitString = `${bigint}/${PeriodString}`;
export interface ICodeInjector {
srcFoldersToSync: Object;
allComponentNames: Object;
devServerPort: number;
getServeDir(): string;
registerCustomComponent(filePath: string): void;
spaTmpPath(): string;
}
export interface IConfigValidator {
validateConfig(): void;
validateAfterPluginsActivation(): void;
postProcessAfterDiscover(resource: AdminForthResource): void;
}
export interface IAdminForthHttpResponse {
setHeader: (key: string, value: string) => void,
setStatus: (code: number, message?: string) => void,
blobStream: () => Writable,
};
export interface IAdminForthEndpointHandlerInput {
body: any;
adminUser: AdminUser | undefined;
query: {[key: string]: any};
headers: {[key: string]: any};
cookies: Array<{ key: string, value: string }>;
response: IAdminForthHttpResponse;
requestUrl: string;
abortSignal: AbortSignal;
_raw_express_req: Request;
_raw_express_res: Response;
tr: ITranslateFunction;
}
export interface IAdminForthAuthenticatedEndpointHandlerInput extends IAdminForthEndpointHandlerInput {
adminUser: AdminUser;
}
export type AgentToolMeta = {
isDangerous?: boolean;
};
export interface IAdminForthEndpointOptionsBase {
method: string,
path: string,
description?: string,
request_schema?: AnySchemaObject,
response_schema?: AnySchemaObject,
agent?: AgentToolMeta,
meta?: Record<string, unknown>,
target?: 'json' | 'upload',
}
export interface IAdminForthAuthenticatedEndpointOptions extends IAdminForthEndpointOptionsBase {
noAuth?: false,
handler: (input: IAdminForthAuthenticatedEndpointHandlerInput) => void | Promise<any>,
}
export interface IAdminForthNoAuthEndpointOptions extends IAdminForthEndpointOptionsBase {
noAuth: true,
handler: (input: IAdminForthEndpointHandlerInput) => void | Promise<any>,
}
export type IAdminForthEndpointOptions =
| IAdminForthAuthenticatedEndpointOptions
| IAdminForthNoAuthEndpointOptions;
export type AdminForthExpressSchemaInput = AnySchemaObject | ZodType;
export interface IAdminForthExpressRouteSchema {
/**
* Detailed OpenAPI operation description for a custom Express route.
*/
description?: string;
/**
* JSON schema or Zod schema describing the request body for a custom Express route.
*/
request?: AdminForthExpressSchemaInput;
/**
* JSON schema or Zod schema describing the JSON response body for a custom Express route.
*/
response?: AdminForthExpressSchemaInput;
/**
* AdminForth agent metadata.
*/
agent?: AgentToolMeta;
/**
* Internal metadata for AdminForth integrations. This is not rendered in the OpenAPI document.
*/
meta?: Record<string, unknown>;
}
export interface IRegisteredApiSchema {
method: string;
path: string;
description?: string;
agent?: AgentToolMeta;
meta?: Record<string, unknown>;
request_schema?: AnySchemaObject;
response_schema?: AnySchemaObject;
handler?: (input: IAdminForthEndpointHandlerInput) => void | Promise<any>;
}
export interface IAdminForthApiValidationError {
instancePath: string;
schemaPath: string;
keyword: string;
message?: string;
params: {[key: string]: any};
}
export interface IAdminForthApiValidationResult {
valid: boolean;
errors?: IAdminForthApiValidationError[];
}
export interface IOpenApiRegistry {
registeredSchemas: IRegisteredApiSchema[];
registerApiSchema(options: IAdminForthEndpointOptions): IRegisteredApiSchema;
register_api_schema(options: IAdminForthEndpointOptions): IRegisteredApiSchema;
validateRequestSchema(route: IRegisteredApiSchema | null, payload: any): IAdminForthApiValidationResult;
validateResponseSchema(route: IRegisteredApiSchema | null, payload: any): IAdminForthApiValidationResult;
renderOpenApiDocument(): {[key: string]: any};
}
/**
* Implement this interface to create custom HTTP server adapter for AdminForth.
*/
export interface IHttpServer {
// constructor(adminforth: IAdminForth): void;
/**
* Sets up HTTP server to serve AdminForth SPA.
* if hotReload is true, it should proxy all requests and headers to Vite dev server at `http://localhost:5173$\{req.url\}`
* otherwise it should serve AdminForth SPA from dist folder. See Express for example.
*/
setupSpaServer(): void;
/**
* Method which should register endpoint in HTTP server.
*
* @param options : Object with method, path and handler properties.
*/
endpoint(options: IAdminForthAuthenticatedEndpointOptions): void;
endpoint(options: IAdminForthNoAuthEndpointOptions): void;
}
export interface IExpressHttpServer extends IHttpServer {
/**
* Call this method to serve AdminForth SPA from Express instance.
* @param app : Express instance
*/
serve(app: Express): void;
/**
* Method to start listening on port.
*/
listen(port: number, callback: Function): void;
listen(port: number, host: string, callback: Function): void;
/**
* Returns an internal HTTP origin for same-process/server API calls.
*/
getInternalApiOrigin(): string | undefined;
/**
* Method (middleware) to wrap express endpoints with authorization check.
* Adds adminUser to request object if user is authorized. Drops request with 401 status if user is not authorized.
* @param callable : Function which will be called if user is authorized.
*
*
* @example
* ```ts
* expressApp.get('/myApi', authorize((req, res) => {
* console.log('User is authorized', req.adminUser);
* res.json({ message: 'Hello World' });
* }));
* ```
*
*/
authorize(callable: (...args: any[]) => any): (...args: any[]) => any;
/**
* Method (middleware) to inject translation helper into Express request object.
*/
translatable(callable: (...args: any[]) => any): (...args: any[]) => any;
/**
* Registers OpenAPI schemas for a custom Express route.
*
* Wrap this around the handler passed to `app.get/post/...`.
* If you also need authorization, make `withSchema` the outer wrapper:
*
* ```ts
* import * as z from 'zod';
*
* app.get('/myApi', admin.express.withSchema({
* description: 'Returns current user profile',
* response: z.object({ user: z.unknown() }),
* }, admin.express.authorize((req, res) => {
* res.json({ user: req.adminUser });
* })));
* ```
*/
withSchema(schema: IAdminForthExpressRouteSchema, callable: (...args: any[]) => any): (...args: any[]) => any;
}
export interface ITranslateFunction {
(
msg: string,
category: string,
params?: any,
pluralizationNumber?: number
): Promise<string>;
}
// Omit <Request, 'param'> is used to remove 'param' method from Request type for correct docs generation
export interface IAdminUserExpressRequest extends Omit<Request, 'protocol' | 'param' | 'unshift'> {
adminUser: AdminUser;
}
export interface ITranslateExpressRequest extends Omit<Request, 'protocol' | 'param' | 'unshift'> {
tr: ITranslateFunction;
}
export interface IAdminForthSingleFilter {
field?: string;
operator?: AdminForthFilterOperators.EQ | AdminForthFilterOperators.NE
| AdminForthFilterOperators.GT | AdminForthFilterOperators.LT | AdminForthFilterOperators.GTE
| AdminForthFilterOperators.LTE | AdminForthFilterOperators.LIKE | AdminForthFilterOperators.ILIKE
| AdminForthFilterOperators.IN | AdminForthFilterOperators.NIN | AdminForthFilterOperators.IS_EMPTY | AdminForthFilterOperators.IS_NOT_EMPTY;
value?: any;
rightField?: string;
insecureRawSQL?: string;
insecureRawNoSQL?: any;
}
export interface IAdminForthAndOrFilter {
operator: AdminForthFilterOperators.AND | AdminForthFilterOperators.OR;
subFilters: Array<IAdminForthAndOrFilter | IAdminForthSingleFilter>
}
export interface IAdminForthSort {
field: string,
direction: AdminForthSortDirections
}
export interface IAdminForthDataSourceConnector {
client: any;
/**
* Function to setup client connection to database.
* @param url URL to database. Examples: clickhouse://demo:demo@localhost:8125/demo
* @param options Optional connection options. `recovery` mirrors the dataSource
* `connectionRecovery` flag (defaults to true when omitted).
*/
setupClient(url: string, options?: { recovery?: boolean }): Promise<void>;
/**
* Function to get all tables from database.
*/
getAllTables(): Promise<Array<string>>;
/**
* Function to get all columns in table.
*/
getAllColumnsInTable(tableName: string): Promise<Array<{ name: string; type?: string; isPrimaryKey?: boolean; sampleValue?: any; }>>;
/**
* Function to check whether database has no user data.
*/
isDatabaseEmpty?(): Promise<boolean>;
/**
* Optional.
* You an redefine this function to define how one record should be fetched from database.
* You you will not redefine it, AdminForth will use {@link IAdminForthDataSourceConnector.getData} with limit 1 and offset 0 and
* filter by primary key.
*/
getRecordByPrimaryKeyWithOriginalTypes(resource: AdminForthResource, recordId: string): Promise<any>;
/**
* Function should go over all columns of table defined in resource.table and try to guess
* data and constraints for each columns.
* Type should be saved to:
* - {@link AdminForthResourceColumn.type}
* Constraints:
* - {@link AdminForthResourceColumn.required}
* - {@link AdminForthResourceColumn.primaryKey}
* For string fields:
* - {@link AdminForthResourceColumn.maxLength}
* For numbers:
* // min/max are used inside getMinMaxForColumns from base connector
* - {@link AdminForthResourceColumn.min}
* - {@link AdminForthResourceColumn.max}
* - {@link AdminForthResourceColumn.minValue},
* - {@link AdminForthResourceColumn.maxValue},
* - {@link AdminForthResourceColumn.enum},
* - {@link AdminForthResourceColumn.foreignResource},
* - {@link AdminForthResourceColumn.sortable},
* - {@link AdminForthResourceColumn.backendOnly},
* - {@link AdminForthResourceColumn.masked},
* - {@link AdminForthResourceColumn.virtual},
* - {@link AdminForthResourceColumn.components},
* - {@link AdminForthResourceColumn.allowMinMaxQuery},
* - {@link AdminForthResourceColumn.editingNote},
* - {@link AdminForthResourceColumn.showIn},
* - {@link AdminForthResourceColumn.isUnique},
* - {@link AdminForthResourceColumn.validation})
* Also you can additionally save original column type to {@link AdminForthResourceColumn._underlineType}. This might be later used
* in {@link IAdminForthDataSourceConnector.getFieldValue} and {@link IAdminForthDataSourceConnector.setFieldValue} methods.
*
*
* @param resource
*/
discoverFields(resource: AdminForthResource, config: AdminForthConfig): Promise<{[key: string]: AdminForthResourceColumn}>;
/**
* Used to transform record after fetching from database.
* According to AdminForth convention, if {@link AdminForthResourceColumn.type} is set to {@link AdminForthDataTypes.DATETIME} then it should be transformed to ISO string.
* @param field
* @param value
*/
getFieldValue(field: AdminForthResourceColumn, value: any): any;
/**
* Used to transform record before saving to database. Should perform operation inverse to {@link IAdminForthDataSourceConnector.getFieldValue}
* @param field
* @param value
*/
setFieldValue(field: AdminForthResourceColumn, value: any): any;
/**
* Used to fetch data from database.
* This method is reused both to list records and show one record (by passing limit 1 and offset 0) .
*
* Fields are returned from db "as is" then {@link AdminForthBaseConnector.getData} will transform each field using {@link IAdminForthDataSourceConnector.getFieldValue}
*/
getDataWithOriginalTypes({ resource, limit, offset, sort, filters, columns }: {
resource: AdminForthResource,
limit: number,
offset: number,
sort: IAdminForthSort[],
filters: IAdminForthAndOrFilter,
columns?: AdminForthResourceColumn[],
}): Promise<Array<any>>;
/**
* Used to get count of records in database.
*/
getCount({ resource, filters }: {
resource: AdminForthResource,
filters: IAdminForthAndOrFilter,
}): Promise<number>;
/**
* Optional method which used to get min and max values for columns in resource.
* Called only for columns which have {@link AdminForthResourceColumn.allowMinMaxQuery} set to true.
*
* Internally should call {@link IAdminForthDataSourceConnector.getFieldValue} for both min and max values.
*/
getMinMaxForColumnsWithOriginalTypes({ resource, columns }: { resource: AdminForthResource, columns: AdminForthResourceColumn[] }): Promise<ColumnMinMaxValue>;
/**
* Used to create record in database. Should return value of primary key column of created record.
*/
createRecordOriginalValues({ resource, record }: { resource: AdminForthResource, record: any }): Promise<string>;
/**
* Update record in database. newValues might have not all fields in record, but only changed ones.
* recordId is value of field which is marked as {@link AdminForthResourceColumn.primaryKey}
*/
updateRecordOriginalValues({ resource, recordId, newValues }: { resource: AdminForthResource; recordId: string; newValues: any; }): Promise<void>;
/**
* Used to delete record in database.
*/
deleteRecord({ resource, recordId }: { resource: AdminForthResource, recordId: any }): Promise<boolean>;
/**
* Optional. Used to perform aggregation queries on a resource table.
* Returns rows with aliased aggregate values and optional group key.
*/
getAggregateWithOriginalTypes?({ resource, filters, aggregations, groupBy }: {
resource: AdminForthResource,
filters: IAdminForthAndOrFilter,
aggregations: { [alias: string]: IAggregationRule },
groupBy?: IGroupByRule | IGroupByRule[],
}): Promise<Array<{ group?: string, [key: string]: any }>>;
}
/**
* Interface that exposes methods to interact with AdminForth in standard way
*/
export interface IAdminForthDataSourceConnectorBase extends IAdminForthDataSourceConnector {
validateAndNormalizeInputFilters(filter: IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter> | undefined): IAdminForthAndOrFilter;
getPrimaryKey(resource: AdminForthResource): string;
getData({ resource, limit, offset, sort, filters, columns }: {
resource: AdminForthResource,
limit: number,
offset: number,
sort: IAdminForthSort[],
filters: IAdminForthAndOrFilter,
getTotals?: boolean,
columns?: AdminForthResourceColumn[],
}): Promise<{ data: Array<any>, total: number }>;
getRecordByPrimaryKey(resource: AdminForthResource, recordId: string): Promise<any>;
createRecord({ resource, record, adminUser }: {
resource: AdminForthResource,
record: any
adminUser: AdminUser,
}): Promise<{ok: boolean, error?: string, createdRecord?: any}>;
updateRecord({ resource, recordId, newValues }: {
resource: AdminForthResource,
recordId: string,
newValues: any,
}): Promise<{ok: boolean, error?: string}>;
getMinMaxForColumns({ resource, columns }: { resource: AdminForthResource, columns: AdminForthResourceColumn[] }): Promise<ColumnMinMaxValue>;
deleteMany?({resource, recordIds}:{resource: AdminForthResource, recordIds: any[]}): Promise<number>;
aggregate({ resource, filters, aggregations, groupBy }: {
resource: AdminForthResource,
filters: IAdminForthAndOrFilter,
aggregations: { [alias: string]: IAggregationRule },
groupBy?: IGroupByRule | IGroupByRule[],
}): Promise<Array<{ group?: string, [key: string]: any }>>;
}
export interface IAdminForthDataSourceConnectorConstructor {
new (): IAdminForthDataSourceConnectorBase;
}
/**
* Result of {@link IAdminForthAuth.authorizeByCookies}.
* Statuses are separated because caller decides how to answer: authenticated endpoints answer 401 on any
* non-ok status except `verifyFailed` (which is a server side problem and must not logout user),
* while noAuth endpoints just treat caller as anonymous.
*/
export type AdminUserAuthorizationResult =
| { status: 'ok', adminUser: AdminUser }
/** no auth cookie in request at all */
| { status: 'noToken' }
/** jwt is expired, malformed or its user does not exist anymore */
| { status: 'invalidToken' }
/** verification itself failed, e.g. database is not ready yet */
| { status: 'verifyFailed', error: any }
/** one of `adminUserAuthorize` hooks denied the user */
| { status: 'notAllowed', error?: string };
export interface IAdminForthAuth {
verify(jwt : string, mustHaveType: string, decodeUser?: boolean): Promise<any>;
/**
* Takes auth jwt from cookies, verifies it and runs `adminUserAuthorize` hooks.
*/
authorizeByCookies({ cookies, response, extra }: {
cookies: {key: string, value: string}[],
response: IAdminForthHttpResponse,
extra: HttpExtra,
}): Promise<AdminUserAuthorizationResult>;
/**
* Runs `adminUserAuthorize` hooks for already authenticated user.
*/
runAdminUserAuthorizeHooks(adminUser: AdminUser, response: IAdminForthHttpResponse, extra: HttpExtra): Promise<{ allowed: boolean, error?: string }>;
/**
* Returns auth jwt from cookies, or null if it is not there.
*/
getAuthCookie(cookies: {key: string, value: string}[]): string | null;
issueJWT(payload: Object, type: string, expiresIn?: string | number): string;
removeCustomCookie({response, name}: {response: any, name: string}): void;
setCustomCookie({response, payload}: {response: any, payload: {name: string, value: string, expiry?: number, expirySeconds: number, httpOnly: boolean}}): void;
getCustomCookie({cookies, name}: {cookies: {key: string, value: string}[], name: string}): string | null;
setAuthCookie({expireInDuration, response, username, pk,}: {expireInDuration?: string, response: any, username: string, pk: string}): void;
removeAuthCookie(response: any): void;
getClientIp(headers: any): string;
}
export interface IAdminForthRestAPI {
/**
* Called by AdminForth to initialize all endpoints for REST API.
*/
registerEndpoints(server: IHttpServer): void;
/**
* Called by login endpoint to process login callbacks. Also might be called by plugins, to prevent action if user is not allowed to login.
* For example signup or login via google might want to check if user is allowed to login by calling this method.
* @param adminUser - plugin/af pases current adminUser
* @param toReturn - this is an object which will get status of login process. If at least one callback returns error or redirectTo, login process will be stopped (future callbacks will not be called).
* @param response - http response object
* @param sessionDuration - duration of session in format "1s", "1m", "1h", or "1d" (e.g., "30d" for 30 days)
*/
processLoginCallbacks(adminUser: AdminUser, toReturn: { redirectTo?: string, allowedLogin: boolean, error?: string }, response: any, extra: HttpExtra, sessionDuration?: string): Promise<void>;
}
export interface IAdminForth {
config: AdminForthConfig;
codeInjector: ICodeInjector;
express: IExpressHttpServer;
openApi: IOpenApiRegistry;
restApi: IAdminForthRestAPI;
activatedPlugins: Array<IAdminForthPlugin>;
websocket: IWebSocketBroker;
statuses: {
dbDiscover: 'running' | 'done',
};
connectors: {
[key: string]: IAdminForthDataSourceConnectorBase;
};
formatAdminForth(): string;
tr(msg: string, category: string, lang: string, params: any, pluralizationNumber?: number): Promise<string>;
createResourceRecord(
params: CreateResourceRecordParams,
): Promise<CreateResourceRecordResult>;
updateResourceRecord(
params: UpdateResourceRecordParams,
): Promise<UpdateResourceRecordResult>;
deleteResourceRecord(
params: DeleteResourceRecordParams,
): Promise<DeleteResourceRecordResult>;
auth: IAdminForthAuth;
/**
* Internal flag which indicates if AdminForth is running in hot reload mode.
*/
runningHotReload: boolean;
/**
* Connects to databases defined in datasources and fetches described resource columns to find out data types and constraints.
* You must call this method as soon as possible after AdminForth class is instantiated.
*/
discoverDatabases(): Promise<void>;
/**
* Bundles AdminForth SPA by injecting custom components into internal pre-made SPA source code. It generates internally dist which then will be
* served by AdminForth HTTP adapter.
* Bundle is generated in /tmp folder so if you have ramfs or tmpfs this operation will be faster.
*
* We recommend calling this method from dedicated script which will be run by CI/CD pipeline in build time. This ensures lowest downtime for your users.
* However for simple setup you can call it from your main script, and users will see some "AdminForth is bundling" message in the admin panel while app is bundling.
*/
bundleNow({ hotReload, buildTime }: { hotReload: boolean, buildTime: boolean }): Promise<void>;
/**
* Resource to get access to operational resources for data api fetching and manipulation.
*/
resource(resourceId: string): IOperationalResource;
/**
* This method will be automatically called from AdminForth HTTP adapter to serve AdminForth SPA.
*/
setupEndpoints(server: IHttpServer): void;
/**
* This method can be used when you want to get some plugin instances by class name.
* Should be used for plugins which might have multiple instances with the same class name.
* @param className - name of class which is used to identify plugin instance
*/
getPluginsByClassName<T>(className: string): T[];
/**
* This method can be used when you want to get some plugin instance by class name.
* Should be called only if you are sure there is only one plugin instance with this class name.
* If several instances are found, this method will drop error.
* @param className - name of class which is used to identify plugin instance
*
* Example:
*
* ```ts
* const i18nPlugin = adminforth.getPluginByClassName\<I18nPlugin\>('I18nPlugin');
* ```
*
*/
getPluginByClassName<T>(className: string): T;
/**
*This method can be used when you want to get a plugin instance by its unique identifier.
* @param id - unique id of the plugin instance (custom identifier passed when registering/configuring the plugin)
*
* Example:
* ```ts
* const auditLog = adminforth.getPluginById<AuditLogPlugin>('AuditLogPlugin');
* ```
*/
getPluginById<T>(id: string): T;
registerMenuContribution(contribution: AdminForthMenuContribution): void;
registerMenuContributionProvider(provider: AdminForthMenuContributionProvider): void;
getMenuContributions(): AdminForthMenuContribution[];
getMenuWithContributions(adminUser?: AdminUser, menu?: AdminForthConfigMenuItem[]): Promise<AdminForthConfigMenuItem[]>;
refreshMenu(adminUser: AdminUser): Promise<void>;
refreshMenuBadge(menuItemId: string, adminUser: AdminUser): Promise<void>;
}
export type AdminForthMenuContributionProvider = (ctx: {
adminUser?: AdminUser,
adminforth: IAdminForth,
}) => AdminForthMenuContribution[] | Promise<AdminForthMenuContribution[]>;
export interface IAdminForthPlugin {
adminforth: IAdminForth;
pluginDir: string;
customFolderName: string;
pluginInstanceId: string;
customFolderPath: string;
pluginOptions: any;
resourceConfig: AdminForthResource;
className: string;
pluginsScope: 'resource' | 'global';
/**
* Before activating all plugins are sorted by this number and then activated in order.
* If you want to make sure that your plugin is activated after some other plugin, set this number to higher value. (default is 0)
*/
activationOrder: number;
/**
* AdminForth plugins concept is based on modification of full AdminForth configuration
* to add some custom functionality. For example plugin might simply add custom field to resource by reusing
* {@link AdminForthResourceColumn.components} object, then add some hook which will modify record before getting or saving it to database.
*
* So this method is core of AdminForth plugins. It allows to modify full resource configuration.
* @param adminforth Instance of IAdminForth
* @param resourceConfig Resource configuration object which will be modified by plugin
*/
modifyResourceConfig?(adminforth: IAdminForth, resourceConfig: AdminForthResource, allPluginInstances?: {pi: IAdminForthPlugin, resource: AdminForthResource}[]): void;
/**
* This method is used for plugins, applied in global scope (pluginsScope = 'global')
* @param adminforth Instance of IAdminForth
*/
modifyGlobalConfig?(adminforth: IAdminForth): void;
componentPath(componentFile: string): string;
/**
* If plugin should support multiple installations per one resource, this function that should return unique string for each instance of plugin.
* For example if plugin is installed for one column and this column defined as
* `targetColumn` in plugin options, then this method should return `${pluginOptions.targetColumn}`.
*
* If plugin should support only one installation per resource, option can return 'single'
* @param pluginOptions - options of plugin
*/
instanceUniqueRepresentation(pluginOptions: any) : string;
/**
* If this method returns true, AdminForth will allow only one instance of plugin per whole app
* (only for case when we are creating copy of resource and activating plugins)
* If false, multiple instances of plugin can be installed on different resources.
*/
shouldHaveSingleInstancePerWholeApp?(): boolean;
/**
* Optional method which will be called after AdminForth discovers all resources and their columns.
* Can be used to validate types of columns, check if some columns are missing, etc.
*/
validateConfigAfterDiscover?(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
/**
* Here you can register custom endpoints for your plugin.
*
* @param server
*/
setupEndpoints(server: IHttpServer): void;
}
/**
* Modify query to change how data is fetched from database.
* Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
*/
export type BeforeDataSourceRequestFunction = (params: {
resource: AdminForthResource,
adminUser: AdminUser,
query: any,
extra: {
body: any,
query: Record<string, string>,
headers: Record<string, string>,
cookies: { key: string, value: string }[],
requestUrl: string,
},
filtersTools: any,
adminforth: IAdminForth,
}) => Promise<{
ok: boolean,
error?: string | null,
/**
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use redirectToRecordId instead.
*/
newRecordId?: string,
redirectToRecordId?: string
}>;
/**
* Modify response to change how data is returned after fetching from database.
* Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
*/
export type AfterDataSourceResponseFunction = (params: {
resource: AdminForthResource,
adminUser: AdminUser,
query: any,
response: any,
extra: {
body: any,
query: Record<string, string>,
headers: Record<string, string>,
cookies: { key: string, value: string }[],
requestUrl: string,
},
adminforth: IAdminForth,
}) => Promise<{ok: boolean, error?: string}>;
export interface HttpExtra {
body: any,
query: Record<string, string>,
headers: Record<string, string>,
cookies: { key: string, value: string }[],
requestUrl: string,
meta?: any,
response: IAdminForthHttpResponse
}
/**
* Result of {@link IAdminForth.createResourceRecord}.
*/
export type CreateResourceRecordResult = {
/** Optional error message if creation failed. */
error?: string;
/** Created record as returned from the connector. */
createdRecord?: any;
/**
* Optional id of an existing record to redirect to
* (used when a beforeSave hook aborts creation and supplies newRecordId, allows to implement programmatic creation via API).
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use redirectToRecordId instead.
*/
newRecordId?: any;
/**
* Optional id of an existing record to redirect to
* (used when a beforeSave hook aborts creation and supplies redirectToRecordId, allows to implement programmatic creation via API).
*/
redirectToRecordId?: any;
};
/**
* Parameters for {@link IAdminForth.createResourceRecord}.
*/
export type CreateResourceRecordParams = {
/**
* Resource configuration used to create a record.
*/
resource: AdminForthResource;
/**
* Record data to create.
*/
record: any;
/**
* Admin user performing the action.
*/
adminUser: AdminUser;
/**
* HTTP response object.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use extra.response instead.
*/
response?: IAdminForthHttpResponse;
/**
* Extra HTTP information. Prefer using extra.response over the top-level response field.
*/
extra?: HttpExtra;
};
/**
* Parameters for {@link IAdminForth.updateResourceRecord}.
*/
export type UpdateResourceRecordParams =
| {
/**
* Resource configuration used to update a record.
*/
resource: AdminForthResource;
/**
* Primary key value of the record to update.
*/
recordId: any;
/**
* Full record data with applied changes.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use updates instead.
*/
record: any;
/**
* Record data before update.
*/
oldRecord: any;
/**
* Admin user performing the action.
*/
adminUser: AdminUser;
/**
* HTTP response object.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use extra.response instead.
*/
response?: IAdminForthHttpResponse;
/**
* Extra HTTP information. Prefer using extra.response over the top-level response field.
*/
extra?: HttpExtra;
/**
* Partial record data with only changed fields. Mutually exclusive with record.
*/
updates?: never;
}
| {
/**
* Resource configuration used to update a record.
*/
resource: AdminForthResource;
/**
* Primary key value of the record to update.
*/
recordId: any;
/**
* Full record data with applied changes.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use updates instead.
*/
record?: never;
/**
* Record data before update.
*/
oldRecord: any;
/**
* Admin user performing the action.
*/
adminUser: AdminUser;
/**
* HTTP response object.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use extra.response instead.
*/
response?: IAdminForthHttpResponse;
/**
* Extra HTTP information. Prefer using extra.response over the top-level response field.
*/
extra?: HttpExtra;
/**
* Partial record data with only changed fields. Mutually exclusive with record.
*/
updates: any;
};
/**
* Parameters for {@link IAdminForth.deleteResourceRecord}.
*/
export type DeleteResourceRecordParams = {
/**
* Resource configuration used to delete a record.
*/
resource: AdminForthResource;
/**
* Primary key value of the record to delete.
*/
recordId: string;
/**
* Admin user performing the action.
*/
adminUser: AdminUser;
/**
* Record data before deletion.
*/
record: any;
/**
* HTTP response object.
*
* @deprecated Since 1.2.9. Will be removed in 4.0.0. Use extra.response instead.
*/
response?: IAdminForthHttpResponse;
/**
* Extra HTTP information. Prefer using extra.response over the top-level response field.
*/
extra?: HttpExtra;
};
/**
* Result of {@link IAdminForth.updateResourceRecord}.
*/
export type UpdateResourceRecordResult = {
/** Optional error message if update failed. */
error?: string;
};
/**
* Result of {@link IAdminForth.deleteResourceRecord}.
*/
export type DeleteResourceRecordResult = {
/** Optional error message if delete failed. */
error?: string;
};