@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,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,51 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import test from "node:test";
4
+ import { createPackageTestKnex, createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
5
+ import { bookCrud, bookResource } from "../patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js";
6
+
7
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
8
+ const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
9
+
10
+ const providerPath = new URL(
11
+ "../patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js",
12
+ import.meta.url
13
+ );
14
+
15
+ test("CRUD feature package pattern leaves repetition in the framework", async () => {
16
+ const providerSource = await readFile(providerPath, "utf8");
17
+
18
+ assert.equal(bookCrud.namespace, "books");
19
+ assert.equal(bookCrud.resource, bookResource);
20
+ assert.equal(bookResource.tableName, "books");
21
+ assert.equal(bookResource.ownership, "user");
22
+ assert.match(providerSource, /defineCrudFeature/u);
23
+ assert.doesNotMatch(providerSource, /app\.singleton|app\.service|router\.register|createRepository/u);
24
+ assert.doesNotMatch(providerSource, /generator|scaffold|receipt|provenance/u);
25
+ });
26
+
27
+ test("the pattern's books resource is owned and creates a book, its timestamps in whole seconds as declared", async (t) => {
28
+ const knex = await testKnex(t);
29
+ await knex.schema.createTable("books", (table) => {
30
+ table.increments("id");
31
+ table.integer("user_id").notNullable();
32
+ table.string("title").notNullable();
33
+ table.string("author").notNullable();
34
+ table.text("notes");
35
+ table.string("created_at").notNullable();
36
+ table.string("updated_at").notNullable();
37
+ });
38
+ const runtime = await createTestResourceRuntime({ knex });
39
+ const { books } = await runtime.own("app.books", [bookResource]);
40
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-08T01:00:00.789Z") });
41
+
42
+ // A signed-in request on a user route: the actor, and the user whose rows the route reaches.
43
+ const context = { actor: { id: "7" }, visibilityContext: { visibility: "user", scopeOwnerId: "7", userId: "7" } };
44
+ const book = await books.create({ title: "Kindred", author: "Octavia E. Butler" }, { context });
45
+ assert.equal(book.title, "Kindred");
46
+ assert.deepEqual(await knex("books").first("user_id", "created_at", "updated_at"), {
47
+ user_id: 7,
48
+ created_at: "2026-11-08 01:00:00.000",
49
+ updated_at: "2026-11-08 01:00:00.000"
50
+ });
51
+ });