@jskit-ai/crud-core 0.2.3 → 0.2.4

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 (48) hide show
  1. package/locales/en.json +2 -1
  2. package/package.json +7 -7
  3. package/patterns/json-api-resource-package/PATTERN.md +102 -23
  4. package/patterns/json-api-resource-package/example/packages/books/package.json +3 -2
  5. package/patterns/json-api-resource-package/example/packages/books/src/server/types.js +5 -0
  6. package/src/server/createCrudServiceFromResource.js +14 -6
  7. package/src/server/createHooksToCollectChildren.js +123 -97
  8. package/src/server/defineCrudJsonApiFeature.js +40 -8
  9. package/src/server/fieldAccess.js +33 -25
  10. package/src/server/jsonApiModule/actions.js +151 -548
  11. package/src/server/jsonApiModule/assistantExtension.js +386 -0
  12. package/src/server/jsonApiModule/customActionId.js +12 -0
  13. package/src/server/jsonApiModule/repository.js +73 -21
  14. package/src/server/jsonApiModule/routes.js +44 -30
  15. package/src/server/jsonApiModule/service.js +37 -35
  16. package/src/server/jsonApiResourceContract.js +22 -18
  17. package/src/server/listFilterJsonRest.js +304 -0
  18. package/src/server/listFilterTypes.js +427 -0
  19. package/src/server/listFilters.js +26 -722
  20. package/src/server/listQueryValidators.js +26 -21
  21. package/src/server/lookupPathSupport.js +31 -18
  22. package/src/server/lookups.js +20 -34
  23. package/src/server/normalizeOptionalText.js +13 -0
  24. package/src/server/repositorySupport.js +11 -10
  25. package/src/server/resourceRuntime/compiledRuntime.js +284 -0
  26. package/src/server/resourceRuntime/index.js +167 -920
  27. package/src/server/resourceRuntime/listControls.js +333 -0
  28. package/src/server/resourceRuntime/lookupHydration.js +121 -186
  29. package/src/server/resourceRuntime/operationStages.js +140 -0
  30. package/src/server/resourceRuntime/recordValidation.js +65 -0
  31. package/src/server/routeContracts.js +44 -46
  32. package/src/server/serviceEvents.js +42 -118
  33. package/src/server/serviceMethods.js +34 -26
  34. package/src/server/types.js +156 -0
  35. package/test/assistantActionConformance.test.js +8 -5
  36. package/test/assistantPagination.integration.test.js +5 -3
  37. package/test/createCrudServiceFromResource.test.js +0 -18
  38. package/test/customActionId.test.js +12 -0
  39. package/test/defineCrudJsonApiFeature.test.js +193 -28
  40. package/test/errorCodes.test.js +18 -0
  41. package/test/jsonApiRepository.test.js +103 -3
  42. package/test/listFilters.test.js +7 -7
  43. package/test/listQueryValidators.test.js +1 -54
  44. package/test/serviceEvents.test.js +31 -81
  45. package/test/support/crudJsonApiActionOptions.js +37 -0
  46. package/src/server/crudModuleConfig.js +0 -181
  47. package/src/server/lookupHydration.js +0 -710
  48. package/test/crudModuleConfig.test.js +0 -33
@@ -1,62 +1,40 @@
1
1
  import {
2
2
  createWithTransaction,
3
3
  resolveInsertedRecordId,
4
+ resolveRepoClient,
4
5
  toInsertDateTime
5
6
  } from "@jskit-ai/database-runtime/shared";
6
7
  import { applyVisibility, applyVisibilityOwners } from "@jskit-ai/database-runtime/shared/visibility";
7
- import { AppError, createValidationError } from "@jskit-ai/kernel/server/runtime/errors";
8
- import { isRecord, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
8
+ import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
9
9
  import {
10
- DEFAULT_LIST_LIMIT,
11
- MAX_LIST_LIMIT,
12
- buildRepositoryColumnMetadata,
13
- deriveRepositoryMappingFromResource,
14
10
  normalizeCrudListLimit,
15
- requireCrudTableName,
16
11
  applyCrudListQueryFilters,
17
12
  buildWritePayload,
18
13
  mapRecordRow,
19
- resolveColumnName,
20
- resolveCrudIdColumn
14
+ resolveColumnName
21
15
  } from "../repositorySupport.js";
16
+ import { hydrateCrudLookupRecords } from "./lookupHydration.js";
17
+ import { CRUD_FIELD_STORAGE_COLUMN } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
22
18
  import {
23
- codedFieldErrors,
24
- resolveSchemaTransportSchemaDefinition,
25
- validateSchemaPayload
26
- } from "@jskit-ai/kernel/shared/validators";
19
+ applyCrudRepositoryVirtualProjections,
20
+ applyConfiguredQueryStage,
21
+ applyConfiguredObjectStage,
22
+ buildCrudRepositoryActionContextBase
23
+ } from "./operationStages.js";
27
24
  import {
28
- createCrudLookupRuntime,
29
- hydrateCrudLookupRecords
30
- } from "./lookupHydration.js";
31
- import { CRUD_FIELD_STORAGE_COLUMN } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
25
+ encodeOrderedListCursor,
26
+ applyOrderedListCursorFilter,
27
+ enforceCrudRepositoryListControls
28
+ } from "./listControls.js";
29
+ import {
30
+ normalizeRepositoryInputPayload,
31
+ normalizeRepositoryOutputRecord
32
+ } from "./recordValidation.js";
33
+ import { buildCompiledCrudRepositoryRuntime } from "./compiledRuntime.js";
32
34
 
33
- const LIST_ORDER_DIRECTION_ASC = "asc";
34
- const LIST_ORDER_DIRECTION_DESC = "desc";
35
- const LIST_ORDER_NULLS_FIRST = "first";
36
- const LIST_ORDER_NULLS_LAST = "last";
37
- const ORDERED_LIST_CURSOR_VALUE_TYPE_KEY = "__jskitCursorValueType";
38
- const ORDERED_LIST_CURSOR_VALUE_KEY = "value";
39
- const ORDERED_LIST_CURSOR_VALUE_TYPE_DATE = "date";
40
- const REPOSITORY_OPERATION_KEYS = Object.freeze([
41
- "read",
42
- "list",
43
- "findById",
44
- "listByIds",
45
- "create",
46
- "updateById",
47
- "deleteById"
48
- ]);
49
- const REPOSITORY_OPERATION_STAGE_KEYS = Object.freeze({
50
- read: ["applyQuery"],
51
- list: ["applyQuery"],
52
- findById: ["applyQuery"],
53
- listByIds: ["applyQuery"],
54
- create: ["preparePayload", "prepareInsertPayload", "applyQuery"],
55
- updateById: ["preparePatch", "applyQuery"],
56
- deleteById: ["applyQuery"]
57
- });
35
+ /** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} RuntimeKnex */
58
36
 
