@jskit-ai/crud-core 0.2.2 → 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
@@ -59,6 +59,7 @@ function normalizeScope(scope = {}) {
59
59
  .map((entry) => normalizeText(entry))
60
60
  .filter(Boolean)
61
61
  )]),
62
+ // readable-check: allow method-probe - input validation: the scope an application passes may define input()
62
63
  input: typeof scope.input === "function" ? scope.input : null
63
64
  });
64
65
  }
@@ -113,17 +114,24 @@ function normalizeOperations(operations, resource) {
113
114
  return Object.freeze([...new Set(source.map((operation) => assertCrudOperationName(operation)))]);
114
115
  }
115
116
 
116
- function resolveActionPermission(actionName, { access, workspaceScoped, permissions } = {}) {
117
+ /**
118
+ * @param {string} actionName
119
+ * @param {{ access: string, workspaceScoped: boolean, permissions: { namespace: string } & Record<string, unknown> }} policy
120
+ */
121
+ function resolveActionPermission(actionName, { access, workspaceScoped, permissions }) {
117
122
  const normalizedActionName = normalizeText(actionName).toLowerCase();
118
123
  if (!normalizedActionName) {
119
124
  throw new TypeError("CRUD action name is required.");
120
125
  }
121
- const explicitPermission = permissions?.[normalizedActionName];
126
+ const explicitPermission = permissions[normalizedActionName];
122
127
  if (explicitPermission && typeof explicitPermission === "object") {
123
128
  return explicitPermission;
124
129
  }
125
130
  if (typeof explicitPermission === "string" && explicitPermission.trim()) {
126
- return Object.freeze({ require: "all", permissions: [explicitPermission.trim()] });
131
+ return Object.freeze({
132
+ require: "all",
133
+ permissions: [explicitPermission.trim()]
134
+ });
127
135
  }
128
136
  if (access === "public") {
129
137
  return Object.freeze({ require: "none" });
@@ -131,7 +139,7 @@ function resolveActionPermission(actionName, { access, workspaceScoped, permissi
131
139
  if (workspaceScoped) {
132
140
  return Object.freeze({
133
141
  require: "all",
134
- permissions: [`crud.${permissions?.namespace || "resource"}.${normalizedActionName}`]
142
+ permissions: [`crud.${permissions.namespace}.${normalizedActionName}`]
135
143
  });
136
144
  }
137
145
  return Object.freeze({ require: "authenticated" });
@@ -144,6 +152,31 @@ function projectEnabledServiceOperations(service, operations) {
144
152
  ));
145
153
  }
146
154
 
155
+ /**
156
+ * @param {object} feature
157
+ * @param {import("./types.js").CrudResourceDefinition} feature.resource The CRUD resource definition the feature serves.
158
+ * @param {string} feature.surface The surface whose routes serve it.
159
+ * @param {string} [feature.id] Defaults to `crud.<namespace>`.
160
+ * @param {string} [feature.capability] Defaults to the feature id.
161
+ * @param {string} [feature.ownershipFilter] Defaults to the resource's autofilter, then "public".
162
+ * @param {string} [feature.relativePath] Defaults to the namespace, with dashes.
163
+ * @param {boolean} [feature.internal]
164
+ * @param {boolean} [feature.routes] False registers no HTTP routes.
165
+ * @param {object | null} [feature.listFilterQueryValidator]
166
+ * @param {object | null} [feature.searchSchema]
167
+ * @param {object | null} [feature.permissions]
168
+ * @param {import("./types.js").CrudScope} [feature.scope] The route base, validators, input keys and input() of a scoped resource.
169
+ * @param {Record<string, string>} [feature.requires] More capabilities the feature requires, by name.
170
+ * @param {((dependencies: { repository: import("./types.js").CrudRepository, resource: import("./types.js").CrudResourceDefinition } & Record<string, any>) => import("./types.js").CrudRepository | Promise<import("./types.js").CrudRepository>) | null} [feature.decorateRepository]
171
+ * Receives the CRUD repository, the resource, runtime.database, runtime.http, runtime.json-rest-api and the feature's requires.
172
+ * @param {((dependencies: { service: import("./types.js").CrudService, repository: import("./types.js").CrudRepository, resource: import("./types.js").CrudResourceDefinition } & Record<string, any>) => import("./types.js").CrudService | Promise<import("./types.js").CrudService>) | null} [feature.decorateService]
173
+ * Receives the CRUD service, the (decorated) repository, the resource and the feature's requires.
174
+ * @param {import("./types.js").CrudOperationLifecycle} [feature.operationLifecycle]
175
+ * @param {object} [feature.operationInputs]
176
+ * @param {object} [feature.actions] Custom actions, by name.
177
+ * @param {string[]} [feature.operations] Defaults to every operation the resource defines.
178
+ * @param {string} [feature.realtimeAudience] Defaults to "event_scope".
179
+ */
147
180
  function defineCrudJsonApiFeature({
148
181
  resource,
149
182
  id = "",
@@ -165,7 +198,7 @@ function defineCrudJsonApiFeature({
165
198
  actions = {},
166
199
  operations = undefined,
167
200
  realtimeAudience = "event_scope"
168
- } = {}) {
201
+ }) {
169
202
  if (!resource || typeof resource !== "object" || Array.isArray(resource)) {
170
203
  throw new TypeError("defineCrudJsonApiFeature requires resource.");
171
204
  }
@@ -279,10 +312,9 @@ function defineCrudJsonApiFeature({
279
312
  resourceApi: Object.freeze({ repository, resource, service })
280
313
  };
281
314
  },
282
- actions(dependencies) {
283
- const { resourceApi } = dependencies;
315
+ actions({ resourceApi, ...required }) {
284
316
  const actionDependencies = Object.freeze(Object.fromEntries(
285
- Object.keys(featureRequirements).map((name) => [name, dependencies[name]])
317
+ Object.keys(featureRequirements).map((name) => [name, required[name]])
286
318
  ));
287
319
  return createCrudJsonApiActions({
288
320
  namespace,
@@ -1,6 +1,6 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { resolveCrudFieldSchemaProperties } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
3
- import { normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
+ import { isRecord, normalizeObject, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import { normalizeObjectInput } from "@jskit-ai/kernel/shared/validators/inputNormalization";
5
5
 
6
6
  function normalizeFieldSet(value, { context = "crudFieldAccess", label = "field list" } = {}) {
@@ -25,20 +25,19 @@ function normalizeFieldSet(value, { context = "crudFieldAccess", label = "field
25
25
  }
26
26
 
27
27
  async function resolveFieldSet(resolver, input = {}, { context = "crudFieldAccess", label = "field list" } = {}) {
28
- const resolvedResolver = resolver;
29
- if (resolvedResolver == null) {
28
+ if (resolver == null) {
30
29
  return null;
31
30
  }
32
31
 
33
- const resolvedValue = typeof resolvedResolver === "function"
34
- ? await resolvedResolver(input)
35
- : resolvedResolver;
32
+ const resolvedValue = typeof resolver === "function"
33
+ ? await resolver(input)
34
+ : resolver;
36
35
 
37
36
  return normalizeFieldSet(resolvedValue, { context, label });
38
37
  }
39
38
 
40
39
  function resolveWriteMode(fieldAccess = {}, { context = "crudFieldAccess" } = {}) {
41
- const writeMode = normalizeText(fieldAccess?.writeMode || "throw").toLowerCase();
40
+ const writeMode = normalizeText(fieldAccess.writeMode || "throw").toLowerCase();
42
41
  if (writeMode === "throw" || writeMode === "strip") {
43
42
  return writeMode;
44
43
  }
@@ -46,7 +45,7 @@ function resolveWriteMode(fieldAccess = {}, { context = "crudFieldAccess" } = {}
46
45
  throw new TypeError(`${context} fieldAccess.writeMode must be "throw" or "strip".`);
47
46
  }
48
47
 
49
- function buildOutputFieldRules(resource = {}) {
48
+ function buildOutputFieldRules(resource) {
50
49
  const outputProperties = resolveCrudFieldSchemaProperties(resource?.operations?.view?.output, {
51
50
  context: "crudFieldAccess resource.operations.view.output"
52
51
  });
@@ -79,12 +78,12 @@ function buildOutputFieldRules(resource = {}) {
79
78
  });
80
79
  }
81
80
 
82
- function resolveRoleFromFieldAccessInput(input = {}) {
81
+ function resolveRoleFromFieldAccessInput(input) {
83
82
  const role = normalizeText(input?.context?.auth?.role).toLowerCase();
84
83
  return role || "default";
85
84
  }
86
85
 
87
- function resolveActionFromFieldAccessInput(input = {}) {
86
+ function resolveActionFromFieldAccessInput(input) {
88
87
  const action = normalizeText(input?.action).toLowerCase();
89
88
  return action || "*";
90
89
  }
@@ -101,7 +100,7 @@ function resolveOperationPolicyValue(operationPolicy, input = {}, action = "*")
101
100
  ) {
102
101
  return operationPolicy;
103
102
  }
104
- if (typeof operationPolicy !== "object" || Array.isArray(operationPolicy)) {
103
+ if (typeof operationPolicy !== "object") {
105
104
  return null;
106
105
  }
107
106
 
@@ -139,31 +138,41 @@ function createFieldAccessForRoleMatrix(matrix = {}, { context = "crudFieldAcces
139
138
  { context: `${context} createFieldAccessForRoleMatrix` }
140
139
  );
141
140
 
141
+ function readable(input = {}) {
142
+ return resolveRoleMatrixPolicy(sourceMatrix, "readable", input);
143
+ }
144
+
145
+ function writable(input = {}) {
146
+ return resolveRoleMatrixPolicy(sourceMatrix, "writable", input);
147
+ }
148
+
142
149
  return Object.freeze({
143
- readable(input = {}) {
144
- return resolveRoleMatrixPolicy(sourceMatrix, "readable", input);
145
- },
146
- writable(input = {}) {
147
- return resolveRoleMatrixPolicy(sourceMatrix, "writable", input);
148
- },
150
+ readable,
151
+ writable,
149
152
  writeMode
150
153
  });
151
154
  }
152
155
 
153
- function applyReadableFieldPolicyToRecord(record, allowedFields, outputRules = null, { context = "crudFieldAccess" } = {}) {
154
- if (!record || typeof record !== "object" || Array.isArray(record) || !allowedFields) {
156
+ /**
157
+ * The record with the fields the caller may not read removed, or nulled or
158
+ * defaulted where the output schema requires them. outputRules is present
159
+ * whenever allowedFields is: resolveReadableAllowedFields refuses a readable
160
+ * policy on a resource with no view output.
161
+ */
162
+ function applyReadableFieldPolicyToRecord(record, allowedFields, outputRules, { context = "crudFieldAccess" } = {}) {
163
+ if (!isRecord(record) || !allowedFields) {
155
164
  return record;
156
165
  }
157
166
 
158
167
  const nextRecord = { ...record };
159
- const fieldRules = outputRules?.fieldRules instanceof Map ? outputRules.fieldRules : null;
168
+ const { fieldRules } = outputRules;
160
169
 
161
170
  for (const fieldKey of Object.keys(nextRecord)) {
162
171
  if (allowedFields.has(fieldKey)) {
163
172
  continue;
164
173
  }
165
174
 
166
- const fieldRule = fieldRules?.get(fieldKey);
175
+ const fieldRule = fieldRules.get(fieldKey);
167
176
  if (!fieldRule || fieldRule.required !== true) {
168
177
  delete nextRecord[fieldKey];
169
178
  continue;
@@ -192,7 +201,7 @@ function createCrudFieldAccessRuntime(resource = {}, { context = "crudFieldAcces
192
201
 
193
202
  async function resolveReadableAllowedFields(fieldAccess = {}, input = {}) {
194
203
  const allowedFields = await resolveFieldSet(
195
- fieldAccess?.readable,
204
+ fieldAccess.readable,
196
205
  input,
197
206
  {
198
207
  context,
@@ -211,7 +220,7 @@ function createCrudFieldAccessRuntime(resource = {}, { context = "crudFieldAcces
211
220
 
212
221
  async function enforceWritablePayload(payload = {}, fieldAccess = {}, input = {}) {
213
222
  const allowedFields = await resolveFieldSet(
214
- fieldAccess?.writable,
223
+ fieldAccess.writable,
215
224
  input,
216
225
  {
217
226
  context,
@@ -286,5 +295,4 @@ function createCrudFieldAccessRuntime(resource = {}, { context = "crudFieldAcces
286
295
  });
287
296
  }
288
297
 
289
- export { createCrudFieldAccessRuntime };
290
- export { createFieldAccessForRoleMatrix };
298
+ export { createCrudFieldAccessRuntime, createFieldAccessForRoleMatrix };