@sdflc/backend-helpers 1.0.112 → 1.0.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +470 -33
  5. package/build/BaseCore.js +608 -127
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +599 -118
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -2
  135. package/build/esm/utils.js +23 -13
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -2
  197. package/build/utils.js +24 -16
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -64
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -58
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
@@ -0,0 +1,20 @@
1
+ import { Logger } from '@sdflc/utils';
2
+ import { BaseControllerPropsInterface } from './interfaces';
3
+ type OnResponseFn = (req: any, res: any, next: any) => Promise<void> | void;
4
+ /**
5
+ * Base class for REST API controllers.
6
+ */
7
+ declare class BaseController {
8
+ protected onResponse: OnResponseFn;
9
+ protected logger: Logger;
10
+ constructor(props?: BaseControllerPropsInterface);
11
+ init(_props?: any): void;
12
+ /**
13
+ * Wraps a controller method in consistent HTTP response handling.
14
+ * Supports OpResult, redirects, plain objects, and empty responses.
15
+ * @param method - Async handler receiving (req, res, next)
16
+ * @returns Express-compatible middleware function
17
+ */
18
+ json(method: (req: any, res: any, next: any) => Promise<any>): (req: any, res: any, next: any) => Promise<void>;
19
+ }
20
+ export { BaseController };
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseController = void 0;
7
+ // ./src/baseController.ts
8
+ const check_types_1 = __importDefault(require("check-types"));
9
+ const api_helpers_1 = require("@sdflc/api-helpers");
10
+ const utils_1 = require("@sdflc/utils");
11
+ /**
12
+ * Base class for REST API controllers.
13
+ */
14
+ class BaseController {
15
+ onResponse;
16
+ logger;
17
+ constructor(props) {
18
+ this.onResponse = check_types_1.default.function(props?.onResponse)
19
+ ? props.onResponse
20
+ : async (_req, _res, _next) => {
21
+ /* no-op */
22
+ };
23
+ this.logger = props?.logger && (0, utils_1.isLogger)(props.logger) ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
24
+ }
25
+ init(_props) {
26
+ // Implemented by subclasses to register routes on the Express app.
27
+ // Example:
28
+ // app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
29
+ }
30
+ /**
31
+ * Wraps a controller method in consistent HTTP response handling.
32
+ * Supports OpResult, redirects, plain objects, and empty responses.
33
+ * @param method - Async handler receiving (req, res, next)
34
+ * @returns Express-compatible middleware function
35
+ */
36
+ json(method) {
37
+ return async (req, res, next) => {
38
+ try {
39
+ const result = await method(req, res, next);
40
+ if ((0, api_helpers_1.isOpResult)(result)) {
41
+ res.status(result.getHttpStatus()).json(result.toJS());
42
+ }
43
+ else if (result?.redirectUrl) {
44
+ // Do NOT call next() after redirect — response is already finalised
45
+ res.redirect(result.redirectUrl);
46
+ return;
47
+ }
48
+ else if (result) {
49
+ res.status(200).json(result);
50
+ }
51
+ else {
52
+ // 204 No Content — no body should be sent
53
+ res.status(204).end();
54
+ }
55
+ await this.onResponse(req, res, next);
56
+ }
57
+ catch (ex) {
58
+ this.logger.log(`An exception occurred processing '${req.method} ${req.originalUrl}'`);
59
+ next(ex);
60
+ }
61
+ };
62
+ }
63
+ }
64
+ exports.BaseController = BaseController;
@@ -2,87 +2,524 @@ import { OpResult } from '@sdflc/api-helpers';
2
2
  import { Logger, MeasureTool } from '@sdflc/utils';
3
3
  import { ID_TYPES } from './constants';
4
4
  import { Database } from './Database';
