@jskit-ai/crud-core 0.2.14 → 0.2.15

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 +16 -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 +509 -0
  12. package/src/server/jsonApiModule/actions.js +44 -30
  13. package/src/server/jsonApiModule/routes.js +2 -2
  14. package/src/server/jsonApiModule/service.js +213 -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 +50 -0
  23. package/test/crudOnHandles.test.js +454 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +62 -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,19 +1,27 @@
1
1
  // The types of the capability a CRUD feature provides, for features that require it,
2
- // of what its custom actions receive, and of the records repository a CRUD service uses.
2
+ // and of what its custom actions and lifecycle hooks receive.
3
3
 
4
4
  /**
5
- * The resource definition a CRUD feature serves, as defineCrudResource returns it.
6
- * @typedef {object} CrudResourceDefinition
5
+ * One table's description, as defineTableResource returns it.
6
+ * @typedef {object} TableResource
7
7
  */
8
8
 
9
9
  /**
10
- * The JSON:API repository a CRUD feature provides as its capability's `repository`.
11
- * @typedef {ReturnType<typeof import("./jsonApiModule/repository.js").createCrudJsonApiRepository>} CrudRepository
10
+ * The CRUD surface a CRUD feature serves, as defineCrudContract returns it; its
11
+ * table resource is its `resource`.
12
+ * @typedef {object} CrudContract
12
13
  */
13
14
 
14
15
  /**
15
- * The JSON:API service a CRUD feature provides as its capability's `service`.
16
- * @typedef {ReturnType<typeof import("./jsonApiModule/service.js").createCrudJsonApiService>} CrudService
16
+ * The repository a CRUD feature provides as its capability's `repository`: its
17
+ * CRUD table's handle, as decorateRepository returns it.
18
+ * @typedef {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} CrudRepository
19
+ */
20
+
21
+ /**
22
+ * The CRUD service a CRUD feature provides as its capability's `service`: list,
23
+ * view, create, patch and delete, answering JSON:API documents.
24
+ * @typedef {ReturnType<typeof import("./jsonApiModule/service.js").createCrudService>} CrudService
17
25
  */
18
26
 
19
27
  /**
@@ -39,12 +47,12 @@
39
47
  */
40
48
 
41
49
  /**
42
- * What a `defineCrudJsonApiFeature` feature provides under the capability its
43
- * application names: the resource, its repository and its service, after any
44
- * decorateRepository and decorateService. The service keeps only the methods
45
- * of the feature's enabled operations.
50
+ * What a `defineCrudFeature` feature provides under the capability its
51
+ * application names: the CRUD contract, its repository and its service, after
52
+ * any decorateRepository and decorateService. The service keeps only the
53
+ * methods of the feature's enabled operations.
46
54
  * @typedef {object} CrudResourceApi
47
- * @property {CrudResourceDefinition} resource
55
+ * @property {CrudContract} crud
48
56
  * @property {CrudRepository} repository
49
57
  * @property {CrudService} service
50
58
  */
@@ -62,7 +70,7 @@
62
70
  * @typedef {{
63
71
  * input: any,
64
72
  * context: object,
65
- * resource: CrudResourceDefinition,
73
+ * resource: CrudContract,
66
74
  * repository: Repository,
67
75
  * service: Service
68
76
  * } & Requires} CrudCustomActionInvocation
