@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
@@ -13,8 +13,7 @@ import {
13
13
  createJsonApiFieldsetsQueryValidator,
14
14
  createCrudParentFilterQueryValidator,
15
15
  createStandardCrudListQueryValidators,
16
- createStandardCrudViewQueryValidators,
17
- resolveCrudParentFilterKeys
16
+ createStandardCrudViewQueryValidators
18
17
  } from "../src/server/listQueryValidators.js";
19
18
 
20
19
  function composeSchemaDefinition(...definitions) {
@@ -168,58 +167,6 @@ test("createCrudCursorPaginationQueryValidator allows opaque cursor strings for
168
167
  });
169
168
  });
170
169
 
171
- test("resolveCrudParentFilterKeys returns lookup keys that exist in create schema", () => {
172
- const resource = createCrudResource({
173
- viewFields: {
174
- contactId: {
175
- type: "integer",
176
- relation: {
177
- kind: "lookup",
178
- apiPath: "/contacts",
179
- valueKey: "id"
180
- }
181
- },
182
- vetId: {
183
- type: "integer",
184
- relation: {
185
- kind: "lookup",
186
- apiPath: "/vets",
187
- valueKey: "id"
188
- }
189
- },
190
- ignoredLookup: {
191
- type: "integer",
192
- relation: {
193
- kind: "lookup",
194
- apiPath: "/ignored",
195
- valueKey: "id"
196
- }
197
- }
198
- },
199
- createFields: {
200
- contactId: {
201
- type: "integer",
202
- relation: {
203
- kind: "lookup",
204
- apiPath: "/contacts",
205
- valueKey: "id"
206
- }
207
- },
208
- name: { type: "string" },
209
- vetId: {
210
- type: "integer",
211
- relation: {
212
- kind: "lookup",
213
- apiPath: "/vets",
214
- valueKey: "id"
215
- }
216
- }
217
- }
218
- });
219
-
220
- assert.deepEqual(resolveCrudParentFilterKeys(resource), ["contactId", "vetId"]);
221
- });
222
-
223
170
  test("createCrudParentFilterQueryValidator normalizes configured parent filters", async () => {
224
171
  const validator = createCrudParentFilterQueryValidator(createCrudResource({
225
172
  viewFields: {
@@ -1,88 +1,38 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import {
4
- createCrudJsonApiServiceEvents,
5
- createCrudServiceEvents,
6
- resolveCrudEntityIdFromArgs,
7
- resolveCrudEntityIdFromResult,
8
- resolveCrudJsonApiEntityIdFromResult
9
- } from "../src/server/serviceEvents.js";
10
-
11
- test("createCrudServiceEvents builds CRUD realtime events from resource namespace", () => {
12
- const events = createCrudServiceEvents({
13
- namespace: "contacts"
14
- });
15
-
16
- assert.equal(events.createRecord[0].realtime.event, "contacts.record.changed");
17
- assert.equal(events.updateRecord[0].realtime.event, "contacts.record.changed");
18
- assert.equal(events.deleteRecord[0].realtime.event, "contacts.record.changed");
3
+ import { returnJsonApiData, returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
4
+ import { buildCrudRecordChangedEvent, resolveCrudJsonApiEntityIdFromResult } from "../src/server/serviceEvents.js";
5
+
6
+ test("resolveCrudJsonApiEntityIdFromResult reads the created record's id from a tagged JSON:API result of either kind", () => {
7
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: returnJsonApiDocument({ data: { id: 15 } }) }), "15");
8
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: returnJsonApiData({ id: 16, title: "Kindred" }) }), "16");
9
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: { data: { id: 17 } } }), "",
10
+ "an untagged document is not a create result");
11
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: { kind: "document", value: { data: { id: 18 } } } }), "",
12
+ "a look-alike without the result tag is not a create result");
13
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: returnJsonApiDocument({ data: null }) }), "");
14
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: returnJsonApiData(null) }), "");
15
+ assert.equal(resolveCrudJsonApiEntityIdFromResult({ result: returnJsonApiDocument({ data: { id: " " } }) }), "");
19
16
  });
20
17
 