5
- import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface, JwtTokenSecretAndSettings, ApiContext, ExtractCredentialsArgs, ListArgsInterface } from './interfaces';
5
+ import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface, BaseCoreValidatorsInterface, JwtTokenSecretAndSettings, ApiContext, ExtractCredentialsArgs, ListArgsInterface } from './interfaces';
6
+ /**
7
+ * BaseCore is the foundation for all business-logic core classes.
8
+ *
9
+ * A core sits between the transport layer (GraphQL resolvers, REST controllers)
10
+ * and the data layer (gateways). It is responsible for:
11
+ * - Authentication and authorisation (via `runAction`)
12
+ * - Input validation (via validator functions)
13
+ * - Database transaction management
14
+ * - Calling gateway methods and transforming results
15
+ * - Consistent error handling and OpResult wrapping
16
+ *
17
+ * Cores are instantiated per-request and receive a full `BaseCorePropsInterface`
18
+ * including the ApiContext, db, logger, auth config, etc.
19
+ *
20
+ * Subclasses typically override:
21
+ * - `getValidators()` — to provide custom validation per action
22
+ * - `before*` / `after*` — to transform inputs/outputs per action
23
+ * - `processItemOnIn()` — to normalise inbound data
24
+ * - `processItemOnOut()` — to shape outbound data
25
+ * - `authenticate()` — to implement custom auth strategies
26
+ * - `getJwtTokenSecretAndSettings()` — to resolve JWT config per space/tenant
27
+ * - `onException()` — to customise exception messages
28
+ * - `getFilterToSetOrderNo()` — to scope orderNo sequences to a parent entity
29
+ */
6
30
  declare class BaseCore {
7
31
  protected measureTool: MeasureTool;
8
32
  protected config: BaseCorePropsInterface;
9
33
  protected logger: Logger;
10
34
  constructor(props: BaseCorePropsInterface);
35
+ /**
36
+ * Returns the ID type this core operates with (UUID, integer, etc.).
37
+ * Defaults to ID_TYPES.UNKNOWN if not configured.
38
+ * Used by consumers that need to validate or coerce ID formats.
39
+ */
11
40
  getIdType(): ID_TYPES;
41
+ /**
42
+ * Returns the Database instance from config.
43
+ * Used for transaction management and raw query access.
44
+ */
12
45
  getDb(): Database;
46
+ /**
47
+ * Returns the requestId from the current ApiContext.
48
+ * Used to detect same-request calls (see `sameRequest` logic in runAction).
49
+ */
13
50
  getRequestId(): string;
51
+ /**
52
+ * Returns the full ApiContext for this request.
53
+ * Contains userId, spaceId, gateways, cores, headers, etc.
54
+ */
14
55
  getContext(): ApiContext;
15
- getGateways(): any;
56
+ /**
57
+ * Returns all gateway instances from the current request context.
58
+ * Returns an empty object if context or gateways are not available.
59
+ */
60
+ getGateways(): Record<string, any>;
61
+ /**
62
+ * Returns a single gateway by name.
63
+ * Falls back to `config.gatewayName` if no name is provided.
64
+ * Returns undefined if the gateway does not exist in context.
65
+ */
16
66
  getGateway(name?: string): any;
17
- getValidators(): any;
67
+ /**
68
+ * Returns the validator map for this core.
69
+ * Override in subclasses to provide custom validators per action.
70
+ *
71
+ * Each validator is a function (or async function) that receives
72
+ * `(args, actionOpt)` and returns `[result, validatedItems]` where:
73
+ * - result === true means validation passed
74
+ * - result is a validation error object if validation failed
75
+ * - validatedItems is an optional object of pre-fetched/validated data
76
+ * that will be merged into actionOpt for the action handler
77
+ */
78
+ getValidators(): BaseCoreValidatorsInterface;
79
+ /**
80
+ * Wraps data in a successful OpResult and returns its plain JS representation.
81
+ *
82
+ * Always returns data as an array — single objects are wrapped in `[data]`.
83
+ * Empty/null data returns an empty array with OK status.
84
+ *
85
+ * @param data The data to include in the result
86
+ * @param code Optional result code (defaults to OP_RESULT_CODES.OK)
87
+ */
18
88
  success(data: any, code?: number): any;
89
+ /**
90
+ * Creates a failed OpResult with a single error message.
91
+ *
92
+ * @param code Result code (e.g. OP_RESULT_CODES.NOT_FOUND)
93
+ * @param errorMsg Human-readable error description
94
+ * @param data Optional data payload to include alongside the error
95
+ */
19
96
  failure(code: number, errorMsg: string, data?: any): any;
97
+ /**
98
+ * Creates a validation-failed OpResult from a validation error object.
99
+ *
100
+ * Handles two cases:
101
+ * - If `ex` is already an OpResult, returns a plain VALIDATION_FAILED result
102
+ * (the original OpResult's errors are not re-wrapped to avoid duplication)
103
+ * - Otherwise, iterates `ex.errors` (checkit library format) and adds each
104
+ * field's error messages individually, supporting both single and multiple
105
+ * rule failures per field
106
+ */
20
107
  validationFailure(ex: OpResult | any): any;
108
+ /**
109
+ * Creates an exception-failed OpResult from a caught error.
110
+ *
111
+ * Distinguishes between database errors (returned to the client with the
112
+ * DB-level message) and application errors (logged internally, generic
113
+ * message returned to the client to avoid leaking implementation details).
114
+ *
115
+ * Note: uses `isExOpResult` instead of `isOpResult` to avoid shadowing
116
+ * the imported `isOpResult` utility function.
117
+ *
118
+ * @param ex The caught exception
119
+ * @param doingWhat Description of the operation that failed (for logging)
120
+ * @param data Optional data payload to include in the result
121
+ */
21
122
  exceptionFailure(ex: any, doingWhat: string, data?: any): any;
123
+ /**
124
+ * Commits or rolls back the active database transaction based on the action result.
125
+ *
126
+ * Called at the end of every `runAction()` flow, including in the catch block.
127
+ * Does nothing if `hasTransaction` is false or if `sameRequest` is true
128
+ * (same-request calls share their caller's transaction).
129
+ *
130
+ * `skipCheckResult` forces a commit regardless of result code — useful for
131
+ * operations where the caller has already verified correctness and just needs
132
+ * the transaction closed (e.g. after a manual rollback-and-retry pattern).
133
+ */
22
134
  checkResult(args: any): Promise<void>;
135
+ /**
136
+ * Core action runner. All public CRUD methods delegate to this.
137
+ *
138
+ * Execution flow:
139
+ * 1. Detect same-request calls (skip transaction + auth for nested calls
140
+ * within the same request, identified by matching requestId)
141
+ * 2. Start DB transaction if `hasTransaction` is true
142
+ * 3. Authenticate the request (if `doAuth` is true) OR verify the space
143
+ * (if `requireSpace` is not false) — space verification is a lighter
144
+ * alternative to full auth for public-but-space-scoped operations
145
+ * 4. Check role-based access if `roles` array is provided
146
+ * 5. Run the validator function if provided — validator returns
147
+ * `[true, validatedItems]` on success or `[errorObj, {}]` on failure
148
+ * 6. Execute the action handler with `(args, { ...actionOpt, validatedItems })`
149
+ * 7. Commit or rollback the transaction via `checkResult()`
150
+ * 8. On any exception: rollback, call `onException()` and the caller's
151
+ * `onException` hook, then return an exceptionFailure result
152
+ *
153
+ * Same-request detection:
154
+ * When a core method calls another core method on the same request
155
+ * (e.g. create calling list to re-fetch results), it can pass
156
+ * `args.requestId = context.requestId`. The inner call detects this,
157
+ * skips starting a new transaction, skips auth, and skips committing —
158
+ * the outer call owns the transaction lifecycle.
159
+ *
160
+ * @param opt CoreActionInterface with all action configuration
161
+ */
23
162
  runAction(opt: CoreActionInterface): Promise<any>;
163
+ /**
164
+ * Lists records via the configured gateway.
165
+ *
166
+ * Calls `beforeList()` to transform filter args, then `afterList()` on results.
167
+ * Auth is controlled by `doAuthOnAction.list`.
168
+ * Does not use a DB transaction — list is a read-only operation.
169
+ */
24
170
  list(args: ListArgsInterface): Promise<any>;
171
+ /**
172
+ * Fetches a single record by id via the configured gateway.
173
+ *
174
+ * Calls `beforeGet()` to transform/validate the args object (which should
175
+ * contain an `id` field). Returns NOT_FOUND if:
176
+ * - beforeGet returns null/undefined id
177
+ * - the gateway returns no record for that id
178
+ *
179
+ * Does not use a DB transaction.
180
+ */
25
181
  get(args: any): Promise<any>;
182
+ /**
183
+ * Fetches multiple records by their ids via the configured gateway.
184
+ *
185
+ * Calls `beforeGetMany()` to transform the args object (which should
186
+ * contain an `ids` array). Returns NOT_FOUND if `ids` is not an array
187
+ * after the before-hook.
188
+ *
189
+ * Results are returned in DataLoader order (same order as input ids,
190
+ * with null entries for missing records). Does not use a DB transaction.
191
+ */
26
192
  getMany(args: any): Promise<any>;
193
+ /**
194
+ * Returns the gateway instance used for orderNo calculation.
195
+ * Override in subclasses to use a different gateway than the default one.
196
+ */
27
197
  getGatewayToSetOrerNo(): any;
28
- getFilterToSetOrderNo(args: any): {};
198
+ /**
199
+ * Returns the filter object used when querying for the last orderNo value.
200
+ * Override in subclasses to scope orderNo sequences to a parent entity
201
+ * (e.g. return `{ categoryId: params.categoryId }` to have per-category ordering).
202
+ */
203
+ getFilterToSetOrderNo(_args: any): Record<string, any>;
204
+ /**
205
+ * Creates a single record via the configured gateway.
206
+ *
207
+ * If `config.hasOrderNo` is true, auto-calculates the next orderNo value
208
+ * before calling `beforeCreate()`. Uses a DB transaction.
209
+ */
29
210
  create(args: any): Promise<any>;
211
+ /**
212
+ * Creates multiple records in a single gateway call.
213
+ *
214
+ * Calls `beforeCreateMany()` which maps each item through `processItemOnIn()`
215
+ * using `Promise.all` to correctly resolve async transforms.
216
+ * Uses a DB transaction.
217
+ */
30
218
  createMany(args: any): Promise<any>;
219
+ /**
220
+ * Updates a single record matching the `where` filter.
221
+ *
222
+ * `args` should contain `{ where, params }`:
223
+ * - `where` carries the filter (id, optional version for optimistic locking)
224
+ * - `params` carries the fields to update
225
+ *
226
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
227
+ * Uses a DB transaction.
228
+ */
31
229
  update(args: any): Promise<any>;
230
+ /**
231
+ * Updates multiple records, each with its own where/params pair.
232
+ *
233
+ * `args.params` should be an array of `{ where, params }` objects.
234
+ * Each is processed sequentially by the gateway's `updateMany()`.
235
+ * Uses a DB transaction.
236
+ */
32
237
  updateMany(args: any): Promise<any>;
238
+ /**
239
+ * Upserts one or more records via the gateway's `set()` method
240
+ * (INSERT ... ON CONFLICT ... MERGE).
241
+ *
242
+ * `args.params` can be a single object or array. Each item is passed
243
+ * through `processItemOnIn()` via `beforeSet()`.
244
+ * Uses a DB transaction.
245
+ */
33
246
  set(args: any): Promise<any>;
247
+ /**
248
+ * Soft- or hard-deletes a single record matching `args.where`.
249
+ *
250
+ * The actual delete behaviour (hard vs soft) is determined by gateway config.
251
+ * Returns NOT_FOUND if the gateway reports 0 affected records.
252
+ * Does not use a DB transaction (remove is typically a single atomic operation).
253
+ */
34
254
  remove(args: any): Promise<any>;
255
+ /**
256
+ * Removes multiple records matching `args.where`.
257
+ *
258
+ * Delegates to the gateway's `remove()` method (not `removeMany`) —
259
+ * the gateway's `onRemoveFilter` handles the multi-id WHERE clause.
260
+ * Does not use a DB transaction.
261
+ */
35
262
  removeMany(args: any): Promise<any>;
36
- defaultAfterAndBefore(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
37
263
  /**
38
- * Used to transform an object before sending it in the response
39
- * @param {any} item An object coming from the database
40
- * @param {BaseCoreActionsInterface} opt Options
41
- * @returns {any} transformed object
264
+ * Default identity transform used by all before/after hooks that have
265
+ * no specific logic. Simply returns the params unchanged.
266
+ * Override to add cross-cutting transforms that apply to all actions.
267
+ */
268
+ defaultAfterAndBefore(params: any, _opt?: BaseCoreActionsInterface): Promise<any>;
269
+ /**
270
+ * Transforms an outbound record (from DB to caller).
271
+ * Override to rename fields, attach computed properties, or strip sensitive data.
272
+ * Called by all after-* hooks via their Promise.all map loops.
42
273
  */
43
274
  processItemOnOut(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
44
275
  /**
45
- * Used to transform an object before processing it on the request
46
- * @param {any} item An object coming from the outside
47
- * @param {BaseCoreActionsInterface} opt Options
48
- * @returns {any} transformed object
276
+ * Transforms an inbound record (from caller to DB).
277
+ * Override to normalise fields, enforce defaults, or coerce types before writes.
278
+ * Called by all before-* mutation hooks via their Promise.all map loops.
49
279
  */
50
280
  processItemOnIn(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
281
+ /**
282
+ * Transforms the args object before a get() call.
283
+ * The returned object should contain an `id` field.
284
+ * If it returns an OpResult, `get()` will return that OpResult directly.
285
+ */
51
286
  beforeGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
287
+ /**
288
+ * Transforms the args object before a getMany() call.
289
+ * The returned object should contain an `ids` array.
290
+ * If it returns an OpResult, `getMany()` will return that OpResult directly.
291
+ */
52
292
  beforeGetMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
293
+ /**
294
+ * Transforms the filter/args object before a list() call.
295
+ * Override to inject default filters, enforce scope restrictions, etc.
296
+ * If it returns an OpResult, `list()` will return that OpResult directly.
297
+ */
53
298
  beforeList(filter: any, opt?: BaseCoreActionsInterface): Promise<any>;
299
+ /**
300
+ * Transforms a single fetched record after get().
301
+ * Delegates to `processItemOnOut()`.
302
+ */
54
303
  afterGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
55
- afterGetMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
56
- afterList(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
304
+ /**
305
+ * Transforms fetched records after getMany().
306
+ * Maps each item through `processItemOnOut()` using Promise.all
307
+ * to correctly handle async transforms.
308
+ */
309
+ afterGetMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
310
+ /**
311
+ * Transforms fetched records after list().
312
+ * Maps each item through `processItemOnOut()` using Promise.all.
313
+ */
314
+ afterList(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
315
+ /**
316
+ * Transforms a single record before create().
317
+ * Delegates to `processItemOnIn()`.
318
+ */
57
319
  beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
58
- afterCreate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
59
- beforeCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
60
- afterCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
320
+ /**
321
+ * Transforms created records after create().
322
+ * Maps each item through `processItemOnOut()` using Promise.all.
323
+ */
324
+ afterCreate(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
325
+ /**
326
+ * Transforms an array of records before createMany().
327
+ * Maps each item through `processItemOnIn()` using Promise.all
328
+ * to correctly resolve async transforms.
329
+ *
330
+ * Fix: was using .map() without Promise.all, returning Promise[]
331
+ * instead of resolved values.
332
+ */
333
+ beforeCreateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
334
+ /**
335
+ * Transforms created records after createMany().
336
+ * Maps each item through `processItemOnOut()` using Promise.all.
337
+ */
338
+ afterCreateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
339
+ /**
340
+ * Transforms a single record before update().
341
+ * Delegates to `processItemOnIn()`.
342
+ */
61
343
  beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
62
- afterUpdate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
63
- beforeUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
64
- afterUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
344
+ /**
345
+ * Transforms updated records after update().
346
+ * Maps each item through `processItemOnOut()` using Promise.all.
347
+ */
348
+ afterUpdate(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
349
+ /**
350
+ * Transforms an array of { where, params } objects before updateMany().
351
+ * Maps each item's `params` through `processItemOnIn()` while preserving
352
+ * the `where` filter unchanged.
353
+ *
354
+ * Fix: was using .map() without Promise.all, returning Promise[]
355
+ * instead of resolved values.
356
+ */
357
+ beforeUpdateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
358
+ /**
359
+ * Transforms updated records after updateMany().
360
+ * Maps each item through `processItemOnOut()` using Promise.all.
361
+ */
362
+ afterUpdateMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
363
+ /**
364
+ * Transforms params before set() (upsert).
365
+ * Normalises params to an array via castArray, then maps each item
366
+ * through `processItemOnIn()` using Promise.all.
367
+ *
368
+ * Fix: was using .map() without Promise.all, returning Promise[]
369
+ * instead of resolved values.
370
+ */
65
371
  beforeSet(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
66
- afterSet(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
372
+ /**
373
+ * Transforms upserted records after set().
374
+ * Maps each item through `processItemOnOut()` using Promise.all.
375
+ */
376
+ afterSet(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
377
+ /**
378
+ * Transforms the where filter before remove().
379
+ * Override to add ownership checks or enrich the filter before deletion.
380
+ * If it returns an OpResult, `remove()` returns that OpResult directly.
381
+ */
67
382
  beforeRemove(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
68
- afterRemove(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
383
+ /**
384
+ * Transforms removed records after remove().
385
+ * Maps each item through `processItemOnOut()` using Promise.all.
386
+ */
387
+ afterRemove(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
388
+ /**
389
+ * Transforms the where filter before removeMany().
390
+ * Same contract as beforeRemove() but for bulk removal.
391
+ */
69
392
  beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
70
- afterRemoveMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
71
- onException(params: any, opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
72
393
  /**
73
- * Returns JWT secret and its settings to verify received JWT token
74
- * @param params Object of parameters passed to the authenticate method
75
- * @returns Object with the jwtSecret and verifyTokenArgs
394
+ * Transforms removed records after removeMany().
395
+ * Maps each item through `processItemOnOut()` using Promise.all.
396
+ */
397
+ afterRemoveMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
398
+ /**
399
+ * Called when `runAction()` catches an unhandled exception.
400
+ * Override to return a custom human-readable error message for specific
401
+ * exception types, or to trigger side effects (e.g. alert notifications).
402
+ *
403
+ * Return an empty string or null to let the default error handling apply.
404
+ * The caller's `onException` hook (passed to runAction) is called after this.
405
+ */
406
+ onException(_params: any, _opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
407
+ /**
408
+ * Returns the JWT secret and verification settings for the current request.
409
+ * Called by `authenticate()` to resolve auth config per space/tenant.
410
+ *
411
+ * Override to implement per-space token secrets, custom algorithms,
412
+ * or audience/issuer values derived from the request context.
413
+ *
414
+ * @param _params The args object passed to the action being authenticated
415
+ */
416
+ getJwtTokenSecretAndSettings(_params: any): Promise<JwtTokenSecretAndSettings>;
417
+ /**
418
+ * Resolves the current space from context or via the spaceGw gateway.
419
+ *
420
+ * Returns `[true, space]` on success, `[false, errorMessage]` on failure.
421
+ *
422
+ * Resolution order:
423
+ * 1. If `context.space` is already populated, return it immediately
424
+ * (avoids a redundant DB lookup on subsequent calls within the same request)
425
+ * 2. If `spaceGw` is configured, look up the space by `context.spaceId`
426
+ * 3. If no `spaceGw` is configured, return `[true, null]` —
427
+ * callers must handle the null space case
428
+ *
429
+ * Side effect: on successful lookup, `context.space` is populated for
430
+ * future calls within the same request.
76
431
  */
77
- getJwtTokenSecretAndSettings(params: any): Promise<JwtTokenSecretAndSettings>;
78
432
  findSpace(): Promise<any[]>;
433
+ /**
434
+ * Extracts the authentication token and fingerprint from the request.
435
+ * Called by `authenticate()` before token verification.
436
+ *
437
+ * Token resolution order:
438
+ * 1. Cookie named `space.cookieName`
439
+ * 2. Authorization header
440
+ * 3. `authorization` from context (passed explicitly, e.g. from API gateway)
441
+ *
442
+ * Fingerprint resolution order:
443
+ * 1. Cookie named `space.fingerprintCookieName`
444
+ * 2. X-Fingerprint header
445
+ * 3. `args.fingerprint` passed to the function
446
+ *
447
+ * Override to support additional token sources (e.g. query string tokens
448
+ * for WebSocket connections, or custom header schemes).
449
+ */
79
450
  extractCredentials(args: ExtractCredentialsArgs): Promise<{
80
- token: any;
81
- fingerprint: any;
451
+ token: string;
452
+ fingerprint: string;
82
453
  }>;
83
- authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<any[]>;
454
+ /**
455
+ * Authenticates the current request.
456
+ * Called by `runAction()` when `doAuth` is true.
457
+ *
458
+ * Returns `[true, '']` on success, `[false, errorMessage]` on failure.
459
+ *
460
+ * Authentication flow:
461
+ * 1. Resolve the current space via `findSpace()`
462
+ * 2. Extract token + fingerprint via `extractCredentials()`
463
+ * 3. Resolve JWT secret via `getJwtTokenSecretAndSettings()`
464
+ * 4. If a token and secret are present, verify the JWT:
465
+ * - On success: populate context with accountId, roleId, userId,
466
+ * isSuperAdmin, spaceId, lang from token payload
467
+ * - On failure: return the verification error
468
+ * 5. If no token was present, fall back to API key auth:
469
+ * - Interservice API key (config.interserviceApiKey) for service-to-service calls
470
+ * - Space API key (space.apiKey) for public API access
471
+ * - If neither matches: return 'No authentication provided'
472
+ *
473
+ * Note: context.spaceId is only set from the token if not already present
474
+ * in context (header value takes precedence). context.lang defaults to
475
+ * empty string if neither requestedLang nor tokenData.lang is available.
476
+ *
477
+ * Override to add MFA checks, session validation, or custom token formats.
478
+ */
479
+ authenticate(params: any, _opt?: BaseCoreActionsInterface): Promise<any[]>;
480
+ /**
481
+ * Strips the removal suffix from a soft-deleted record's id.
482
+ *
483
+ * When a record is soft-deleted with `hasLang`, the gateway appends
484
+ * a timestamp to the id (e.g. "my-slug_en-20240101T120000+0000") to free
485
+ * the original key for re-use. This method extracts the original id
486
+ * by splitting at '~'.
487
+ */
84
488
  processRemovedRecord(record: any): any;
85
- addRemovedModifierToFields(fields: string | string[]): any;
489
+ /**
490
+ * Builds a partial update object that appends a removal suffix to the
491
+ * specified fields using a raw DB expression.
492
+ *
493
+ * Used to "tombstone" unique fields (slugs, emails, etc.) when soft-deleting,
494
+ * freeing them for re-use on new records. The suffix includes a UUID to
495
+ * ensure uniqueness even if the same record is deleted multiple times.
496
+ *
497
+ * Example: `{ slug: db.raw("slug || '~removed~' || uuid_generate_v4()") }`
498
+ *
499
+ * @param fields A single field name or array of field names to tombstone
500
+ */
501
+ addRemovedModifierToFields(fields: string | string[]): Record<string, any>;
502
+ /**
503
+ * Calculates and sets the next `orderNo` value on `params` before a create.
504
+ * Called by `create()` when `config.hasOrderNo` is true.
505
+ *
506
+ * Queries the gateway for the last record (sorted by orderNo DESC, limit 1)
507
+ * using the provided filter, then increments by `DEFAULT_ORDER_NO_STEP`.
508
+ *
509
+ * Supports two ordering strategies via `config.orderNoAsDecimal`:
510
+ * - `true` — numeric ordering (e.g. 10, 20, 30)
511
+ * - `false` — lexicographic string ordering via StrOrderHelpers
512
+ * (e.g. "a", "b", "c" — useful for reordering without renumbering)
513
+ *
514
+ * Does nothing if `params.orderNo` is already set (non-null).
515
+ *
516
+ * Fix: changed `!params.orderNo` to `params.orderNo == null` to correctly
517
+ * handle the case where `orderNo` is explicitly set to `0`.
518
+ *
519
+ * @param args.params The params object to mutate with the orderNo value
520
+ * @param args.filter Filter to scope the orderNo sequence (e.g. by parentId)
521
+ * @param args.gateway Gateway instance to query for the current max orderNo
522
+ */
86
523
  setOrderNo(args: any): Promise<void>;
87
524
  }
88
525
  export { BaseCore };