59
- function requireCrudRecordId(value, { context = "crudRepository" } = {}) {
37
+ function requireCrudRecordId(value, { context }) {
60
38
  const recordId = normalizeRecordId(value, { fallback: null });
61
39
  if (!recordId) {
62
40
  throw new TypeError(`${context} requires recordId.`);
@@ -64,798 +42,44 @@ function requireCrudRecordId(value, { context = "crudRepository" } = {}) {
64
42
  return recordId;
65
43
  }
66
44
 
67
- function requireCrudRepositoryOptions(value = {}, { context = "crudRepository" } = {}) {
68
- if (!value || typeof value !== "object" || Array.isArray(value)) {
69
- throw new TypeError(`${context} requires repository options object when provided.`);
70
- }
71
-
72
- return value;
73
- }
74
-
75
- function resolveRepositoryDefaults(resource = {}, repositoryMapping = {}, { context = "crudRepository" } = {}) {
76
- const resourceName = normalizeText(resource.namespace);
77
- const tableName = normalizeText(resource.tableName) || resourceName;
78
- if (!tableName) {
79
- throw new TypeError(`${context} requires resource.tableName or resource.namespace.`);
80
- }
81
-
82
- const idColumn = normalizeText(resource.idColumn) || resolveColumnName("id", repositoryMapping.columnOverrides) || "id";
83
- const createdAtColumn = repositoryMapping.outputKeys.includes("createdAt") &&
84
- repositoryMapping.fieldStorageByKey?.createdAt === CRUD_FIELD_STORAGE_COLUMN
85
- ? resolveColumnName("createdAt", repositoryMapping.columnOverrides)
86
- : "";
87
- const updatedAtColumn = repositoryMapping.outputKeys.includes("updatedAt") &&
88
- repositoryMapping.fieldStorageByKey?.updatedAt === CRUD_FIELD_STORAGE_COLUMN
89
- ? resolveColumnName("updatedAt", repositoryMapping.columnOverrides)
90
- : "";
91
-
45
+ /**
46
+ * What one repository call reads and writes through: the call's transaction
47
+ * (else the repository's Knex), with the runtime's table and id column, and the
48
+ * visibility filter of the call's visibility context.
49
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
50
+ * @param {RuntimeKnex} knex
51
+ * @param {object} callOptions
52
+ */
53
+ function resolveCrudRepositoryCall(runtime, knex, callOptions) {
92
54
  return Object.freeze({
93
- tableName,
94
- idColumn,
95
- createdAtColumn,
96
- updatedAtColumn
55
+ client: resolveRepoClient(knex, callOptions),
56
+ tableName: runtime.tableName,
57
+ idColumn: runtime.idColumn,
58
+ visible: (queryBuilder) => applyVisibility(queryBuilder, callOptions.visibilityContext)
97
59
  });
98
60
  }
99
61
 
100
- function normalizeCrudVirtualFieldHandlers(
101
- virtualFields = {},
102
- repositoryMapping = {},
103
- { context = "crudRepository" } = {}
104
- ) {
105
- const expectedKeys = new Set(
106
- (Array.isArray(repositoryMapping?.virtualOutputKeys) ? repositoryMapping.virtualOutputKeys : [])
107
- .map((key) => normalizeText(key))
108
- .filter(Boolean)
109
- );
110
- if (expectedKeys.size < 1) {
111
- if (virtualFields === null || virtualFields === undefined) {
112
- return Object.freeze([]);
113
- }
114
- if (!virtualFields || typeof virtualFields !== "object" || Array.isArray(virtualFields)) {
115
- throw new TypeError(`${context} virtualFields must be an object when provided.`);
116
- }
117
- if (Object.keys(virtualFields).length > 0) {
118
- throw new Error(
119
- `${context} virtualFields contains registrations, but the resource does not declare any storage.virtual fields.`
120
- );
121
- }
122
- return Object.freeze([]);
123
- }
124
-
125
- if (!virtualFields || typeof virtualFields !== "object" || Array.isArray(virtualFields)) {
126
- throw new TypeError(`${context} virtualFields must be an object.`);
127
- }
128
-
129
- const normalizedHandlers = [];
130
- const seenKeys = new Set();
131
- for (const [rawKey, handlerConfig] of Object.entries(virtualFields)) {
132
- const key = normalizeText(rawKey);
133
- if (!key || seenKeys.has(key)) {
134
- continue;
135
- }
136
- if (!expectedKeys.has(key)) {
137
- throw new Error(
138
- `${context} virtualFields["${key}"] is unknown; declare the field in the resource schema with storage.virtual true.`
139
- );
140
- }
141
- if (!handlerConfig || typeof handlerConfig !== "object" || Array.isArray(handlerConfig)) {
142
- throw new TypeError(`${context} virtualFields["${key}"] must be an object.`);
143
- }
144
- if (typeof handlerConfig.applyProjection !== "function") {
145
- throw new TypeError(`${context} virtualFields["${key}"].applyProjection must be a function.`);
146
- }
147
-
148
- seenKeys.add(key);
149
- normalizedHandlers.push(Object.freeze({
150
- key,
151
- alias: resolveColumnName(key, repositoryMapping.columnOverrides),
152
- applyProjection: handlerConfig.applyProjection
153
- }));
154
- }
155
-
156
- for (const key of expectedKeys) {
157
- if (!seenKeys.has(key)) {
158
- throw new Error(
159
- `${context} resource output field "${key}" is virtual but no repository runtime projection was registered.`
160
- );
161
- }
162
- }
163
-
164
- return Object.freeze(normalizedHandlers);
165
- }
166
-
167
- function applyCrudRepositoryVirtualProjections(
168
- dbQuery,
169
- runtime = {},
170
- { knex, tableName } = {}
171
- ) {
172
- const virtualFields = Array.isArray(runtime?.virtualFields) ? runtime.virtualFields : [];
173
- if (virtualFields.length < 1) {
174
- return dbQuery;
175
- }
176
-
177
- for (const virtualField of virtualFields) {
178
- virtualField.applyProjection(dbQuery, {
179
- knex,
180
- tableName,
181
- alias: virtualField.alias,
182
- fieldKey: virtualField.key
183
- });
184
- }
185
-
186
- return dbQuery;
187
- }
188
-
189
- function normalizeSearchColumns(searchColumns = [], fallbackColumns = []) {
190
- const normalizedConfiguredColumns = (Array.isArray(searchColumns) ? searchColumns : [])
191
- .map((columnName) => String(columnName || "").trim())
192
- .filter(Boolean);
193
-
194
- if (normalizedConfiguredColumns.length > 0) {
195
- return Object.freeze([...new Set(normalizedConfiguredColumns)]);
196
- }
197
-
198
- return Object.freeze(
199
- (Array.isArray(fallbackColumns) ? fallbackColumns : [])
200
- .map((columnName) => String(columnName || "").trim())
201
- .filter(Boolean)
202
- );
203
- }
204
-
205
- function normalizeListOrderDirection(value = LIST_ORDER_DIRECTION_ASC) {
206
- const normalized = normalizeText(value).toLowerCase();
207
- if (!normalized) {
208
- return LIST_ORDER_DIRECTION_ASC;
209
- }
210
- if (normalized === LIST_ORDER_DIRECTION_ASC || normalized === LIST_ORDER_DIRECTION_DESC) {
211
- return normalized;
212
- }
213
-
214
- throw new TypeError(`crudRepository list.orderBy direction must be "${LIST_ORDER_DIRECTION_ASC}" or "${LIST_ORDER_DIRECTION_DESC}".`);
215
- }
216
-
217
- function normalizeListOrderNulls(value = LIST_ORDER_NULLS_LAST) {
218
- const normalized = normalizeText(value).toLowerCase();
219
- if (!normalized) {
220
- return LIST_ORDER_NULLS_LAST;
221
- }
222
- if (normalized === LIST_ORDER_NULLS_FIRST || normalized === LIST_ORDER_NULLS_LAST) {
223
- return normalized;
224
- }
225
-
226
- throw new TypeError(`crudRepository list.orderBy nulls must be "${LIST_ORDER_NULLS_FIRST}" or "${LIST_ORDER_NULLS_LAST}".`);
227
- }
228
-
229
- function normalizeListOrderBy(orderBy = [], { idColumn = "id" } = {}) {
230
- const sourceEntries = Array.isArray(orderBy)
231
- ? orderBy
232
- : orderBy === null || orderBy === undefined
233
- ? []
234
- : [orderBy];
235
- const normalizedIdColumn = normalizeText(idColumn) || "id";
236
- const normalizedOrderBy = [];
237
- const seenColumns = new Set();
238
-
239
- for (const rawEntry of sourceEntries) {
240
- const sourceEntry = typeof rawEntry === "string"
241
- ? { column: rawEntry }
242
- : rawEntry;
243
- if (!sourceEntry || typeof sourceEntry !== "object" || Array.isArray(sourceEntry)) {
244
- throw new TypeError("crudRepository list.orderBy entries must be objects or column strings.");
245
- }
246
-
247
- const column = normalizeText(sourceEntry.column);
248
- if (!column) {
249
- throw new TypeError("crudRepository list.orderBy entries require column.");
250
- }
251
- if (seenColumns.has(column)) {
252
- continue;
253
- }
254
-
255
- seenColumns.add(column);
256
- normalizedOrderBy.push(
257
- Object.freeze({
258
- column,
259
- direction: normalizeListOrderDirection(sourceEntry.direction),
260
- nulls: normalizeListOrderNulls(sourceEntry.nulls)
261
- })
262
- );
263
- }
264
-
265
- if (normalizedOrderBy.length > 0 && !seenColumns.has(normalizedIdColumn)) {
266
- normalizedOrderBy.push(
267
- Object.freeze({
268
- column: normalizedIdColumn,
269
- direction: normalizedOrderBy[normalizedOrderBy.length - 1].direction,
270
- nulls: LIST_ORDER_NULLS_LAST
271
- })
272
- );
273
- }
274
-
275
- return Object.freeze(normalizedOrderBy);
276
- }
277
-
278
- function resolveListRuntimeConfig(list = {}, fallbackSearchColumns = [], { idColumn = "id" } = {}) {
279
- const parsedMaxLimit = Number(list?.maxLimit);
280
- const normalizedMaxLimit = Number.isInteger(parsedMaxLimit) && parsedMaxLimit > 0
281
- ? parsedMaxLimit
282
- : MAX_LIST_LIMIT;
283
- const normalizedDefaultLimit = normalizeCrudListLimit(list?.defaultLimit, {
284
- fallback: DEFAULT_LIST_LIMIT,
285
- max: normalizedMaxLimit
286
- });
287
-
288
- return Object.freeze({
289
- defaultLimit: normalizedDefaultLimit,
290
- maxLimit: normalizedMaxLimit,
291
- searchColumns: normalizeSearchColumns(list?.searchColumns, fallbackSearchColumns),
292
- orderBy: normalizeListOrderBy(list?.orderBy, { idColumn })
293
- });
294
- }
295
-
296
- function resolveRecordOutputValidator(resource = {}, { context = "crudRepository" } = {}) {
297
- const output = resource?.operations?.view?.output;
298
- if (!output || typeof output !== "object" || Array.isArray(output)) {
299
- throw new TypeError(`${context} requires operations.view.output.`);
300
- }
301
- const schema = resolveSchemaTransportSchemaDefinition(output, {
302
- context: `${context} operations.view.output`,
303
- defaultMode: "replace"
304
- });
305
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
306
- throw new TypeError(`${context} requires operations.view.output to resolve to an object schema.`);
307
- }
308
-
309
- return output;
310
- }
311
-
312
- function resolveOperationBodyValidator(resource = {}, operationKey = "", { context = "crudRepository" } = {}) {
313
- const body = resource?.operations?.[operationKey]?.body;
314
- if (body == null) {
315
- return null;
316
- }
317
- if (!body || typeof body !== "object" || Array.isArray(body)) {
318
- throw new TypeError(`${context} operations.${operationKey}.body must be an object when provided.`);
319
- }
320
-
321
- return body;
322
- }
323
-
324
- function extractExplicitFieldErrors(error) {
325
- if (isRecord(error?.fieldErrors)) {
326
- return error.fieldErrors;
327
- }
328
-
329
- if (isRecord(error?.details?.fieldErrors)) {
330
- return error.details.fieldErrors;
331
- }
332
-
333
- return null;
334
- }
335
-
336
- async function normalizeRepositoryInputPayload(
337
- runtime = {},
338
- payload = {},
339
- {
340
- operationKey = "create",
341
- phase = "crudCreate",
342
- action = "create",
343
- recordId = null,
344
- existingRecord = null,
345
- actionContextBase = {}
346
- } = {}
347
- ) {
348
- const input = operationKey === "patch"
349
- ? runtime.input?.patch
350
- : runtime.input?.create;
351
- const normalizedPayload = normalizeCrudRepositoryObjectInput(payload);
352
-
353
- if (!input) {
354
- return normalizedPayload;
355
- }
356
-
357
- try {
358
- const nextPayload = validateSchemaPayload(input, normalizedPayload, {
359
- phase: "input",
360
- context: `${runtime?.context || "crudRepository"} operations.${operationKey}.body`
361
- });
362
- return normalizeCrudRepositoryObjectInput(nextPayload);
363
- } catch (error) {
364
- const fieldErrors = codedFieldErrors(error);
365
- if (fieldErrors) {
366
- throw createValidationError(fieldErrors);
367
- }
368
- throw error;
369
- }
370
- }
371
-
372
- async function normalizeRepositoryOutputRecord(runtime = {}, record = {}, { operation = "list" } = {}) {
373
- try {
374
- return validateSchemaPayload(runtime.output, record, {
375
- phase: "output",
376
- context: `${runtime?.context || "crudRepository"} operations.view.output`
377
- });
378
- } catch (error) {
379
- const explicitFieldErrors = extractExplicitFieldErrors(error);
380
- if (explicitFieldErrors) {
381
- const detailMessage = Object.entries(explicitFieldErrors)
382
- .map(([field, message]) => `${field}: ${message}`)
383
- .join(", ");
384
- throw new TypeError(
385
- `${runtime?.context || "crudRepository"} ${operation} output validation failed: ${detailMessage}.`
386
- );
387
- }
388
- throw new TypeError(
389
- `${runtime?.context || "crudRepository"} ${operation} output validation failed: ${String(error?.message || "Invalid value.")}.`
390
- );
391
- }
392
- }
393
-
394
- function encodeOrderedListCursorValue(value = null) {
395
- if (value instanceof Date) {
396
- return {
397
- [ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]: ORDERED_LIST_CURSOR_VALUE_TYPE_DATE,
398
- [ORDERED_LIST_CURSOR_VALUE_KEY]: value.toISOString()
399
- };
400
- }
401
-
402
- return value === undefined ? null : value;
403
- }
404
-
405
- function decodeOrderedListCursorValue(value = null) {
406
- if (!value || typeof value !== "object" || Array.isArray(value)) {
407
- return value === undefined ? null : value;
408
- }
409
-
410
- const valueType = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]).toLowerCase();
411
- if (!valueType) {
412
- return value;
413
- }
414
- if (valueType !== ORDERED_LIST_CURSOR_VALUE_TYPE_DATE) {
415
- return value;
416
- }
417
-
418
- const normalizedValue = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_KEY]);
419
- if (!normalizedValue) {
420
- throw new TypeError("Ordered list cursor date values require a non-empty value.");
421
- }
422
-
423
- const date = new Date(normalizedValue);
424
- if (Number.isNaN(date.getTime())) {
425
- throw new TypeError("Ordered list cursor date values must be valid dates.");
426
- }
427
-
428
- return date;
429
- }
430
-
431
- function encodeOrderedListCursor(row = null, orderBy = []) {
432
- if (!row || typeof row !== "object" || Array.isArray(row)) {
433
- return null;
434
- }
435
-
436
- const normalizedOrderBy = Array.isArray(orderBy) ? orderBy : [];
437
- if (normalizedOrderBy.length < 1) {
438
- return null;
439
- }
440
-
441
- const values = normalizedOrderBy.map(({ column }) => (
442
- Object.hasOwn(row, column) && row[column] !== undefined
443
- ? encodeOrderedListCursorValue(row[column])
444
- : null
445
- ));
446
-
447
- return Buffer.from(JSON.stringify({ values }), "utf8").toString("base64url");
448
- }
449
-
450
- function decodeOrderedListCursor(cursor = "", orderBy = []) {
451
- const normalizedCursor = normalizeText(cursor);
452
- const normalizedOrderBy = Array.isArray(orderBy) ? orderBy : [];
453
- if (!normalizedCursor || normalizedOrderBy.length < 1) {
454
- return null;
455
- }
456
-
457
- try {
458
- const decoded = Buffer.from(normalizedCursor, "base64url").toString("utf8");
459
- const payload = JSON.parse(decoded);
460
- const values = Array.isArray(payload?.values) ? payload.values : null;
461
- if (!values || values.length !== normalizedOrderBy.length) {
462
- throw new AppError(400, "Invalid cursor.", {
463
- code: "INVALID_CURSOR"
464
- });
465
- }
466
-
467
- return values.map((value) => decodeOrderedListCursorValue(value));
468
- } catch (error) {
469
- if (error instanceof AppError) {
470
- throw error;
471
- }
472
-
473
- throw new AppError(400, "Invalid cursor.", {
474
- code: "INVALID_CURSOR"
475
- });
476
- }
477
- }
478
-
479
- function applyOrderedListCursorEquality(query, descriptor = {}, value = null) {
480
- if (value === null) {
481
- query.whereNull(descriptor.column);
482
- return;
483
- }
484
-
485
- query.where(descriptor.column, value);
486
- }
487
-
488
- function applyOrderedListCursorAfterBranch(query, descriptor = {}, value = null) {
489
- const operator = descriptor.direction === LIST_ORDER_DIRECTION_DESC ? "<" : ">";
490
-
491
- if (value === null) {
492
- if (descriptor.nulls === LIST_ORDER_NULLS_FIRST) {
493
- query.whereNotNull(descriptor.column);
494
- return true;
495
- }
496
-
497
- return false;
498
- }
499
-
500
- if (descriptor.nulls === LIST_ORDER_NULLS_LAST) {
501
- query.where((branchQuery) => {
502
- branchQuery.where(descriptor.column, operator, value);
503
- branchQuery.orWhereNull(descriptor.column);
504
- });
505
- return true;
506
- }
507
-
508
- query.where(descriptor.column, operator, value);
509
- return true;
510
- }
511
-
512
- function canApplyOrderedListCursorAfterBranch(descriptor = {}, value = null) {
513
- return !(value === null && descriptor.nulls === LIST_ORDER_NULLS_LAST);
514
- }
515
-
516
- function appendOrderedListCursorBranches(query, orderBy = [], cursorValues = [], index = 0, { useOr = false } = {}) {
517
- const descriptor = orderBy[index];
518
- if (!descriptor) {
519
- return false;
520
- }
521
-
522
- let addedBranch = false;
523
- const currentValue = cursorValues[index] ?? null;
524
-
525
- if (canApplyOrderedListCursorAfterBranch(descriptor, currentValue)) {
526
- const afterMethod = useOr === true ? "orWhere" : "where";
527
- query[afterMethod]((afterQuery) => {
528
- applyOrderedListCursorAfterBranch(afterQuery, descriptor, currentValue);
529
- });
530
- addedBranch = true;
531
- }
532
-
533
- if (index >= orderBy.length - 1) {
534
- return addedBranch;
535
- }
536
-
537
- const equalityMethod = useOr === true || addedBranch === true ? "orWhere" : "where";
538
- query[equalityMethod]((equalQuery) => {
539
- applyOrderedListCursorEquality(equalQuery, descriptor, currentValue);
540
- equalQuery.where((nestedQuery) => {
541
- appendOrderedListCursorBranches(nestedQuery, orderBy, cursorValues, index + 1);
542
- });
543
- });
544
- return true;
545
- }
546
-
547
- function applyOrderedListCursorFilter(query, { orderBy = [], cursor = "" } = {}) {
548
- const normalizedOrderBy = Array.isArray(orderBy) ? orderBy : [];
549
- const cursorValues = decodeOrderedListCursor(cursor, normalizedOrderBy);
550
- if (!cursorValues) {
551
- return query;
552
- }
553
-
554
- return query.where((cursorQuery) => {
555
- appendOrderedListCursorBranches(cursorQuery, normalizedOrderBy, cursorValues);
556
- });
557
- }
558
-
559
- function normalizeCrudRepositoryOperationStage(stage = null, stageLabel = "", { context = "crudRepository" } = {}) {
560
- if (stage === undefined || stage === null) {
561
- return null;
562
- }
563
- if (typeof stage !== "function") {
564
- throw new TypeError(`${context} ${stageLabel} must be a function when provided.`);
565
- }
566
- return stage;
567
- }
568
-
569
- function normalizeCrudRepositoryOperationConfig(config = {}, operationKey = "", { context = "crudRepository" } = {}) {
570
- if (config === undefined || config === null) {
571
- return Object.freeze({});
572
- }
573
- if (!config || typeof config !== "object" || Array.isArray(config)) {
574
- throw new TypeError(`${context} operations.${operationKey} must be an object when provided.`);
575
- }
576
-
577
- const allowedKeys = REPOSITORY_OPERATION_STAGE_KEYS[operationKey] || [];
578
- const normalized = {};
579
- for (const [rawKey, rawValue] of Object.entries(config)) {
580
- const key = normalizeText(rawKey);
581
- if (!key) {
582
- continue;
583
- }
584
- if (!allowedKeys.includes(key)) {
585
- throw new TypeError(
586
- `${context} operations.${operationKey}.${key} is not supported. Allowed keys: ${allowedKeys.join(", ")}.`
587
- );
588
- }
589
- normalized[key] = normalizeCrudRepositoryOperationStage(
590
- rawValue,
591
- `operations.${operationKey}.${key}`,
592
- { context }
593
- );
594
- }
595
-
596
- return Object.freeze(normalized);
597
- }
598
-
599
- function normalizeCrudRepositoryOperations(sourceOperations = {}, { context = "crudRepository" } = {}) {
600
- if (sourceOperations === undefined || sourceOperations === null) {
601
- return Object.freeze({});
602
- }
603
- if (!sourceOperations || typeof sourceOperations !== "object" || Array.isArray(sourceOperations)) {
604
- throw new TypeError(`${context} operations must be an object when provided.`);
605
- }
606
-
607
- const normalized = {};
608
- for (const operationKey of REPOSITORY_OPERATION_KEYS) {
609
- normalized[operationKey] = normalizeCrudRepositoryOperationConfig(
610
- sourceOperations[operationKey],
611
- operationKey,
612
- { context }
613
- );
614
- }
615
-
616
- for (const rawKey of Object.keys(sourceOperations)) {
617
- const key = normalizeText(rawKey);
618
- if (key && !REPOSITORY_OPERATION_KEYS.includes(key)) {
619
- throw new TypeError(
620
- `${context} operations.${key} is not supported. Allowed keys: ${REPOSITORY_OPERATION_KEYS.join(", ")}.`
621
- );
622
- }
623
- }
624
-
625
- return Object.freeze(normalized);
626
- }
627
-
628
- function applyConfiguredQueryStage(
629
- dbQuery,
630
- stage = null,
631
- stageContext = {},
632
- { context = "crudRepository", stageKey = "applyQuery" } = {}
633
- ) {
634
- if (typeof stage !== "function") {
635
- return {
636
- queryBuilder: dbQuery
637
- };
638
- }
639
-
640
- const directResult = stage(dbQuery, stageContext);
641
- if (directResult === undefined || directResult === dbQuery) {
642
- return {
643
- queryBuilder: dbQuery
644
- };
645
- }
646
-
647
- if (isCrudRepositoryQueryBuilder(directResult)) {
648
- return {
649
- queryBuilder: directResult
650
- };
651
- }
652
-
653
- if (directResult && typeof directResult.then === "function") {
654
- return Promise.resolve(directResult).then((awaitedResult) => {
655
- if (awaitedResult === undefined || awaitedResult === dbQuery) {
656
- return {
657
- queryBuilder: dbQuery
658
- };
659
- }
660
-
661
- if (isCrudRepositoryQueryBuilder(awaitedResult)) {
662
- throw new TypeError(
663
- `${context} ${stageKey} cannot return a query builder asynchronously. Mutate the provided builder and return undefined instead.`
664
- );
665
- }
666
-
667
- throw new TypeError(
668
- `${context} ${stageKey} must return undefined, the provided query builder, or another query builder synchronously.`
669
- );
670
- });
671
- }
672
-
673
- return Promise.reject(new TypeError(
674
- `${context} ${stageKey} must return undefined, the provided query builder, or another query builder synchronously.`
675
- ));
676
- }
677
-
678
- function isCrudRepositoryQueryBuilder(value) {
679
- if (!value || (typeof value !== "object" && typeof value !== "function") || Array.isArray(value)) {
680
- return false;
681
- }
682
-
683
- return [
684
- "where",
685
- "whereIn",
686
- "select",
687
- "insert",
688
- "update",
689
- "delete",
690
- "del",
691
- "first",
692
- "modify"
693
- ].some((key) => typeof value[key] === "function");
694
- }
695
-
696
- function normalizeCrudRepositoryObjectInput(value = {}) {
697
- if (!value || typeof value !== "object" || Array.isArray(value)) {
698
- return {};
699
- }
700
-
701
- return value;
702
- }
703
-
704
- async function applyConfiguredObjectStage(
705
- payload = {},
706
- stage = null,
707
- stageContext = {},
708
- { context = "crudRepository", stageKey = "preparePayload" } = {}
709
- ) {
710
- const normalizedPayload = normalizeCrudRepositoryObjectInput(payload);
711
- if (typeof stage !== "function") {
712
- return normalizedPayload;
713
- }
714
-
715
- const nextPayload = await stage(normalizedPayload, stageContext);
716
- if (nextPayload === undefined) {
717
- return normalizedPayload;
718
- }
719
-
720
- if (!nextPayload || typeof nextPayload !== "object" || Array.isArray(nextPayload)) {
721
- throw new TypeError(`${context} ${stageKey} must return an object when it returns a value.`);
722
- }
723
-
724
- return nextPayload;
725
- }
726
-
727
- function applyOrderedListControls(dbQuery, orderBy = []) {
728
- let nextQuery = dbQuery;
729
- for (const descriptor of Array.isArray(orderBy) ? orderBy : []) {
730
- if (typeof nextQuery.orderByRaw === "function") {
731
- nextQuery = nextQuery.orderByRaw(
732
- descriptor.nulls === LIST_ORDER_NULLS_FIRST
733
- ? "?? is null desc"
734
- : "?? is null asc",
735
- [descriptor.column]
736
- );
737
- }
738
- nextQuery = nextQuery.orderBy(descriptor.column, descriptor.direction);
739
- }
740
-
741
- return nextQuery;
742
- }
743
-
744
- function enforceCrudRepositoryListControls(
745
- dbQuery,
746
- {
747
- idColumn = "id",
748
- limit = DEFAULT_LIST_LIMIT + 1,
749
- orderBy = []
750
- } = {}
751
- ) {
752
- let nextQuery = dbQuery;
753
- if (typeof nextQuery.clearOrder === "function") {
754
- nextQuery = nextQuery.clearOrder();
755
- }
756
- if (typeof nextQuery.clear === "function") {
757
- nextQuery = nextQuery.clear("limit");
758
- }
759
-
760
- const normalizedOrderBy = Array.isArray(orderBy) ? orderBy : [];
761
- if (normalizedOrderBy.length > 0) {
762
- return applyOrderedListControls(nextQuery, normalizedOrderBy)
763
- .limit(limit);
764
- }
765
-
766
- return nextQuery
767
- .orderBy(idColumn, "asc")
768
- .limit(limit);
769
- }
770
-
771
- function createCrudRepositoryActionContextBase(runtime, callOptions = {}) {
772
- return {
773
- runtime,
774
- repositoryOptions: runtime.repositoryOptions,
775
- callOptions,
776
- state: {}
777
- };
778
- }
779
-
780
- function createCompiledCrudRepositoryRuntime(resource = {}, repositoryOptions = {}) {
781
- const sourceOptions = requireCrudRepositoryOptions(repositoryOptions, {
782
- context: "createCrudResourceRuntime"
783
- });
784
- const context = normalizeText(sourceOptions.context) || "crudRepository";
785
- const repositoryMapping = deriveRepositoryMappingFromResource(resource, { context });
786
- const defaults = resolveRepositoryDefaults(resource, repositoryMapping, { context });
787
- const output = resolveRecordOutputValidator(resource, { context });
788
- const lookupRuntime = createCrudLookupRuntime(resource, {
789
- outputKeys: repositoryMapping.outputKeys
790
- });
791
- const listRuntime = resolveListRuntimeConfig(sourceOptions.list, repositoryMapping.listSearchColumns, {
792
- idColumn: defaults.idColumn
793
- });
794
- const { selectColumns } = buildRepositoryColumnMetadata({
795
- outputKeys: repositoryMapping.columnBackedOutputKeys,
796
- writeKeys: repositoryMapping.writeKeys,
797
- columnOverrides: repositoryMapping.columnOverrides,
798
- fieldStorageByKey: repositoryMapping.fieldStorageByKey
799
- });
800
- const normalizedSelectColumns = Object.freeze(
801
- [...new Set([
802
- ...selectColumns,
803
- ...listRuntime.orderBy.map(({ column }) => column)
804
- ])]
805
- );
806
-
807
- return Object.freeze({
808
- context,
809
- resource,
810
- repositoryOptions: sourceOptions,
811
- defaults,
812
- input: Object.freeze({
813
- create: resolveOperationBodyValidator(resource, "create", { context }),
814
- patch: resolveOperationBodyValidator(resource, "patch", { context })
815
- }),
816
- selectColumns: normalizedSelectColumns,
817
- output,
818
- list: listRuntime,
819
- lookup: lookupRuntime,
820
- mapping: repositoryMapping,
821
- operations: normalizeCrudRepositoryOperations(sourceOptions.operations, { context }),
822
- virtualFields: normalizeCrudVirtualFieldHandlers(sourceOptions.virtualFields, repositoryMapping, { context })
823
- });
824
- }
825
-
826
- function resolveCrudRepositoryCall(runtime, knex, callOptions = {}) {
827
- const client = callOptions?.trx || knex;
828
- const tableName = requireCrudTableName(runtime.repositoryOptions?.tableName ?? runtime.defaults?.tableName, {
829
- context: runtime.context || "crudRepository"
830
- });
831
- const idColumn = resolveCrudIdColumn(runtime.repositoryOptions?.idColumn, {
832
- fallback: runtime.defaults?.idColumn || "id"
833
- });
834
- const visible = (queryBuilder) => applyVisibility(queryBuilder, callOptions.visibilityContext);
835
-
836
- return Object.freeze({
837
- client,
838
- tableName,
839
- idColumn,
840
- visible
841
- });
842
- }
843
-
844
- function applyCrudRepositoryReadLock(dbQuery, callOptions = {}) {
845
- if (callOptions?.forUpdate === true && typeof dbQuery.forUpdate === "function") {
62
+ function applyCrudRepositoryReadLock(dbQuery, callOptions) {
63
+ if (callOptions.forUpdate === true) {
846
64
  return dbQuery.forUpdate();
847
65
  }
848
66
 
849
67
  return dbQuery;
850
68
  }
851
69
 
852
- async function listRecords(runtime, knex, query = {}, callOptions = {}) {
70
+ /**
71
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
72
+ * @param {RuntimeKnex} knex
73
+ * @param {object} query
74
+ * @param {object} callOptions
75
+ */
76
+ async function listRecords(runtime, knex, query, callOptions) {
853
77
  const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
854
- const normalizedLimit = normalizeCrudListLimit(query?.limit, {
78
+ const normalizedLimit = normalizeCrudListLimit(query.limit, {
855
79
  fallback: runtime.list.defaultLimit,
856
80
  max: runtime.list.maxLimit
857
81
  });
858
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
82
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
859
83
  const usesOrderedListCursor = runtime.list.orderBy.length > 0;
860
84
  let dbQuery = client(tableName)
861
85
  .select(...runtime.selectColumns);
@@ -866,9 +90,9 @@ async function listRecords(runtime, knex, query = {}, callOptions = {}) {
866
90
 
867
91
  dbQuery = applyCrudListQueryFilters(dbQuery, {
868
92
  idColumn,
869
- cursor: query?.cursor,
93
+ cursor: query.cursor,
870
94
  applyCursor: usesOrderedListCursor !== true,
871
- q: query?.q,
95
+ q: query.q,
872
96
  searchColumns: runtime.list.searchColumns,
873
97
  parentFilters: query,
874
98
  parentFilterColumns: runtime.mapping.parentFilterColumns
@@ -876,13 +100,13 @@ async function listRecords(runtime, knex, query = {}, callOptions = {}) {
876
100
  if (usesOrderedListCursor) {
877
101
  dbQuery = applyOrderedListCursorFilter(dbQuery, {
878
102
  orderBy: runtime.list.orderBy,
879
- cursor: query?.cursor
103
+ cursor: query.cursor
880
104
  });
881
105
  }
882
106
 
883
107
  const readListStageResult = await applyConfiguredQueryStage(
884
108
  dbQuery,
885
- runtime.operations?.read?.applyQuery,
109
+ runtime.operations.read.applyQuery,
886
110
  {
887
111
  action: "list",
888
112
  query,
@@ -896,7 +120,7 @@ async function listRecords(runtime, knex, query = {}, callOptions = {}) {
896
120
  dbQuery = readListStageResult.queryBuilder;
897
121
  const listStageResult = await applyConfiguredQueryStage(
898
122
  dbQuery,
899
- runtime.operations?.list?.applyQuery,
123
+ runtime.operations.list.applyQuery,
900
124
  {
901
125
  action: "list",
902
126
  query,
@@ -940,11 +164,8 @@ async function listRecords(runtime, knex, query = {}, callOptions = {}) {
940
164
  }));
941
165
  }
942
166
 
943
- const hydratedItems = await hydrateCrudLookupRecords(items, {
944
- ...runtime.lookup,
945
- context: runtime.context
946
- }, {
947
- include: callOptions?.include,
167
+ const hydratedItems = await hydrateCrudLookupRecords(items, runtime.lookup, {
168
+ include: callOptions.include,
948
169
  mode: "list",
949
170
  repositoryOptions: runtime.repositoryOptions,
950
171
  callOptions
@@ -965,10 +186,16 @@ async function listRecords(runtime, knex, query = {}, callOptions = {}) {
965
186
  };
966
187
  }
967
188
 
968
- async function findRecordById(runtime, knex, recordId, callOptions = {}) {
189
+ /**
190
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
191
+ * @param {RuntimeKnex} knex
192
+ * @param {unknown} recordId
193
+ * @param {object} callOptions
194
+ */
195
+ async function findRecordById(runtime, knex, recordId, callOptions) {
969
196
  const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
970
197
  const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.findById" });
971
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
198
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
972
199
  let dbQuery = client(tableName)
973
200
  .select(...runtime.selectColumns);
974
201
  dbQuery = applyCrudRepositoryVirtualProjections(dbQuery, runtime, {
@@ -978,7 +205,7 @@ async function findRecordById(runtime, knex, recordId, callOptions = {}) {
978
205
 
979
206
  const readFindStageResult = await applyConfiguredQueryStage(
980
207
  dbQuery,
981
- runtime.operations?.read?.applyQuery,
208
+ runtime.operations.read.applyQuery,
982
209
  {
983
210
  action: "findById",
984
211
  recordId,
@@ -992,7 +219,7 @@ async function findRecordById(runtime, knex, recordId, callOptions = {}) {
992
219
  dbQuery = readFindStageResult.queryBuilder;
993
220
  const findStageResult = await applyConfiguredQueryStage(
994
221
  dbQuery,
995
- runtime.operations?.findById?.applyQuery,
222
+ runtime.operations.findById.applyQuery,
996
223
  {
997
224
  action: "findById",
998
225
  recordId,
@@ -1030,11 +257,8 @@ async function findRecordById(runtime, knex, recordId, callOptions = {}) {
1030
257
  const normalizedRecord = await normalizeRepositoryOutputRecord(runtime, mappedRecord, {
1031
258
  operation: "findById"
1032
259
  });
1033
- const hydrated = await hydrateCrudLookupRecords([normalizedRecord], {
1034
- ...runtime.lookup,
1035
- context: runtime.context
1036
- }, {
1037
- include: callOptions?.include,
260
+ const hydrated = await hydrateCrudLookupRecords([normalizedRecord], runtime.lookup, {
261
+ include: callOptions.include,
1038
262
  mode: "view",
1039
263
  repositoryOptions: runtime.repositoryOptions,
1040
264
  callOptions
@@ -1043,23 +267,29 @@ async function findRecordById(runtime, knex, recordId, callOptions = {}) {
1043
267
  return hydrated[0] || null;
1044
268
  }
1045
269
 
1046
- async function listRecordsByIds(runtime, knex, ids = [], callOptions = {}) {
270
+ /**
271
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
272
+ * @param {RuntimeKnex} knex
273
+ * @param {unknown[]} ids
274
+ * @param {object} callOptions
275
+ */
276
+ async function listRecordsByIds(runtime, knex, ids, callOptions) {
1047
277
  const { client, tableName, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
1048
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
1049
- const lookupValueKey = normalizeText(callOptions?.valueKey) || "id";
278
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
279
+ const lookupValueKey = normalizeText(callOptions.valueKey) || "id";
1050
280
  if (!runtime.mapping.outputKeys.includes(lookupValueKey)) {
1051
281
  throw new TypeError(
1052
- `${runtime.context || "crudRepository"} listByIds requires valueKey "${lookupValueKey}" to exist in output schema.`
282
+ `${runtime.context} listByIds requires valueKey "${lookupValueKey}" to exist in output schema.`
1053
283
  );
1054
284
  }
1055
- if (runtime.mapping.fieldStorageByKey?.[lookupValueKey] !== CRUD_FIELD_STORAGE_COLUMN) {
285
+ if (runtime.mapping.fieldStorageByKey[lookupValueKey] !== CRUD_FIELD_STORAGE_COLUMN) {
1056
286
  throw new TypeError(
1057
- `${runtime.context || "crudRepository"} listByIds requires valueKey "${lookupValueKey}" to be column-backed.`
287
+ `${runtime.context} listByIds requires valueKey "${lookupValueKey}" to be column-backed.`
1058
288
  );
1059
289
  }
1060
290
  const lookupColumn = resolveColumnName(lookupValueKey, runtime.mapping.columnOverrides);
1061
291
  if (!lookupColumn) {
1062
- throw new TypeError(`${runtime.context || "crudRepository"} listByIds requires a valid valueKey.`);
292
+ throw new TypeError(`${runtime.context} listByIds requires a valid valueKey.`);
1063
293
  }
1064
294
 
1065
295
  const normalizedIds = Array.isArray(ids)
@@ -1078,7 +308,7 @@ async function listRecordsByIds(runtime, knex, ids = [], callOptions = {}) {
1078
308
 
1079
309
  const readListByIdsStageResult = await applyConfiguredQueryStage(
1080
310
  dbQuery,
1081
- runtime.operations?.read?.applyQuery,
311
+ runtime.operations.read.applyQuery,
1082
312
  {
1083
313
  action: "listByIds",
1084
314
  ids: normalizedIds,
@@ -1094,7 +324,7 @@ async function listRecordsByIds(runtime, knex, ids = [], callOptions = {}) {
1094
324
  dbQuery = readListByIdsStageResult.queryBuilder;
1095
325
  const listByIdsStageResult = await applyConfiguredQueryStage(
1096
326
  dbQuery,
1097
- runtime.operations?.listByIds?.applyQuery,
327
+ runtime.operations.listByIds.applyQuery,
1098
328
  {
1099
329
  action: "listByIds",
1100
330
  ids: normalizedIds,
@@ -1136,11 +366,8 @@ async function listRecordsByIds(runtime, knex, ids = [], callOptions = {}) {
1136
366
  }));
1137
367
  }
1138
368
 
1139
- const lookupInclude = callOptions?.include === undefined ? "none" : callOptions.include;
1140
- return hydrateCrudLookupRecords(records, {
1141
- ...runtime.lookup,
1142
- context: runtime.context
1143
- }, {
369
+ const lookupInclude = callOptions.include === undefined ? "none" : callOptions.include;
370
+ return hydrateCrudLookupRecords(records, runtime.lookup, {
1144
371
  include: lookupInclude,
1145
372
  mode: "list",
1146
373
  repositoryOptions: runtime.repositoryOptions,
@@ -1148,18 +375,19 @@ async function listRecordsByIds(runtime, knex, ids = [], callOptions = {}) {
1148
375
  });
1149
376
  }
1150
377
 
1151
- async function createRecord(runtime, knex, payload = {}, callOptions = {}) {
378
+ /**
379
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
380
+ * @param {RuntimeKnex} knex
381
+ * @param {object} payload
382
+ * @param {object} callOptions
383
+ */
384
+ async function createRecord(runtime, knex, payload, callOptions) {
1152
385
  const { client, tableName } = resolveCrudRepositoryCall(runtime, knex, callOptions);
1153
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
1154
- let sourcePayload = await normalizeRepositoryInputPayload(runtime, payload, {
1155
- operationKey: "create",
1156
- phase: "crudCreate",
1157
- action: "create",
1158
- actionContextBase
1159
- });
386
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
387
+ let sourcePayload = await normalizeRepositoryInputPayload(runtime, payload, "create");
1160
388
  sourcePayload = await applyConfiguredObjectStage(
1161
389
  sourcePayload,
1162
- runtime.operations?.create?.preparePayload,
390
+ runtime.operations.create.preparePayload,
1163
391
  {
1164
392
  action: "create",
1165
393
  payload: sourcePayload,
@@ -1188,7 +416,7 @@ async function createRecord(runtime, knex, payload = {}, callOptions = {}) {
1188
416
  }
1189
417
  insertPayload = await applyConfiguredObjectStage(
1190
418
  insertPayload,
1191
- runtime.operations?.create?.prepareInsertPayload,
419
+ runtime.operations.create.prepareInsertPayload,
1192
420
  {
1193
421
  action: "create",
1194
422
  payload: sourcePayload,
@@ -1207,7 +435,7 @@ async function createRecord(runtime, knex, payload = {}, callOptions = {}) {
1207
435
  let createQuery = client(tableName);
1208
436
  const createStageResult = await applyConfiguredQueryStage(
1209
437
  createQuery,
1210
- runtime.operations?.create?.applyQuery,
438
+ runtime.operations.create.applyQuery,
1211
439
  {
1212
440
  action: "create",
1213
441
  payload: {
@@ -1235,28 +463,21 @@ async function createRecord(runtime, knex, payload = {}, callOptions = {}) {
1235
463
  });
1236
464
  }
1237
465
 
1238
- async function updateRecordById(runtime, knex, recordId, patch = {}, callOptions = {}) {
466
+ /**
467
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
468
+ * @param {RuntimeKnex} knex
469
+ * @param {unknown} recordId
470
+ * @param {object} patch
471
+ * @param {object} callOptions
472
+ */
473
+ async function updateRecordById(runtime, knex, recordId, patch, callOptions) {
1239
474
  const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
1240
475
  const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.updateById" });
1241
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
1242
- const existingRecord = Object.hasOwn(callOptions, "existingRecord")
1243
- ? callOptions.existingRecord
1244
- : await findRecordById(runtime, knex, normalizedRecordId, {
1245
- ...callOptions,
1246
- trx: client,
1247
- sourceOperation: "update"
1248
- });
1249
- let sourcePatch = await normalizeRepositoryInputPayload(runtime, patch, {
1250
- operationKey: "patch",
1251
- phase: "crudPatch",
1252
- action: "update",
1253
- recordId: normalizedRecordId,
1254
- existingRecord,
1255
- actionContextBase
1256
- });
476
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
477
+ let sourcePatch = await normalizeRepositoryInputPayload(runtime, patch, "patch");
1257
478
  sourcePatch = await applyConfiguredObjectStage(
1258
479
  sourcePatch,
1259
- runtime.operations?.updateById?.preparePatch,
480
+ runtime.operations.updateById.preparePatch,
1260
481
  {
1261
482
  action: "updateById",
1262
483
  recordId,
@@ -1292,7 +513,7 @@ async function updateRecordById(runtime, knex, recordId, patch = {}, callOptions
1292
513
  let updateQuery = client(tableName);
1293
514
  const updateStageResult = await applyConfiguredQueryStage(
1294
515
  updateQuery,
1295
- runtime.operations?.updateById?.applyQuery,
516
+ runtime.operations.updateById.applyQuery,
1296
517
  {
1297
518
  action: "updateById",
1298
519
  recordId,
@@ -1323,10 +544,16 @@ async function updateRecordById(runtime, knex, recordId, patch = {}, callOptions
1323
544
  });
1324
545
  }
1325
546
 
1326
- async function deleteRecordById(runtime, knex, recordId, callOptions = {}) {
547
+ /**
548
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
549
+ * @param {RuntimeKnex} knex
550
+ * @param {unknown} recordId
551
+ * @param {object} callOptions
552
+ */
553
+ async function deleteRecordById(runtime, knex, recordId, callOptions) {
1327
554
  const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
1328
555
  const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.deleteById" });
1329
- const actionContextBase = createCrudRepositoryActionContextBase(runtime, callOptions);
556
+ const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
1330
557
  const existing = await findRecordById(runtime, knex, recordId, {
1331
558
  ...callOptions,
1332
559
  include: "none",
@@ -1339,7 +566,7 @@ async function deleteRecordById(runtime, knex, recordId, callOptions = {}) {
1339
566
  let deleteQuery = client(tableName);
1340
567
  const deleteStageResult = await applyConfiguredQueryStage(
1341
568
  deleteQuery,
1342
- runtime.operations?.deleteById?.applyQuery,
569
+ runtime.operations.deleteById.applyQuery,
1343
570
  {
1344
571
  action: "deleteById",
1345
572
  recordId,
@@ -1367,45 +594,65 @@ async function deleteRecordById(runtime, knex, recordId, callOptions = {}) {
1367
594
  };
1368
595
  }
1369
596
 
1370
- function createCrudResourceRuntime(resource = {}, knex, repositoryOptions = {}) {
1371
- if (typeof knex !== "function") {
1372
- throw new TypeError("createCrudResourceRuntime requires knex.");
597
+ /**
598
+ * @param {import("../types.js").CrudResourceDefinition} resource
599
+ * @param {RuntimeKnex} knex
600
+ * @param {object} [repositoryOptions]
601
+ */
602
+ function createCrudResourceRuntime(resource, knex, repositoryOptions = {}) {
603
+ // readable-check: allow method-probe - input validation: the application passes its own Knex instance
604
+ if (typeof knex !== "function" || typeof knex.transaction !== "function") {
605
+ throw new TypeError("createCrudResourceRuntime requires the application's Knex instance.");
1373
606
  }
1374
607
 
1375
- const runtime = createCompiledCrudRepositoryRuntime(resource, repositoryOptions);
608
+ const runtime = buildCompiledCrudRepositoryRuntime(resource, repositoryOptions);
1376
609
  const withTransaction = createWithTransaction(knex);
1377
610
 
1378
- return Object.freeze({
1379
- withTransaction,
1380
- async list(query = {}, callOptions = {}) {
1381
- return listRecords(runtime, knex, query, callOptions);
1382
- },
1383
- async findById(recordId, callOptions = {}) {
1384
- return findRecordById(runtime, knex, recordId, callOptions);
1385
- },
1386
- async listByIds(ids = [], callOptions = {}) {
1387
- return listRecordsByIds(runtime, knex, ids, callOptions);
1388
- },
1389
- async listByForeignIds(ids = [], foreignKey = "", callOptions = {}) {
1390
- const normalizedForeignKey = normalizeText(foreignKey);
1391
- if (!normalizedForeignKey) {
1392
- throw new TypeError(`${runtime.context || "crudRepository"} listByForeignIds requires foreignKey.`);
1393
- }
611
+ async function list(query = {}, callOptions = {}) {
612
+ return listRecords(runtime, knex, query, callOptions);
613
+ }
1394
614
 
1395
- return listRecordsByIds(runtime, knex, ids, {
1396
- ...callOptions,
1397
- valueKey: normalizedForeignKey
1398
- });
1399
- },
1400
- async create(payload = {}, callOptions = {}) {
1401
- return createRecord(runtime, knex, payload, callOptions);
1402
- },
1403
- async updateById(recordId, patch = {}, callOptions = {}) {
1404
- return updateRecordById(runtime, knex, recordId, patch, callOptions);
1405
- },
1406
- async deleteById(recordId, callOptions = {}) {
1407
- return deleteRecordById(runtime, knex, recordId, callOptions);
615
+ async function findById(recordId, callOptions = {}) {
616
+ return findRecordById(runtime, knex, recordId, callOptions);
617
+ }
618
+
619
+ async function listByIds(ids = [], callOptions = {}) {
620
+ return listRecordsByIds(runtime, knex, ids, callOptions);
621
+ }
622
+
623
+ async function listByForeignIds(ids = [], foreignKey = "", callOptions = {}) {
624
+ const normalizedForeignKey = normalizeText(foreignKey);
625
+ if (!normalizedForeignKey) {
626
+ throw new TypeError(`${runtime.context} listByForeignIds requires foreignKey.`);
1408
627
  }
628
+
629
+ return listRecordsByIds(runtime, knex, ids, {
630
+ ...callOptions,
631
+ valueKey: normalizedForeignKey
632
+ });
633
+ }
634
+
635
+ async function create(payload = {}, callOptions = {}) {
636
+ return createRecord(runtime, knex, payload, callOptions);
637
+ }
638
+
639
+ async function updateById(recordId, patch = {}, callOptions = {}) {
640
+ return updateRecordById(runtime, knex, recordId, patch, callOptions);
641
+ }
642
+
643
+ async function deleteById(recordId, callOptions = {}) {
644
+ return deleteRecordById(runtime, knex, recordId, callOptions);
645
+ }
646
+
647
+ return Object.freeze({
648
+ withTransaction,
649
+ list,
650
+ findById,
651
+ listByIds,
652
+ listByForeignIds,
653
+ create,
654
+ updateById,
655
+ deleteById
1409
656
  });
1410
657
  }
1411
658