21
- test("createCrudServiceEvents normalizes namespace into realtime event format", () => {
22
- const events = createCrudServiceEvents({
23
- namespace: "customer-orders"
18
+ test("buildCrudRecordChangedEvent announces a CRUD record change as the namespace's record-changed event", () => {
19
+ const buildEvent = buildCrudRecordChangedEvent({
20
+ namespace: "pet-notes",
21
+ operation: "created",
22
+ entityId: resolveCrudJsonApiEntityIdFromResult,
23
+ audience: "event_scope"
24
+ });
25
+ const event = buildEvent({
26
+ context: { actor: { id: 4 } },
27
+ result: returnJsonApiDocument({ data: { type: "pet-notes", id: "12", attributes: {} } })
24
28
  });
25
29
 
26
- assert.equal(events.createRecord[0].realtime.event, "customer_orders.record.changed");
27
- });
28
-
29
- test("createCrudServiceEvents validates required resource namespace", () => {
30
- assert.throws(
31
- () => createCrudServiceEvents({}),
32
- /resource\.namespace/
33
- );
34
- });
35
-
36
- test("createCrudJsonApiServiceEvents builds JSON:API-aware create/update/delete event defaults", () => {
37
- const events = createCrudJsonApiServiceEvents("contacts");
38
-
39
- assert.equal(events.createDocument[0].realtime.event, "contacts.record.changed");
40
- assert.equal(events.patchDocumentById[0].realtime.event, "contacts.record.changed");
41
- assert.equal(events.deleteDocumentById[0].realtime.event, "contacts.record.changed");
42
- assert.equal(events.createDocument[0].entityId({
43
- result: {
44
- data: {
45
- id: "21"
46
- }
47
- }
48
- }), "21");
49
- assert.equal(events.createDocument[0].entityId({
50
- result: {
51
- kind: "document",
52
- value: {
53
- data: {
54
- id: "24"
55
- }
56
- }
57
- }
58
- }), "24");
59
- assert.equal(events.patchDocumentById[0].entityId({
60
- args: [22]
61
- }), "22");
62
- assert.equal(events.deleteDocumentById[0].entityId({
63
- args: [23]
64
- }), "23");
65
- });
66
-
67
- test("service event entity-id helpers normalize ids from args, plain results, and JSON:API results", () => {
68
- assert.equal(resolveCrudEntityIdFromArgs({ args: [12] }), "12");
69
- assert.equal(resolveCrudEntityIdFromResult({ result: { id: 13 } }), "13");
70
- assert.equal(resolveCrudJsonApiEntityIdFromResult({
71
- result: {
72
- data: {
73
- id: 14
74
- }
75
- }
76
- }), "14");
77
- assert.equal(resolveCrudJsonApiEntityIdFromResult({
78
- result: {
79
- kind: "document",
80
- value: {
81
- data: {
82
- id: 15
83
- }
84
- }
85
- }
86
- }), "15");
87
- assert.equal(resolveCrudEntityIdFromArgs({ args: [" "] }), "");
30
+ assert.equal(event.type, "entity.changed");
31
+ assert.equal(event.source, "crud");
32
+ assert.equal(event.entity, "record");
33
+ assert.equal(event.operation, "created");
34
+ assert.equal(event.entityId, "12");
35
+ assert.equal(event.actorId, "4");
36
+ assert.equal(event.realtime.event, "pet_notes.record.changed");
37
+ assert.equal(event.realtime.audience, "event_scope");
88
38
  });
@@ -0,0 +1,37 @@
1
+ // The options defineCrudJsonApiFeature resolves before it calls createCrudJsonApiActions and
2
+ // registerCrudJsonApiRoutes, for tests that call those directly with only the options they exercise.
3
+
4
+ const CRUD_OPERATIONS = Object.freeze(["list", "view", "create", "update", "delete"]);
5
+
6
+ /** @param {object} options The options a test sets; every other option takes the feature's default. */
7
+ function crudJsonApiActionOptions(options) {
8
+ return {
9
+ operations: CRUD_OPERATIONS,
10
+ scopeInputValidator: null,
11
+ scopeInputKeys: [],
12
+ listFilterQueryValidator: null,
13
+ operationLifecycle: {},
14
+ operationInputs: {},
15
+ actions: {},
16
+ dependencies: {},
17
+ realtimeAudience: "event_scope",
18
+ ...options
19
+ };
20
+ }
21
+
22
+ /** @param {object} options The options a test sets; every other option takes the feature's default. */
23
+ function crudJsonApiRouteOptions(options) {
24
+ return {
25
+ routeBase: "/",
26
+ internal: false,
27
+ operations: CRUD_OPERATIONS,
28
+ actions: {},
29
+ operationInputs: {},
30
+ listFilterQueryValidator: null,
31
+ routeParamsValidator: null,
32
+ scopeInput: null,
33
+ ...options
34
+ };
35
+ }
36
+
37
+ export { crudJsonApiActionOptions, crudJsonApiRouteOptions };
@@ -1,181 +0,0 @@
1
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
- import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
3
- import {
4
- requireCrudNamespace
5
- } from "@jskit-ai/resource-crud-core/shared/crudNamespaceSupport";
6
- import {
7
- ROUTE_VISIBILITY_TOKENS,
8
- checkRouteVisibility,
9
- isWorkspaceRouteVisibility
10
- } from "@jskit-ai/kernel/shared/support/visibility";
11
-
12
- const CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO = "auto";
13
- const CRUD_REQUESTED_OWNERSHIP_FILTER_SET = new Set([
14
- ...ROUTE_VISIBILITY_TOKENS,
15
- CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO
16
- ]);
17
- const WORKSPACE_CAPABLE_TENANCY_MODES = new Set(["personal", "workspaces"]);
18
-
19
- function asRecord(value) {
20
- if (!value || typeof value !== "object" || Array.isArray(value)) {
21
- return {};
22
- }
23
-
24
- return value;
25
- }
26
-
27
- function normalizeCrudRequestedOwnershipFilter(value, { fallback = CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO } = {}) {
28
- const normalized = normalizeText(value).toLowerCase();
29
- if (CRUD_REQUESTED_OWNERSHIP_FILTER_SET.has(normalized)) {
30
- return normalized;
31
- }
32
-
33
- const normalizedFallback = normalizeText(fallback).toLowerCase();
34
- if (CRUD_REQUESTED_OWNERSHIP_FILTER_SET.has(normalizedFallback)) {
35
- return normalizedFallback;
36
- }
37
-
38
- return CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO;
39
- }
40
-
41
- function resolveCrudRelativePath(namespace = "") {
42
- return `/${requireCrudNamespace(namespace, {
43
- context: "resolveCrudRelativePath"
44
- })}`;
45
- }
46
-
47
- function normalizeCrudRelativePath(relativePath = "", { context = "resolveCrudSurfacePolicy" } = {}) {
48
- const normalizedPath = normalizeText(relativePath);
49
- if (!normalizedPath) {
50
- throw new TypeError(`${context} requires a non-empty relativePath.`);
51
- }
52
-
53
- const withLeadingSlash = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
54
- const compacted = withLeadingSlash.replace(/\/{2,}/g, "/");
55
- return compacted === "/" ? "/" : compacted.replace(/\/+$/, "") || "/";
56
- }
57
-
58
- function normalizeSurfaceDefinitions(sourceDefinitions = {}) {
59
- const definitions = asRecord(sourceDefinitions);
60
- const normalized = {};
61
-
62
- for (const [key, value] of Object.entries(definitions)) {
63
- const definition = asRecord(value);
64
- const surfaceId = normalizeSurfaceId(definition.id || key);
65
- if (!surfaceId) {
66
- continue;
67
- }
68
-
69
- normalized[surfaceId] = Object.freeze({
70
- ...definition,
71
- id: surfaceId,
72
- enabled: definition.enabled !== false,
73
- requiresAuth: definition.requiresAuth === true,
74
- requiresWorkspace: definition.requiresWorkspace === true
75
- });
76
- }
77
-
78
- return Object.freeze(normalized);
79
- }
80
-
81
- function resolveOwnershipFilterFromSurfaceDefinition(definition = {}) {
82
- if (definition.requiresWorkspace === true) {
83
- return "workspace";
84
- }
85
- if (definition.requiresAuth === true) {
86
- return "user";
87
- }
88
- return "public";
89
- }
90
-
91
- function resolveCrudSurfacePolicy(
92
- sourceConfig = {},
93
- {
94
- surfaceDefinitions = {},
95
- defaultSurfaceId = "",
96
- context = "resolveCrudSurfacePolicy"
97
- } = {}
98
- ) {
99
- const config = asRecord(sourceConfig);
100
- const normalizedDefinitions = normalizeSurfaceDefinitions(surfaceDefinitions);
101
- const requestedSurfaceId = normalizeSurfaceId(config.surface);
102
- const fallbackSurfaceId = normalizeSurfaceId(defaultSurfaceId);
103
- const surfaceId = requestedSurfaceId || fallbackSurfaceId;
104
- if (!surfaceId) {
105
- throw new Error(`${context} requires surface or defaultSurfaceId.`);
106
- }
107
-
108
- const surfaceDefinition = normalizedDefinitions[surfaceId];
109
- if (!surfaceDefinition) {
110
- throw new Error(`${context} cannot resolve surface "${surfaceId}".`);
111
- }
112
- if (surfaceDefinition.enabled === false) {
113
- throw new Error(`${context} surface "${surfaceId}" is disabled.`);
114
- }
115
-
116
- const requestedOwnershipFilter = normalizeCrudRequestedOwnershipFilter(config.ownershipFilter);
117
- const ownershipFilter =
118
- requestedOwnershipFilter === CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO
119
- ? resolveOwnershipFilterFromSurfaceDefinition(surfaceDefinition)
120
- : checkRouteVisibility(requestedOwnershipFilter, {
121
- context: `${context} ownershipFilter`
122
- });
123
-
124
- if (isWorkspaceRouteVisibility(ownershipFilter) && surfaceDefinition.requiresWorkspace !== true) {
125
- throw new Error(
126
- `${context} ownershipFilter "${ownershipFilter}" requires a workspace-enabled surface.`
127
- );
128
- }
129
-
130
- const relativePath = normalizeCrudRelativePath(config.relativePath || resolveCrudRelativePath(config.namespace), {
131
- context
132
- });
133
-
134
- return Object.freeze({
135
- surfaceId,
136
- ownershipFilter,
137
- requestedOwnershipFilter,
138
- workspaceScoped: isWorkspaceRouteVisibility(ownershipFilter),
139
- relativePath,
140
- surfaceDefinition
141
- });
142
- }
143
-
144
- function resolveCrudSurfacePolicyFromAppConfig(sourceConfig = {}, appConfig = {}, options = {}) {
145
- const config = asRecord(appConfig);
146
- const requestedSurfaceId = normalizeSurfaceId(asRecord(sourceConfig).surface);
147
- const fallbackSurfaceId = normalizeSurfaceId(config.surfaceDefaultId);
148
- const resolvedSurfaceId = requestedSurfaceId || fallbackSurfaceId;
149
-
150
- try {
151
- return resolveCrudSurfacePolicy(sourceConfig, {
152
- ...asRecord(options),
153
- surfaceDefinitions: config.surfaceDefinitions,
154
- defaultSurfaceId: config.surfaceDefaultId
155
- });
156
- } catch (error) {
157
- const normalizedTenancyMode = normalizeText(config.tenancyMode).toLowerCase();
158
- const message = String(error?.message || "");
159
- if (
160
- message.includes("cannot resolve surface") &&
161
- (resolvedSurfaceId === "admin" || resolvedSurfaceId === "app") &&
162
- WORKSPACE_CAPABLE_TENANCY_MODES.has(normalizedTenancyMode)
163
- ) {
164
- error.message = `${message} Workspace-capable tenancy mode "${normalizedTenancyMode}" usually requires ` +
165
- '@jskit-ai/workspaces-core, which defines the "app" and "admin" surfaces. ' +
166
- "Install that package or add matching surface definitions in config/public.js.";
167
- }
168
- throw error;
169
- }
170
- }
171
-
172
- export {
173
- CRUD_REQUESTED_OWNERSHIP_FILTER_AUTO,
174
- normalizeCrudRequestedOwnershipFilter,
175
- isWorkspaceRouteVisibility,
176
- requireCrudNamespace,
177
- resolveCrudRelativePath,
178
- normalizeCrudRelativePath,
179
- resolveCrudSurfacePolicy,
180
- resolveCrudSurfacePolicyFromAppConfig
181
- };