@@ -71,8 +79,9 @@
71
79
  /**
72
80
  * What an `operationLifecycle` hook receives: the operation, the input its
73
81
  * schema validated, the action context, the feature's resource, repository
74
- * and service, and `trx`, the transaction a create, update or delete runs in
75
- * (null for list and view, and in afterCommit, which runs after the commit).
82
+ * and service, and `options`, the call options to pass to the repository:
83
+ * `{ context }`, and inside a create, update or delete the transaction they
84
+ * share (afterCommit, which runs after the commit, gets `{ context }`).
76
85
  * `after` and `afterCommit` also receive the operation's `result` (the JSON:API
77
86
  * document result; null for delete); `execute` receives `standard(nextInput)`,
78
87
  * which runs the standard operation and returns its result.
@@ -84,10 +93,10 @@
84
93
  * @property {"list" | "view" | "create" | "update" | "delete"} operation
85
94
  * @property {any} input
86
95
  * @property {object} context
87
- * @property {CrudResourceDefinition} resource
96
+ * @property {CrudContract} resource
88
97
  * @property {Repository} repository
89
98
  * @property {Service} service
90
- * @property {import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction | null} trx
99
+ * @property {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
91
100
  * @property {CrudJsonApiResult | null} [result]
92
101
  * @property {(nextInput?: object) => Promise<CrudJsonApiResult | null>} [standard]
93
102
  */
@@ -120,37 +129,4 @@
120
129
  * @typedef {{ list?: CrudLifecycleHooks<Service, Repository>, view?: CrudLifecycleHooks<Service, Repository>, create?: CrudLifecycleHooks<Service, Repository>, update?: CrudLifecycleHooks<Service, Repository>, delete?: CrudLifecycleHooks<Service, Repository> }} CrudOperationLifecycle
121
130
  */
122
131
 
123
- /**
124
- * The records repository a CRUD service reads and writes through, as createCrudResourceRuntime builds it.
125
- * @typedef {ReturnType<typeof import("./resourceRuntime/index.js").createCrudResourceRuntime>} CrudRecordRepository
126
- */
127
-
128
- /**
129
- * What a records repository resolves once from its resource and options, and each of its calls reads.
130
- * @typedef {ReturnType<typeof import("./resourceRuntime/compiledRuntime.js").buildCompiledCrudRepositoryRuntime>} CompiledCrudRepositoryRuntime
131
- */
132
-
133
- /**
134
- * The repository a lookup reads: any object with listByIds().
135
- * @typedef {object} CrudLookupRepository
136
- * @property {(ids: unknown[], options?: Record<string, unknown>) => Promise<unknown>} listByIds
137
- * @property {string} [ownershipFilter] The ownership filter its records use.
138
- */
139
-
140
- /**
141
- * A records service's field access policy: the fields a call may read and
142
- * write (a list, a set, "*", or a function of the call that returns one), and
143
- * whether a write to another field throws or is stripped.
144
- * createFieldAccessForRoleMatrix builds one from a role matrix.
145
- * @typedef {object} CrudFieldAccess
146
- * @property {unknown} [readable]
147
- * @property {unknown} [writable]
148
- * @property {"throw" | "strip"} [writeMode]
149
- */
150
-
151
- /**
152
- * The resource, namespace and field access a CRUD service's methods share.
153
- * @typedef {ReturnType<typeof import("./serviceMethods.js").createCrudServiceRuntime>} CrudServiceRuntime
154
- */
155
-
156
132
  export {};
@@ -7,7 +7,8 @@ import {
7
7
  validateSchemaPayload
8
8
  } from "@jskit-ai/kernel/shared/validators";
9
9
  import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
10
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
10
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
11
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
11
12
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
12
13
  import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
13
14
 
@@ -45,37 +46,35 @@ function lookupField(namespace, relationshipName) {
45
46
  namespace,
46
47
  valueKey: "id",
47
48
  labelKey: "name"
48
- },
49
- operations: {
50
- output: { required: true }
51
49
  }
52
50
  };
53
51
  }
54
52
 
