@jskit-ai/crud-core 0.2.14 → 0.2.16

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 (60) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/locales/en.json +1 -11
  3. package/package.json +19 -19
  4. package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  5. package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  6. package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  7. package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  8. package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  9. package/src/server/createHooksToCollectChildren.js +56 -34
  10. package/src/server/crudContracts.js +54 -0
  11. package/src/server/defineCrudFeature.js +538 -0
  12. package/src/server/jsonApiModule/actions.js +117 -59
  13. package/src/server/jsonApiModule/routes.js +35 -11
  14. package/src/server/jsonApiModule/service.js +227 -32
  15. package/src/server/jsonApiResourceContract.js +41 -1
  16. package/src/server/listQueryValidators.js +1 -1
  17. package/src/server/removedApi.js +87 -0
  18. package/src/server/types.js +26 -50
  19. package/test/assistantActionConformance.test.js +20 -21
  20. package/test/assistantPagination.integration.test.js +32 -42
  21. package/test/createHooksToCollectChildren.test.js +61 -16
  22. package/test/crudFeaturePackagePattern.test.js +51 -0
  23. package/test/crudOnHandles.test.js +451 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +451 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +63 -0
  27. package/test/listQueryValidators.test.js +1 -1
  28. package/test/routeContracts.test.js +1 -1
  29. package/test/support/crudJsonApiActionOptions.js +3 -3
  30. package/test/unservedCrudAutomation.test.js +27 -22
  31. package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  32. package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  33. package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  34. package/src/server/createCrudServiceFromResource.js +0 -63
  35. package/src/server/defineCrudJsonApiFeature.js +0 -346
  36. package/src/server/fieldAccess.js +0 -298
  37. package/src/server/jsonApiModule/repository.js +0 -355
  38. package/src/server/lookupPathSupport.js +0 -58
  39. package/src/server/lookups.js +0 -40
  40. package/src/server/repositorySupport.js +0 -528
  41. package/src/server/resourceRuntime/compiledRuntime.js +0 -284
  42. package/src/server/resourceRuntime/index.js +0 -659
  43. package/src/server/resourceRuntime/listControls.js +0 -333
  44. package/src/server/resourceRuntime/lookupHydration.js +0 -626
  45. package/src/server/resourceRuntime/operationStages.js +0 -140
  46. package/src/server/resourceRuntime/recordValidation.js +0 -65
  47. package/src/server/serviceMethods.js +0 -149
  48. package/test/createCrudServiceFromResource.test.js +0 -323
  49. package/test/fieldAccess.test.js +0 -86
  50. package/test/jsonApiRepository.test.js +0 -333
  51. package/test/jsonApiRepositoryDataCosts.test.js +0 -183
  52. package/test/jsonApiRepositoryPageLimits.test.js +0 -158
  53. package/test/jsonApiRepositoryRowLocks.test.js +0 -137
  54. package/test/jsonApiResourcePackagePattern.test.js +0 -20
  55. package/test/lookups.test.js +0 -111
  56. package/test/repositorySupport.test.js +0 -767
  57. package/test/resourceRuntime.test.js +0 -1014
  58. package/test/serviceMethods.test.js +0 -139
  59. /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  60. /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -1,333 +0,0 @@
