@jskit-ai/crud-core 0.2.3 → 0.2.5

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,710 +0,0 @@
1
- import { normalizeOpaqueId, normalizeText, normalizeUniqueTextList } from "@jskit-ai/kernel/shared/support/normalize";
2
- import { normalizeVisibilityContext } from "@jskit-ai/kernel/shared/support/visibility";
3
- import {
4
- normalizeCrudLookupNamespace,
5
- resolveCrudLookupApiPathFromNamespace,
6
- normalizeCrudLookupContainerKey,
7
- resolveCrudLookupContainerKey
8
- } from "@jskit-ai/resource-crud-core/shared/crudLookup";
9
- import { buildCrudFieldContractMap } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
10
- import { normalizeCrudLookupApiPath } from "./lookupPathSupport.js";
11
-
12
- const DEFAULT_LOOKUP_INCLUDE = "*";
13
- const DEFAULT_LOOKUP_MAX_DEPTH = 3;
14
- const MAX_LOOKUP_MAX_DEPTH = 10;
15
- const LOOKUP_OWNERSHIP_FILTER_VALUES = Object.freeze([
16
- "public",
17
- "user",
18
- "workspace",
19
- "workspace_user"
20
- ]);
21
- const LOOKUP_OWNERSHIP_FILTER_SET = new Set(LOOKUP_OWNERSHIP_FILTER_VALUES);
22
-
23
- function normalizeLookupRelationEntry(entry = {}, outputKeys = new Set()) {
24
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
25
- return null;
26
- }
27
-
28
- const key = normalizeText(entry.key);
29
- if (!key) {
30
- return null;
31
- }
32
-
33
- const relation = entry.relation;
34
- if (!relation || typeof relation !== "object" || Array.isArray(relation)) {
35
- return null;
36
- }
37
-
38
- const relationKind = normalizeText(relation.kind).toLowerCase();
39
- if (relationKind !== "lookup" && relationKind !== "collection") {
40
- return null;
41
- }
42
-
43
- const namespace =
44
- normalizeCrudLookupNamespace(relation.namespace) ||
45
- normalizeCrudLookupNamespace(relation.apiPath);
46
- if (!namespace) {
47
- return null;
48
- }
49
- const explicitApiPath = normalizeCrudLookupApiPath(relation.apiPath);
50
- const apiPath = explicitApiPath || resolveCrudLookupApiPathFromNamespace(namespace);
51
-
52
- if (relationKind === "lookup") {
53
- if (outputKeys instanceof Set && !outputKeys.has(key)) {
54
- return null;
55
- }
56
- const valueKey = normalizeText(relation.valueKey) || "id";
57
-
58
- return {
59
- key,
60
- relation: {
61
- kind: "lookup",
62
- namespace,
63
- apiPath,
64
- valueKey,
65
- hydrateOnList: relation.hydrateOnList !== false,
66
- hydrateOnView: relation.hydrateOnView !== false
67
- }
68
- };
69
- }
70
-
71
- const foreignKey = normalizeText(relation.foreignKey);
72
- if (!foreignKey) {
73
- return null;
74
- }
75
-
76
- const parentValueKey = normalizeText(relation.parentValueKey) || "id";
77
- if (outputKeys instanceof Set && !outputKeys.has(parentValueKey)) {
78
- return null;
79
- }
80
-
81
- return {
82
- key,
83
- relation: {
84
- kind: "collection",
85
- namespace,
86
- apiPath,
87
- foreignKey,
88
- parentValueKey,
89
- hydrateOnList: relation.hydrateOnList !== false,
90
- hydrateOnView: relation.hydrateOnView !== false
91
- }
92
- };
93
- }
94
-
95
- function normalizeLookupDefaultInclude(value) {
96
- const normalized = normalizeText(value);
97
- if (!normalized) {
98
- return DEFAULT_LOOKUP_INCLUDE;
99
- }
100
-
101
- if (normalized.toLowerCase() === "none") {
102
- return "none";
103
- }
104
-
105
- return normalized;
106
- }
107
-
108
- function normalizeLookupMaxDepth(value) {
109
- const parsed = Number(value);
110
- if (!Number.isInteger(parsed) || parsed < 0) {
111
- return DEFAULT_LOOKUP_MAX_DEPTH;
112
- }
113
-
114
- return Math.min(parsed, MAX_LOOKUP_MAX_DEPTH);
115
- }
116
-
117
- function resolveLookupRuntimeDefaults(resource = {}) {
118
- const lookupContract = resource?.contract?.lookup;
119
- if (
120
- lookupContract !== undefined &&
121
- lookupContract !== null &&
122
- (typeof lookupContract !== "object" || Array.isArray(lookupContract))
123
- ) {
124
- throw new TypeError("crud lookup runtime requires resource.contract.lookup to be an object when provided.");
125
- }
126
-
127
- return {
128
- defaultInclude: normalizeLookupDefaultInclude(lookupContract?.defaultInclude),
129
- maxDepth: normalizeLookupMaxDepth(lookupContract?.maxDepth)
130
- };
131
- }
132
-
133
- function createCrudLookupRuntime(resource = {}, { outputKeys = [] } = {}) {
134
- const outputKeySet = new Set(
135
- (Array.isArray(outputKeys) ? outputKeys : [])
136
- .map((key) => normalizeText(key))
137
- .filter(Boolean)
138
- );
139
-
140
- const sourceEntries = Object.values(buildCrudFieldContractMap(resource, {
141
- context: "crud lookup runtime field contract"
142
- }));
143
- const lookupEntries = [];
144
- const seenKeys = new Set();
145
-
146
- for (const entry of sourceEntries) {
147
- const normalizedEntry = normalizeLookupRelationEntry(entry, outputKeySet);
148
- if (!normalizedEntry) {
149
- continue;
150
- }
151
-
152
- if (seenKeys.has(normalizedEntry.key)) {
153
- continue;
154
- }
155
- seenKeys.add(normalizedEntry.key);
156
- lookupEntries.push(normalizedEntry);
157
- }
158
-
159
- const lookupEntryByKey = lookupEntries.reduce((accumulator, entry) => {
160
- accumulator[entry.key] = entry;
161
- return accumulator;
162
- }, {});
163
-
164
- const containerKey = resolveCrudLookupContainerKey(resource, {
165
- context: "crud lookup runtime container key"
166
- });
167
- const namespace =
168
- normalizeCrudLookupNamespace(resource?.namespace) ||
169
- normalizeCrudLookupNamespace(resource?.apiPath);
170
- const defaults = resolveLookupRuntimeDefaults(resource);
171
-
172
- return {
173
- namespace,
174
- containerKey,
175
- defaultInclude: defaults.defaultInclude,
176
- maxDepth: defaults.maxDepth,
177
- entries: lookupEntries,
178
- byKey: lookupEntryByKey
179
- };
180
- }
181
-
182
- function normalizeLookupIdentifier(value) {
183
- const normalized = normalizeOpaqueId(value);
184
- if (normalized == null) {
185
- return "";
186
- }
187
-
188
- return normalizeText(normalized);
189
- }
190
-
191
- function normalizeIncludePaths(include, { defaultInclude = DEFAULT_LOOKUP_INCLUDE } = {}) {
192
- const sourceInclude = normalizeText(include);
193
- const normalizedInclude = sourceInclude || normalizeLookupDefaultInclude(defaultInclude);
194
- if (!normalizedInclude || normalizedInclude.toLowerCase() === "none") {
195
- return [];
196
- }
197
-
198
- const tokens = normalizeUniqueTextList(normalizedInclude.split(","));
199
- const paths = [];
200
-
201
- for (const token of tokens) {
202
- const normalizedToken = normalizeText(token);
203
- if (!normalizedToken) {
204
- continue;
205
- }
206
-
207
- if (normalizedToken.toLowerCase() === "none") {
208
- return [];
209
- }
210
-
211
- const segments = normalizedToken
212
- .split(".")
213
- .map((entry) => normalizeText(entry))
214
- .filter(Boolean);
215
-
216
- if (segments.length > 0) {
217
- paths.push(segments);
218
- }
219
- }
220
-
221
- return paths;
222
- }
223
-
224
- function resolveChildIncludeFromPaths(paths = []) {
225
- const entries = Array.isArray(paths) ? paths : [];
226
- const pathKeys = new Set();
227
- let includesAll = false;
228
-
229
- for (const path of entries) {
230
- if (!Array.isArray(path) || path.length < 1) {
231
- continue;
232
- }
233
-
234
- const normalizedPath = path
235
- .map((entry) => normalizeText(entry))
236
- .filter(Boolean);
237
- if (normalizedPath.length < 1) {
238
- continue;
239
- }
240
- if (normalizedPath[0] === "*") {
241
- includesAll = true;
242
- continue;
243
- }
244
- pathKeys.add(normalizedPath.join("."));
245
- }
246
-
247
- if (includesAll) {
248
- return "*";
249
- }
250
- if (pathKeys.size < 1) {
251
- return "none";
252
- }
253
- return [...pathKeys].join(",");
254
- }
255
-
256
- function buildLookupHydrationPlan(
257
- runtime = {},
258
- include,
259
- {
260
- mode = "list",
261
- context = "crudRepository",
262
- includeWasExplicit = false,
263
- skippedNamespaces = new Set()
264
- } = {}
265
- ) {
266
- const entries = Array.isArray(runtime?.entries) ? runtime.entries : [];
267
- if (entries.length < 1) {
268
- return {
269
- entries: [],
270
- childIncludeByKey: {}
271
- };
272
- }
273
-
274
- const includePaths = normalizeIncludePaths(include, {
275
- defaultInclude: runtime?.defaultInclude
276
- });
277
- if (includePaths.length < 1) {
278
- return {
279
- entries: [],
280
- childIncludeByKey: {}
281
- };
282
- }
283
-
284
- const shouldHydrateByMode = mode === "view"
285
- ? (entry) => entry?.relation?.hydrateOnView !== false
286
- : (entry) => entry?.relation?.hydrateOnList !== false;
287
-
288
- const selectedByKey = new Map();
289
- function ensureSelection(entry = null) {
290
- if (!entry) {
291
- return null;
292
- }
293
- if (skippedNamespaces instanceof Set && skippedNamespaces.has(entry?.relation?.namespace)) {
294
- return null;
295
- }
296
-
297
- if (!includeWasExplicit && !shouldHydrateByMode(entry)) {
298
- return null;
299
- }
300
-
301
- if (!selectedByKey.has(entry.key)) {
302
- selectedByKey.set(entry.key, {
303
- entry,
304
- childPaths: [],
305
- childPathSet: new Set()
306
- });
307
- }
308
-
309
- return selectedByKey.get(entry.key);
310
- }
311
-
312
- function appendChildPath(selection, segments = []) {
313
- const sourceSegments = Array.isArray(segments) ? segments : [];
314
- if (sourceSegments.length < 1) {
315
- return;
316
- }
317
-
318
- const normalizedSegments = sourceSegments
319
- .map((entry) => normalizeText(entry))
320
- .filter(Boolean);
321
- if (normalizedSegments.length < 1) {
322
- return;
323
- }
324
-
325
- const pathKey = normalizedSegments.join(".");
326
- if (selection.childPathSet.has(pathKey)) {
327
- return;
328
- }
329
-
330
- selection.childPathSet.add(pathKey);
331
- selection.childPaths.push(normalizedSegments);
332
- }
333
-
334
- for (const pathSegments of includePaths) {
335
- const [head, ...tail] = pathSegments;
336
- if (!head) {
337
- continue;
338
- }
339
-
340
- if (head === "*") {
341
- const wildcardTail = tail.length > 0 ? tail : ["*"];
342
- for (const entry of entries) {
343
- const selection = ensureSelection(entry);
344
- if (!selection) {
345
- continue;
346
- }
347
- appendChildPath(selection, wildcardTail);
348
- }
349
- continue;
350
- }
351
-
352
- const entry = runtime?.byKey?.[head] || null;
353
- if (!entry) {
354
- throw new Error(`${context} include references unknown lookup key "${head}".`);
355
- }
356
-
357
- const selection = ensureSelection(entry);
358
- if (!selection) {
359
- continue;
360
- }
361
-
362
- if (tail.length > 0) {
363
- appendChildPath(selection, tail);
364
- }
365
- }
366
-
367
- const selectedEntries = [];
368
- const childIncludeByKey = {};
369
- for (const selection of selectedByKey.values()) {
370
- selectedEntries.push(selection.entry);
371
- childIncludeByKey[selection.entry.key] = resolveChildIncludeFromPaths(selection.childPaths);
372
- }
373
-
374
- return {
375
- entries: selectedEntries,
376
- childIncludeByKey
377
- };
378
- }
379
-
380
- function resolveLookupResolver(repositoryOptions = {}, callOptions = {}, { context = "crudRepository" } = {}) {
381
- const resolver = callOptions?.resolveLookup || repositoryOptions?.resolveLookup;
382
- if (typeof resolver !== "function") {
383
- throw new TypeError(`${context} requires resolveLookup(relation) to hydrate lookups.`);
384
- }
385
- return resolver;
386
- }
387
-
388
- function resolveLookupDepthRuntime(runtime = {}, repositoryOptions = {}, callOptions = {}) {
389
- const maxDepth = normalizeLookupMaxDepth(
390
- callOptions?.lookupMaxDepth ?? repositoryOptions?.lookupMaxDepth ?? runtime?.maxDepth
391
- );
392
-
393
- const parsedDepth = Number(callOptions?.lookupDepth);
394
- const depth = Number.isInteger(parsedDepth) && parsedDepth >= 0 ? parsedDepth : 0;
395
-
396
- return {
397
- depth,
398
- maxDepth
399
- };
400
- }
401
-
402
- function buildLookupGroupKey(relation = {}) {
403
- if (relation?.kind === "collection") {
404
- return `collection::${relation.namespace}::${relation.foreignKey}::${relation.parentValueKey}`;
405
- }
406
- return `lookup::${relation.namespace}::${relation.valueKey}`;
407
- }
408
-
409
- function normalizeLookupRelationValues(records = [], entries = [], childIncludeByKey = {}) {
410
- const byGroup = new Map();
411
- for (const entry of entries) {
412
- const relation = entry.relation;
413
- const groupKey = buildLookupGroupKey(relation);
414
- if (!byGroup.has(groupKey)) {
415
- byGroup.set(groupKey, {
416
- relation,
417
- entries: [],
418
- values: [],
419
- childIncludes: new Set()
420
- });
421
- }
422
-
423
- const group = byGroup.get(groupKey);
424
- group.entries.push(entry);
425
- group.childIncludes.add(normalizeText(childIncludeByKey?.[entry.key]) || "none");
426
- }
427
-
428
- for (const group of byGroup.values()) {
429
- const seen = new Set();
430
- for (const record of records) {
431
- for (const entry of group.entries) {
432
- const relation = entry?.relation || {};
433
- const rawValue = relation.kind === "collection"
434
- ? record?.[relation.parentValueKey]
435
- : record?.[entry.key];
436
- const normalized = normalizeLookupIdentifier(rawValue);
437
- if (!normalized || seen.has(normalized)) {
438
- continue;
439
- }
440
- seen.add(normalized);
441
- group.values.push(rawValue);
442
- }
443
- }
444
- }
445
-
446
- return byGroup;
447
- }
448
-
449
- function resolveGroupChildInclude(group = {}) {
450
- const sourceIncludes = group?.childIncludes instanceof Set ? [...group.childIncludes] : [];
451
- const includeSet = new Set();
452
- let includeAll = false;
453
-
454
- for (const includeValue of sourceIncludes) {
455
- const normalized = normalizeText(includeValue);
456
- if (!normalized || normalized.toLowerCase() === "none") {
457
- continue;
458
- }
459
-
460
- if (normalized === "*") {
461
- includeAll = true;
462
- continue;
463
- }
464
-
465
- for (const token of normalizeUniqueTextList(normalized.split(","))) {
466
- if (token === "*") {
467
- includeAll = true;
468
- continue;
469
- }
470
- includeSet.add(token);
471
- }
472
- }
473
-
474
- if (includeAll) {
475
- return "*";
476
- }
477
- if (includeSet.size < 1) {
478
- return "none";
479
- }
480
- return [...includeSet].join(",");
481
- }
482
-
483
- function normalizeLookup(provider, relation = {}, { context = "crudRepository" } = {}) {
484
- if (!provider || typeof provider !== "object" || Array.isArray(provider)) {
485
- throw new Error(`${context} could not resolve lookup "${relation.namespace}".`);
486
- }
487
- if (typeof provider.listByIds !== "function") {
488
- throw new Error(`${context} lookup "${relation.namespace}" must expose listByIds(ids, options).`);
489
- }
490
- return provider;
491
- }
492
-
493
- function resolveLookupOwnershipFilter(provider = {}, { context = "crudRepository" } = {}) {
494
- const normalizedOwnershipFilter = normalizeText(provider?.ownershipFilter).toLowerCase();
495
- if (!normalizedOwnershipFilter) {
496
- return "";
497
- }
498
-
499
- if (LOOKUP_OWNERSHIP_FILTER_SET.has(normalizedOwnershipFilter)) {
500
- return normalizedOwnershipFilter;
501
- }
502
-
503
- throw new TypeError(
504
- `${context} lookup ownershipFilter must be one of: ${LOOKUP_OWNERSHIP_FILTER_VALUES.join(", ")}.`
505
- );
506
- }
507
-
508
- function resolveLookupVisibilityContext(
509
- provider = {},
510
- relation = {},
511
- callOptions = {},
512
- { context = "crudRepository" } = {}
513
- ) {
514
- const parentVisibilityContext = normalizeVisibilityContext(callOptions?.visibilityContext);
515
- const lookupOwnershipFilter = resolveLookupOwnershipFilter(provider, {
516
- context
517
- });
518
-
519
- if (!lookupOwnershipFilter) {
520
- if (parentVisibilityContext.visibility !== "public") {
521
- throw new Error(
522
- `${context} lookup "${relation.namespace}" must declare ownershipFilter when parent visibility is "${parentVisibilityContext.visibility}".`
523
- );
524
- }
525
- return callOptions?.visibilityContext;
526
- }
527
-
528
- const nextVisibilityContext = {
529
- visibility: lookupOwnershipFilter
530
- };
531
- if (lookupOwnershipFilter === "workspace" || lookupOwnershipFilter === "workspace_user") {
532
- nextVisibilityContext.scopeOwnerId = parentVisibilityContext.scopeOwnerId;
533
- }
534
- if (lookupOwnershipFilter === "user" || lookupOwnershipFilter === "workspace_user") {
535
- nextVisibilityContext.userId = parentVisibilityContext.userId;
536
- }
537
-
538
- return nextVisibilityContext;
539
- }
540
-
541
- function buildLookupRecordMap(records = [], valueKey = "") {
542
- const lookupMap = new Map();
543
- for (const record of Array.isArray(records) ? records : []) {
544
- const lookupId = normalizeLookupIdentifier(record?.[valueKey]);
545
- if (!lookupId || lookupMap.has(lookupId)) {
546
- continue;
547
- }
548
- lookupMap.set(lookupId, record);
549
- }
550
- return lookupMap;
551
- }
552
-
553
- function buildLookupCollectionMap(records = [], foreignKey = "") {
554
- const collectionMap = new Map();
555
- for (const record of Array.isArray(records) ? records : []) {
556
- const ownerId = normalizeLookupIdentifier(record?.[foreignKey]);
557
- if (!ownerId) {
558
- continue;
559
- }
560
- const currentRecords = collectionMap.get(ownerId);
561
- if (currentRecords) {
562
- currentRecords.push(record);
563
- continue;
564
- }
565
- collectionMap.set(ownerId, [record]);
566
- }
567
- return collectionMap;
568
- }
569
-
570
- function resolveLookupVisitedNamespaces(runtime = {}, callOptions = {}) {
571
- const namespaces = [];
572
- const seen = new Set();
573
-
574
- function appendNamespace(value) {
575
- const normalized = normalizeCrudLookupNamespace(value);
576
- if (!normalized || seen.has(normalized)) {
577
- return;
578
- }
579
- seen.add(normalized);
580
- namespaces.push(normalized);
581
- }
582
-
583
- const sourceVisitedNamespaces = Array.isArray(callOptions?.lookupVisitedNamespaces)
584
- ? callOptions.lookupVisitedNamespaces
585
- : [];
586
- for (const namespace of sourceVisitedNamespaces) {
587
- appendNamespace(namespace);
588
- }
589
- appendNamespace(runtime?.namespace);
590
-
591
- return namespaces;
592
- }
593
-
594
- async function hydrateCrudLookupRecords(
595
- records = [],
596
- runtime = {},
597
- {
598
- include,
599
- mode = "list",
600
- repositoryOptions = {},
601
- callOptions = {}
602
- } = {}
603
- ) {
604
- const sourceRecords = Array.isArray(records) ? records : [];
605
- if (sourceRecords.length < 1) {
606
- return sourceRecords;
607
- }
608
-
609
- const depthRuntime = resolveLookupDepthRuntime(runtime, repositoryOptions, callOptions);
610
- if (depthRuntime.depth >= depthRuntime.maxDepth) {
611
- return sourceRecords;
612
- }
613
-
614
- const lookupContainerKey = normalizeCrudLookupContainerKey(runtime?.containerKey, {
615
- context: `${runtime?.context || "crudRepository"} lookup runtime container key`
616
- });
617
- const visitedNamespaces = resolveLookupVisitedNamespaces(runtime, callOptions);
618
-
619
- const lookupPlan = buildLookupHydrationPlan(runtime, include, {
620
- mode,
621
- context: runtime?.context || "crudRepository",
622
- includeWasExplicit: normalizeText(include).length > 0,
623
- skippedNamespaces: new Set(visitedNamespaces)
624
- });
625
- const selectedEntries = lookupPlan.entries;
626
- if (selectedEntries.length < 1) {
627
- return sourceRecords;
628
- }
629
-
630
- const resolveLookup = resolveLookupResolver(repositoryOptions, callOptions, {
631
- context: runtime?.context || "crudRepository"
632
- });
633
-
634
- const relationGroups = normalizeLookupRelationValues(sourceRecords, selectedEntries, lookupPlan.childIncludeByKey);
635
- const groupRecordMaps = new Map();
636
- for (const group of relationGroups.values()) {
637
- if (group.values.length < 1) {
638
- groupRecordMaps.set(buildLookupGroupKey(group.relation), new Map());
639
- continue;
640
- }
641
-
642
- const provider = normalizeLookup(resolveLookup(group.relation), group.relation, {
643
- context: runtime?.context || "crudRepository"
644
- });
645
- const childVisibilityContext = resolveLookupVisibilityContext(
646
- provider,
647
- group.relation,
648
- callOptions,
649
- {
650
- context: runtime?.context || "crudRepository"
651
- }
652
- );
653
- const childInclude = resolveGroupChildInclude(group);
654
- const groupValueKey = group?.relation?.kind === "collection"
655
- ? group.relation.foreignKey
656
- : group.relation.valueKey;
657
- const groupRecords = await provider.listByIds(group.values, {
658
- ...callOptions,
659
- visibilityContext: childVisibilityContext,
660
- include: childInclude,
661
- lookupDepth: depthRuntime.depth + 1,
662
- lookupMaxDepth: depthRuntime.maxDepth,
663
- lookupVisitedNamespaces: visitedNamespaces,
664
- valueKey: groupValueKey
665
- });
666
- groupRecordMaps.set(
667
- buildLookupGroupKey(group.relation),
668
- group?.relation?.kind === "collection"
669
- ? buildLookupCollectionMap(groupRecords, group.relation.foreignKey)
670
- : buildLookupRecordMap(groupRecords, group.relation.valueKey)
671
- );
672
- }
673
-
674
- return sourceRecords.map((record) => {
675
- const baseRecord = record && typeof record === "object" && !Array.isArray(record) ? record : {};
676
- const existingLookups =
677
- baseRecord[lookupContainerKey] &&
678
- typeof baseRecord[lookupContainerKey] === "object" &&
679
- !Array.isArray(baseRecord[lookupContainerKey])
680
- ? baseRecord[lookupContainerKey]
681
- : {};
682
- const nextLookups = { ...existingLookups };
683
-
684
- for (const entry of selectedEntries) {
685
- const relation = entry.relation;
686
- const lookupMap = groupRecordMaps.get(buildLookupGroupKey(relation)) || new Map();
687
- if (relation.kind === "collection") {
688
- const ownerId = normalizeLookupIdentifier(baseRecord?.[relation.parentValueKey]);
689
- nextLookups[entry.key] = ownerId ? (lookupMap.get(ownerId) || []) : [];
690
- continue;
691
- }
692
- const lookupId = normalizeLookupIdentifier(baseRecord?.[entry.key]);
693
- if (!lookupId) {
694
- nextLookups[entry.key] = null;
695
- continue;
696
- }
697
- nextLookups[entry.key] = lookupMap.get(lookupId) || null;
698
- }
699
-
700
- return {
701
- ...baseRecord,
702
- [lookupContainerKey]: nextLookups
703
- };
704
- });
705
- }
706
-
707
- export {
708
- createCrudLookupRuntime,
709
- hydrateCrudLookupRecords
710
- };