55
53
  function createBookingsResource() {
56
- return defineCrudResource({
57
- namespace: "bookings",
54
+ const bookings = defineTableResource({
55
+ name: "bookings",
58
56
  tableName: "bookings",
59
- crudOperations: ["list", "view"],
60
- contract: {
61
- lookup: {
62
- containerKey: "lookups"
63
- }
64
- },
57
+ ownership: "public",
65
58
  schema: {
66
59
  serviceId: lookupField("services", "service"),
67
60
  productId: lookupField("products", "product"),
68
61
  contactId: lookupField("contacts", "contact"),
69
62
  petId: lookupField("pets", "pet"),
70
- summary: {
71
- type: "string",
72
- required: true,
73
- operations: {
74
- output: { required: true }
75
- }
76
- }
63
+ summary: { type: "string", required: true }
77
64
  }
78
65
  });
66
+ return defineCrudContract(bookings, {
67
+ namespace: "bookings",
68
+ operations: ["list", "view"],
69
+ contract: {
70
+ lookup: {
71
+ containerKey: "lookups"
72
+ }
73
+ },
74
+ fields: Object.fromEntries(
75
+ ["serviceId", "productId", "contactId", "petId", "summary"].map((field) => [field, { output: "required" }])
76
+ )
77
+ });
79
78
  }
80
79
 
81
80
  function selectFields(source, selectedFields = null) {
@@ -155,11 +154,11 @@ function createFixture() {
155
154
  const resource = createBookingsResource();
156
155
  const calls = [];
157
156
  const service = {
158
- async queryDocuments(query, { context }) {
157
+ async list(query, { context }) {
159
158
  calls.push({ query, context });
160
159
  return returnJsonApiDocument(createBookingDocument(query));
161
160
  },
162
- async getDocumentById(_recordId, query) {
161
+ async view(_recordId, query) {
163
162
  const document = createBookingDocument(query);
164
163
  return returnJsonApiDocument({
165
164
  data: document.data[0],
@@ -1,20 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import knexLib from "knex";
4
- import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
4
  import { createServiceToolCatalog } from "@jskit-ai/assistant-core/server";
6
5
  import { createActionCatalogue } from "@jskit-ai/kernel/server/actions";
7
- import {
8
- addResourceIfMissing,
9
- createJsonRestApiHost,
10
- createJsonRestContext,
11
- createJsonRestResourceScopeOptions
12
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
13
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
6
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
7
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
8
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
14
9
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
15
10
  import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
16
- import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
17
- import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
11
+ import { createCrudService } from "../src/server/jsonApiModule/service.js";
18
12
 
19
13
  test("assistant list traverses real SQL pages with sparse fields and capped limits", async (t) => {
20
14
  const knex = knexLib({
@@ -37,33 +31,29 @@ test("assistant list traverses real SQL pages with sparse fields and capped limi
37
31
  }));
38
32
  await knex.batchInsert("books", rows, 100);
39
33
 
40
- const resource = defineCrudResource({
41
- namespace: "books",
34
+ const resource = defineTableResource({
35
+ name: "books",
42
36
  tableName: "books",
43
- autofilter: "workspace",
37
+ ownership: "workspace",
44
38
  defaultSort: ["-createdAt"],
45
- crudOperations: ["list"],
46
39
  schema: {
47
40
  id: { type: "id", primary: true },
48
41
  workspaceId: { type: "id", column: "workspace_id" },
49
- name: {
50
- type: "string",
51
- operations: { output: { required: true } }
52
- },
42
+ name: { type: "string" },
53
43
  createdAt: { type: "dateTime", temporalPrecision: 3, column: "created_at" }
54
44
  }
55
45
  });
56
- const api = await createJsonRestApiHost({ knex, logger: silentLogger });
57
- await addResourceIfMissing(api, "books", createJsonRestResourceScopeOptions(resource));
58
- const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "books" });
59
- const service = createCrudJsonApiService({ repository });
46
+ const crud = defineCrudContract(resource, { namespace: "books", operations: ["list"], fields: { name: { output: "required" } } });
47
+ const runtime = await createTestResourceRuntime({ knex });
48
+ const { books: repository } = await runtime.own("test.books", [resource]);
49
+ const service = createCrudService({ repository, crud });
60
50
  const actions = createActionCatalogue();
61
51
  actions.register({
62
52
  contributorId: "test.books",
63
53
  domain: "books",
64
54
  actions: createCrudJsonApiActions(crudJsonApiActionOptions({
65
55
  namespace: "books",
66
- resource,
56
+ resource: crud,
67
57
  repository,
68
58
  service,
69
59
  surface: "admin",
@@ -142,31 +132,31 @@ test("assistant list traverses real SQL pages with sparse fields and capped limi
142
132
  });
143
133
  }
144
134
 
145
- await t.test("plain writes and JSON:API repository writes preserve full records", async () => {
146
- const created = await api.resources.books.post({
147
- data: { id: "501", workspaceId: "1", name: "Plain record", createdAt: "2026-09-09T00:00:00.000Z" },
148
- format: "plain",
149
- returning: "full"
150
- }, createJsonRestContext(context));
135
+ await t.test("record writes and the CRUD service's documents preserve full records", async () => {
136
+ const created = await repository.create(
137
+ { id: "501", workspaceId: "1", name: "Plain record", createdAt: "2026-09-09T00:00:00.000Z" },
138
+ { context }
139
+ );
151
140
  assert.equal(created.id, "501");
152
141
  assert.equal(created.name, "Plain record");
153
- const patched = await repository.patchDocumentById("501", { name: "JSON:API update" }, { context });
154
- assert.equal(patched.data.id, "501");
155
- assert.equal(patched.data.attributes.name, "JSON:API update");
156
- const document = await repository.createDocument({
142
+ const patched = await service.patch("501", { name: "JSON:API update" }, { context });
143
+ assert.equal(patched.value.data.id, "501");
144
+ assert.equal(patched.value.data.attributes.name, "JSON:API update");
145
+ const document = await service.create({
157
146
  id: "502", workspaceId: "1", name: "JSON:API record", createdAt: "2026-09-09T00:00:00.000Z"
158
147
  }, { context });
159
- assert.equal(document.data.id, "502");
160
- assert.equal(document.data.attributes.name, "JSON:API record");
161
- assert.equal((await api.resources.books.get({ id: "502", format: "plain" }, createJsonRestContext(context))).name, "JSON:API record");
162
- await assert.rejects(api.transaction(async (trx) => {
163
- await repository.patchDocumentById("502", { name: "Rolled back" }, { trx, context });
148
+ assert.equal(document.value.data.id, "502");
149
+ assert.equal(document.value.data.attributes.name, "JSON:API record");
150
+ assert.equal((await repository.get("502", {}, { context })).name, "JSON:API record");
151
+ await assert.rejects(repository.withTransaction({ context }, async (txOptions) => {
152
+ await service.patch("502", { name: "Rolled back" }, txOptions);
164
153
  throw new Error("Rollback proof");
165
154
  }), /Rollback proof/);
166
- assert.equal((await repository.getDocumentById("502", {}, { context })).data.attributes.name, "JSON:API record");
167
- await repository.deleteDocumentById("501", { context });
168
- await repository.deleteDocumentById("502", { context });
169
- assert.equal(await repository.getDocumentById("501", {}, { context }), null);
155
+ assert.equal((await service.view("502", {}, { context })).value.data.attributes.name, "JSON:API record");
156
+ await service.delete("501", { context });
157
+ await repository.delete("502", { context });
158
+ assert.equal(await repository.get("501", {}, { context, missing: "skip" }), null);
159
+ await assert.rejects(service.view("501", {}, { context }), { status: 404, code: "crud.document.notFound" });
170
160
  assert.equal(await knex("books").whereIn("id", [501, 502]).first(), undefined);
171
161
  });
172
162
  });
@@ -23,8 +23,7 @@ test("createHooksToCollectChildren batches children and hydrates returned record
23
23
  const context = {
24
24
  callOptions: {
25
25
  trx: { id: "trx-1" },
26
- visibilityContext: { visibility: "workspace", scopeOwnerId: "workspace-1" },
27
- ignored: true
26
+ context: { workspace: { id: "workspace-1" } }
28
27
  },
29
28
  state: {}
30
29
  };
@@ -36,10 +35,7 @@ test("createHooksToCollectChildren batches children and hydrates returned record
36
35
  assert.deepEqual(calls, [
37
36
  {
38
37
  contactIds: [7, 8],
39
- options: {
40
- trx: context.callOptions.trx,
41
- visibilityContext: context.callOptions.visibilityContext
42
- }
38
+ options: context.callOptions
43
39
  }
44
40
  ]);
45
41
  assert.deepEqual(hydrated[0].lookups?.pets?.map((entry) => entry.name), ["Milo", "Luna"]);
@@ -81,12 +77,12 @@ test("createHooksToCollectChildren supports childRepository + childListMethod sh
81
77
  assert.equal(hydrated.lookups?.pets?.length, 1);
82
78
  });
83
79
 
84
- test("createHooksToCollectChildren uses childRepository.listByIds by default", async () => {
80
+ test("createHooksToCollectChildren reads every child of the page in one childRepository.queryAll by default", async () => {
85
81
  const calls = [];
86
82
  const childRepository = {
87
- async listByIds(contactIds = [], options = {}) {
83
+ async queryAll(params = {}, options = {}) {
88
84
  calls.push({
89
- contactIds,
85
+ params,
90
86
  options
91
87
  });
92
88
  return [{ id: 11, customerId: 9, name: "Milo" }];
@@ -104,19 +100,17 @@ test("createHooksToCollectChildren uses childRepository.listByIds by default", a
104
100
  },
105
101
  state: {}
106
102
  };
107
- await hooks.afterQuery([{ id: 9 }], context);
103
+ await hooks.afterQuery([{ id: 9 }, { id: 10 }], context);
108
104
  const hydrated = hooks.transformReturnedRecord({ id: 9 }, context);
109
105
 
110
106
  assert.deepEqual(calls, [
111
107
  {
112
- contactIds: [9],
113
- options: {
114
- trx: context.callOptions.trx,
115
- valueKey: "customerId"
116
- }
108
+ params: { filters: { customerId: [9, 10] } },
109
+ options: context.callOptions
117
110
  }
118
111
  ]);
119
112
  assert.equal(hydrated.lookups?.pets?.length, 1);
113
+ assert.deepEqual(hooks.transformReturnedRecord({ id: 10 }, context).lookups?.pets, []);
120
114
  });
121
115
 
122
116
  test("createHooksToCollectChildren supports override hooks for parent id, child owner id, call options, and attach", async () => {
@@ -209,13 +203,27 @@ test("createHooksToCollectChildren validates required configuration", async () =
209
203
  () =>
210
204
  createHooksToCollectChildren({
211
205
  childKey: "pets",
206
+ childRepository: {
207
+ async queryAll() {
208
+ return [];
209
+ }
210
+ }
211
+ }),
212
+ /requires childForeignKey when it reads childRepository\.queryAll/
213
+ );
214
+
215
+ assert.throws(
216
+ () =>
217
+ createHooksToCollectChildren({
218
+ childKey: "pets",
219
+ childForeignKey: "customerId",
212
220
  childRepository: {
213
221
  async listByIds() {
214
222
  return [];
215
223
  }
216
224
  }
217
225
  }),
218
- /requires childForeignKey when using childRepository\.listByIds/
226
+ /requires childRepository\.queryAll to be a function, or a childListMethod/
219
227
  );
220
228
 
221
229
  const hooks = createHooksToCollectChildren({
@@ -249,3 +257,40 @@ test("createHooksToCollectChildren requires ctx.state during afterQuery", async
249
257
  /requires ctx\.state object/
250
258
  );
251
259
  });
260
+
261
+ test("createHooksToCollectChildren names the in-filter a child table must declare for its foreign key", async () => {
262
+ const refusal = Object.assign(new Error("Value could not be cast to the required type."), {
263
+ code: "REST_API_VALIDATION",
264
+ details: { fields: ["queryParams.filters.customerId"] }
265
+ });
266
+ const hooks = createHooksToCollectChildren({
267
+ childKey: "pets",
268
+ childForeignKey: "customerId",
269
+ childRepository: {
270
+ async queryAll() {
271
+ throw refusal;
272
+ }
273
+ }
274
+ });
275
+
276
+ const error = await hooks.afterQuery([{ id: 9 }], { state: {}, callOptions: {} }).then(
277
+ () => assert.fail("expected the read to fail"),
278
+ (failure) => failure
279
+ );
280
+ assert.match(error.message, /reads the children of a page with one customerId filter listing every owner id/u);
281
+ assert.match(error.message, /customerId: \{ \.\.\., search: \{ type: "array", filterOperator: "in" \} \}/u);
282
+ assert.equal(error.cause, refusal);
283
+
284
+ // Any other failure passes through untouched.
285
+ const other = new Error("connection lost");
286
+ const passing = createHooksToCollectChildren({
287
+ childKey: "pets",
288
+ childForeignKey: "customerId",
289
+ childRepository: {
290
+ async queryAll() {
291
+ throw other;
292
+ }
293
+ }
294
+ });
295
+ await assert.rejects(() => passing.afterQuery([{ id: 9 }], { state: {}, callOptions: {} }), (failure) => failure === other);
296
+ });
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import test from "node:test";
4
+ import knexLib from "knex";
5
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
6
+ import { bookCrud, bookResource } from "../patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js";
7
+
8
+ const providerPath = new URL(
9
+ "../patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js",
10
+ import.meta.url
11
+ );
12
+
13
+ test("CRUD feature package pattern leaves repetition in the framework", async () => {
14
+ const providerSource = await readFile(providerPath, "utf8");
15
+
16
+ assert.equal(bookCrud.namespace, "books");
17
+ assert.equal(bookCrud.resource, bookResource);
18
+ assert.equal(bookResource.tableName, "books");
19
+ assert.equal(bookResource.ownership, "user");
20
+ assert.match(providerSource, /defineCrudFeature/u);
21
+ assert.doesNotMatch(providerSource, /app\.singleton|app\.service|router\.register|createRepository/u);
22
+ assert.doesNotMatch(providerSource, /generator|scaffold|receipt|provenance/u);
23
+ });
24
+
25
+ test("the pattern's books resource is owned and creates a book, its timestamps in whole seconds as declared", async (t) => {
26
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
27
+ t.after(() => knex.destroy());
28
+ await knex.schema.createTable("books", (table) => {
29
+ table.increments("id");
30
+ table.integer("user_id").notNullable();
31
+ table.string("title").notNullable();
32
+ table.string("author").notNullable();
33
+ table.text("notes");
34
+ table.string("created_at").notNullable();
35
+ table.string("updated_at").notNullable();
36
+ });
37
+ const runtime = await createTestResourceRuntime({ knex });
38
+ const { books } = await runtime.own("app.books", [bookResource]);
39
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-08T01:00:00.789Z") });
40
+
41
+ // A signed-in request on a user route: the actor, and the user whose rows the route reaches.
42
+ const context = { actor: { id: "7" }, visibilityContext: { visibility: "user", scopeOwnerId: "7", userId: "7" } };
43
+ const book = await books.create({ title: "Kindred", author: "Octavia E. Butler" }, { context });
44
+ assert.equal(book.title, "Kindred");
45
+ assert.deepEqual(await knex("books").first("user_id", "created_at", "updated_at"), {
46
+ user_id: 7,
47
+ created_at: "2026-11-08 01:00:00.000",
48
+ updated_at: "2026-11-08 01:00:00.000"
49
+ });
50
+ });