1
- import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
- import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
- import {
4
- DEFAULT_LIST_LIMIT,
5
- MAX_LIST_LIMIT,
6
- normalizeCrudListLimit
7
- } from "../repositorySupport.js";
8
-
9
- const LIST_ORDER_DIRECTION_ASC = "asc";
10
- const LIST_ORDER_DIRECTION_DESC = "desc";
11
- const LIST_ORDER_NULLS_FIRST = "first";
12
- const LIST_ORDER_NULLS_LAST = "last";
13
- const ORDERED_LIST_CURSOR_VALUE_TYPE_KEY = "__jskitCursorValueType";
14
- const ORDERED_LIST_CURSOR_VALUE_KEY = "value";
15
- const ORDERED_LIST_CURSOR_VALUE_TYPE_DATE = "date";
16
-
17
- /**
18
- * @param {unknown} searchColumns The list options' searchColumns, when given.
19
- * @param {readonly string[]} fallbackColumns The resource's string columns.
20
- */
21
- function normalizeSearchColumns(searchColumns, fallbackColumns) {
22
- const normalizedConfiguredColumns = (Array.isArray(searchColumns) ? searchColumns : [])
23
- .map((columnName) => normalizeText(columnName))
24
- .filter(Boolean);
25
-
26
- if (normalizedConfiguredColumns.length > 0) {
27
- return Object.freeze([...new Set(normalizedConfiguredColumns)]);
28
- }
29
-
30
- return fallbackColumns;
31
- }
32
-
33
- function normalizeListOrderDirection(value = LIST_ORDER_DIRECTION_ASC) {
34
- const normalized = normalizeText(value).toLowerCase();
35
- if (!normalized) {
36
- return LIST_ORDER_DIRECTION_ASC;
37
- }
38
- if (normalized === LIST_ORDER_DIRECTION_ASC || normalized === LIST_ORDER_DIRECTION_DESC) {
39
- return normalized;
40
- }
41
-
42
- throw new TypeError(`crudRepository list.orderBy direction must be "${LIST_ORDER_DIRECTION_ASC}" or "${LIST_ORDER_DIRECTION_DESC}".`);
43
- }
44
-
45
- function normalizeListOrderNulls(value = LIST_ORDER_NULLS_LAST) {
46
- const normalized = normalizeText(value).toLowerCase();
47
- if (!normalized) {
48
- return LIST_ORDER_NULLS_LAST;
49
- }
50
- if (normalized === LIST_ORDER_NULLS_FIRST || normalized === LIST_ORDER_NULLS_LAST) {
51
- return normalized;
52
- }
53
-
54
- throw new TypeError(`crudRepository list.orderBy nulls must be "${LIST_ORDER_NULLS_FIRST}" or "${LIST_ORDER_NULLS_LAST}".`);
55
- }
56
-
57
- function normalizeListOrderBy(orderBy, { idColumn }) {
58
- const sourceEntries = Array.isArray(orderBy)
59
- ? orderBy
60
- : orderBy === null || orderBy === undefined
61
- ? []
62
- : [orderBy];
63
- const normalizedOrderBy = [];
64
- const seenColumns = new Set();
65
-
66
- for (const rawEntry of sourceEntries) {
67
- const sourceEntry = typeof rawEntry === "string"
68
- ? { column: rawEntry }
69
- : rawEntry;
70
- if (!isRecord(sourceEntry)) {
71
- throw new TypeError("crudRepository list.orderBy entries must be objects or column strings.");
72
- }
73
-
74
- const column = normalizeText(sourceEntry.column);
75
- if (!column) {
76
- throw new TypeError("crudRepository list.orderBy entries require column.");
77
- }
78
- if (seenColumns.has(column)) {
79
- continue;
80
- }
81
-
82
- seenColumns.add(column);
83
- normalizedOrderBy.push(
84
- Object.freeze({
85
- column,
86
- direction: normalizeListOrderDirection(sourceEntry.direction),
87
- nulls: normalizeListOrderNulls(sourceEntry.nulls)
88
- })
89
- );
90
- }
91
-
92
- if (normalizedOrderBy.length > 0 && !seenColumns.has(idColumn)) {
93
- normalizedOrderBy.push(
94
- Object.freeze({
95
- column: idColumn,
96
- direction: normalizedOrderBy[normalizedOrderBy.length - 1].direction,
97
- nulls: LIST_ORDER_NULLS_LAST
98
- })
99
- );
100
- }
101
-
102
- return Object.freeze(normalizedOrderBy);
103
- }
104
-
105
- /**
106
- * A repository's list controls, from its list options: the default and maximum
107
- * page size, the search columns and the order.
108
- * @param {object} list The repository options' list, when given.
109
- * @param {readonly string[]} fallbackSearchColumns
110
- * @param {{ idColumn: string }} keys The id column that breaks order ties.
111
- */
112
- function resolveListRuntimeConfig(list = {}, fallbackSearchColumns, { idColumn }) {
113
- const parsedMaxLimit = Number(list.maxLimit);
114
- const normalizedMaxLimit = Number.isInteger(parsedMaxLimit) && parsedMaxLimit > 0
115
- ? parsedMaxLimit
116
- : MAX_LIST_LIMIT;
117
- const normalizedDefaultLimit = normalizeCrudListLimit(list.defaultLimit, {
118
- fallback: DEFAULT_LIST_LIMIT,
119
- max: normalizedMaxLimit
120
- });
121
-
122
- return Object.freeze({
123
- defaultLimit: normalizedDefaultLimit,
124
- maxLimit: normalizedMaxLimit,
125
- searchColumns: normalizeSearchColumns(list.searchColumns, fallbackSearchColumns),
126
- orderBy: normalizeListOrderBy(list.orderBy, { idColumn })
127
- });
128
- }
129
-
130
- function encodeOrderedListCursorValue(value = null) {
131
- if (value instanceof Date) {
132
- return {
133
- [ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]: ORDERED_LIST_CURSOR_VALUE_TYPE_DATE,
134
- [ORDERED_LIST_CURSOR_VALUE_KEY]: value.toISOString()
135
- };
136
- }
137
-
138
- return value === undefined ? null : value;
139
- }
140
-
141
- function decodeOrderedListCursorValue(value = null) {
142
- if (!isRecord(value)) {
143
- return value === undefined ? null : value;
144
- }
145
-
146
- const valueType = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]).toLowerCase();
147
- if (!valueType) {
148
- return value;
149
- }
150
- if (valueType !== ORDERED_LIST_CURSOR_VALUE_TYPE_DATE) {
151
- return value;
152
- }
153
-
154
- const normalizedValue = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_KEY]);
155
- if (!normalizedValue) {
156
- throw new TypeError("Ordered list cursor date values require a non-empty value.");
157
- }
158
-
159
- const date = new Date(normalizedValue);
160
- if (Number.isNaN(date.getTime())) {
161
- throw new TypeError("Ordered list cursor date values must be valid dates.");
162
- }
163
-
164
- return date;
165
- }
166
-
167
- /**
168
- * @param {unknown} row
169
- * @param {ReadonlyArray<{ column: string }>} orderBy The runtime's list order.
170
- */
171
- function encodeOrderedListCursor(row, orderBy) {
172
- if (!isRecord(row) || orderBy.length < 1) {
173
- return null;
174
- }
175
-
176
- const values = orderBy.map(({ column }) => (
177
- Object.hasOwn(row, column) && row[column] !== undefined
178
- ? encodeOrderedListCursorValue(row[column])
179
- : null
180
- ));
181
-
182
- return Buffer.from(JSON.stringify({ values }), "utf8").toString("base64url");
183
- }
184
-
185
- function decodeOrderedListCursor(cursor, orderBy) {
186
- const normalizedCursor = normalizeText(cursor);
187
- if (!normalizedCursor || orderBy.length < 1) {
188
- return null;
189
- }
190
-
191
- try {
192
- const decoded = Buffer.from(normalizedCursor, "base64url").toString("utf8");
193
- const payload = JSON.parse(decoded);
194
- const values = Array.isArray(payload?.values) ? payload.values : null;
195
- if (!values || values.length !== orderBy.length) {
196
- throw new AppError(400, "Invalid cursor.", {
197
- code: "INVALID_CURSOR"
198
- });
199
- }
200
-
201
- return values.map((value) => decodeOrderedListCursorValue(value));
202
- } catch (error) {
203
- if (error instanceof AppError) {
204
- throw error;
205
- }
206
-
207
- throw new AppError(400, "Invalid cursor.", {
208
- code: "INVALID_CURSOR"
209
- });
210
- }
211
- }
212
-
213
- function applyOrderedListCursorEquality(query, descriptor = {}, value = null) {
214
- if (value === null) {
215
- query.whereNull(descriptor.column);
216
- return;
217
- }
218
-
219
- query.where(descriptor.column, value);
220
- }
221
-
222
- function applyOrderedListCursorAfterBranch(query, descriptor = {}, value = null) {
223
- const operator = descriptor.direction === LIST_ORDER_DIRECTION_DESC ? "<" : ">";
224
-
225
- if (value === null) {
226
- if (descriptor.nulls === LIST_ORDER_NULLS_FIRST) {
227
- query.whereNotNull(descriptor.column);
228
- return true;
229
- }
230
-
231
- return false;
232
- }
233
-
234
- if (descriptor.nulls === LIST_ORDER_NULLS_LAST) {
235
- query.where((branchQuery) => {
236
- branchQuery.where(descriptor.column, operator, value);
237
- branchQuery.orWhereNull(descriptor.column);
238
- });
239
- return true;
240
- }
241
-
242
- query.where(descriptor.column, operator, value);
243
- return true;
244
- }
245
-
246
- function canApplyOrderedListCursorAfterBranch(descriptor = {}, value = null) {
247
- return !(value === null && descriptor.nulls === LIST_ORDER_NULLS_LAST);
248
- }
249
-
250
- function appendOrderedListCursorBranches(query, orderBy = [], cursorValues = [], index = 0, { useOr = false } = {}) {
251
- const descriptor = orderBy[index];
252
- if (!descriptor) {
253
- return false;
254
- }
255
-
256
- let addedBranch = false;
257
- const currentValue = cursorValues[index] ?? null;
258
-
259
- if (canApplyOrderedListCursorAfterBranch(descriptor, currentValue)) {
260
- const afterMethod = useOr === true ? "orWhere" : "where";
261
- query[afterMethod]((afterQuery) => {
262
- applyOrderedListCursorAfterBranch(afterQuery, descriptor, currentValue);
263
- });
264
- addedBranch = true;
265
- }
266
-
267
- if (index >= orderBy.length - 1) {
268
- return addedBranch;
269
- }
270
-
271
- const equalityMethod = useOr === true || addedBranch === true ? "orWhere" : "where";
272
- query[equalityMethod]((equalQuery) => {
273
- applyOrderedListCursorEquality(equalQuery, descriptor, currentValue);
274
- equalQuery.where((nestedQuery) => {
275
- appendOrderedListCursorBranches(nestedQuery, orderBy, cursorValues, index + 1);
276
- });
277
- });
278
- return true;
279
- }
280
-
281
- /**
282
- * @param {object} query
283
- * @param {{ orderBy: ReadonlyArray<object>, cursor: unknown }} list The runtime's list order and the query's cursor.
284
- */
285
- function applyOrderedListCursorFilter(query, { orderBy, cursor }) {
286
- const cursorValues = decodeOrderedListCursor(cursor, orderBy);
287
- if (!cursorValues) {
288
- return query;
289
- }
290
-
291
- return query.where((cursorQuery) => {
292
- appendOrderedListCursorBranches(cursorQuery, orderBy, cursorValues);
293
- });
294
- }
295
-
296
- function applyOrderedListControls(dbQuery, orderBy) {
297
- let nextQuery = dbQuery;
298
- for (const descriptor of orderBy) {
299
- nextQuery = nextQuery.orderByRaw(
300
- descriptor.nulls === LIST_ORDER_NULLS_FIRST
301
- ? "?? is null desc"
302
- : "?? is null asc",
303
- [descriptor.column]
304
- );
305
- nextQuery = nextQuery.orderBy(descriptor.column, descriptor.direction);
306
- }
307
-
308
- return nextQuery;
309
- }
310
-
311
- /**
312
- * @param {object} dbQuery
313
- * @param {{ idColumn: string, limit: number, orderBy: ReadonlyArray<object> }} controls
314
- */
315
- function enforceCrudRepositoryListControls(dbQuery, { idColumn, limit, orderBy }) {
316
- const nextQuery = dbQuery.clearOrder().clear("limit");
317
-
318
- if (orderBy.length > 0) {
319
- return applyOrderedListControls(nextQuery, orderBy)
320
- .limit(limit);
321
- }
322
-
323
- return nextQuery
324
- .orderBy(idColumn, "asc")
325
- .limit(limit);
326
- }
327
-
328
- export {
329
- resolveListRuntimeConfig,
330
- encodeOrderedListCursor,
331
- applyOrderedListCursorFilter,
332
- enforceCrudRepositoryListControls
333
- };