@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
@@ -3,13 +3,16 @@ import test from "node:test";
3
3
  import { createSchema } from "json-rest-schema";
4
4
  import { RestApiWriteError } from "json-rest-api";
5
5
 
6
- import { createActionProvider } from "@jskit-ai/kernel/server/actions";
6
+ import { ActionProvider } from "@jskit-ai/kernel/server/actions";
7
+ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
8
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
7
9
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
8
10
  import { validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
9
- import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
11
+ import { returnJsonApiData, returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
10
12
  import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
11
13
  import { defineCrudJsonApiFeature } from "../src/server/defineCrudJsonApiFeature.js";
12
14
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
15
+ import { crudJsonApiActionOptions, crudJsonApiRouteOptions } from "./support/crudJsonApiActionOptions.js";
13
16
  import { registerCrudJsonApiRoutes } from "../src/server/jsonApiModule/routes.js";
14
17
 
15
18
  function createBookResource({ apiAccess = "authenticated", autofilter = "user" } = {}) {
@@ -109,8 +112,9 @@ test("defineCrudJsonApiFeature composes one resource without ceremonial token la
109
112
  }
110
113
  });
111
114
  const runtime = createCapabilityRuntime({
115
+ inputs: { "runtime.logger": silentLogger },
112
116
  providers: [
113
- createActionProvider(),
117
+ EventProvider, ActionProvider,
114
118
  ...createFeatureDependencies(routes),
115
119
  feature,
116
120
  observer
@@ -151,7 +155,7 @@ test("defineCrudJsonApiFeature composes one resource without ceremonial token la
151
155
  });
152
156
 
153
157
  test("defineCrudJsonApiFeature sends record.changed to its realtime audience", async () => {
154
- const execution = { input: { recordId: "5" }, result: { data: { id: "5" } }, context: {} };
158
+ const execution = { input: { recordId: "5" }, result: returnJsonApiDocument({ data: { id: "5" } }), context: {} };
155
159
  for (const [options, audience] of [[{}, "event_scope"], [{ realtimeAudience: "all_users" }, "all_users"]]) {
156
160
  let actions;
157
161
  const observer = defineProvider({
@@ -163,8 +167,9 @@ test("defineCrudJsonApiFeature sends record.changed to its realtime audience", a
163
167
  }
164
168
  });
165
169
  const runtime = createCapabilityRuntime({
170
+ inputs: { "runtime.logger": silentLogger },
166
171
  providers: [
167
- createActionProvider(),
172
+ EventProvider, ActionProvider,
168
173
  ...createFeatureDependencies([]),
169
174
  defineCrudJsonApiFeature({
170
175
  resource: createBookResource({ apiAccess: "public", autofilter: "public" }),
@@ -212,7 +217,8 @@ test("defineCrudJsonApiFeature makes workspace scope and permissions explicit",
212
217
  }
213
218
  });
214
219
  const runtime = createCapabilityRuntime({
215
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature, observer]
220
+ inputs: { "runtime.logger": silentLogger },
221
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
216
222
  });
217
223
 
218
224
  await runtime.start();
@@ -229,6 +235,75 @@ test("defineCrudJsonApiFeature makes workspace scope and permissions explicit",
229
235
  await runtime.shutdown();
230
236
  });
231
237
 
238
+ test("a scoped CRUD custom action's input keeps its own mode, and one without a mode is create", async () => {
239
+ const routes = [];
240
+ const feature = defineCrudJsonApiFeature({
241
+ resource: createBookResource({ autofilter: "workspace" }),
242
+ surface: "app",
243
+ scope: {
244
+ routeBase: "/w/:workspaceSlug",
245
+ actionInputValidator: schemaDefinition({ workspaceSlug: { type: "string", required: true } }),
246
+ routeParamsValidator: schemaDefinition({ workspaceSlug: { type: "string", required: true } }),
247
+ inputKeys: ["workspaceSlug"],
248
+ input: (request) => ({ workspaceSlug: request.input.params.workspaceSlug })
249
+ },
250
+ actions: {
251
+ archive: {
252
+ input: { schema: createSchema({ recordId: { type: "string", required: true } }) },
253
+ execute: ({ input }) => input
254
+ },
255
+ rename: {
256
+ input: schemaDefinition({ recordId: { type: "string", required: true }, title: { type: "string" } }),
257
+ execute: ({ input }) => input
258
+ }
259
+ }
260
+ });
261
+ let actions;
262
+ const observer = defineProvider({
263
+ id: "test.custom-mode-observer",
264
+ requires: { actions: "runtime.actions" },
265
+ setup({ actions: value }) {
266
+ actions = value;
267
+ return {};
268
+ }
269
+ });
270
+ const runtime = createCapabilityRuntime({
271
+ inputs: { "runtime.logger": silentLogger },
272
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
273
+ });
274
+
275
+ await runtime.start();
276
+ const archive = actions.getDefinition("crud.books.archive").input;
277
+ const rename = actions.getDefinition("crud.books.rename").input;
278
+ assert.equal(archive.mode, "create");
279
+ assert.deepEqual(Object.keys(archive.schema.getFieldDefinitions()), ["workspaceSlug", "recordId"]);
280
+ assert.equal(rename.mode, "patch");
281
+ await runtime.shutdown();
282
+ });
283
+
284
+ test("a CRUD custom action that declares idempotency stops the feature from starting", async () => {
285
+ const feature = defineCrudJsonApiFeature({
286
+ resource: createBookResource(),
287
+ surface: "app",
288
+ actions: {
289
+ archive: {
290
+ input: schemaDefinition({ recordId: { type: "string", required: true } }),
291
+ idempotency: "optional",
292
+ execute: ({ input }) => input
293
+ }
294
+ }
295
+ });
296
+ const runtime = createCapabilityRuntime({
297
+ inputs: { "runtime.logger": silentLogger },
298
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies([]), feature]
299
+ });
300
+
301
+ await assert.rejects(
302
+ runtime.start(),
303
+ { message: "CRUD custom action \"archive\" declares idempotency. Action definitions no longer declare idempotency." }
304
+ );
305
+ });
306
+
232
307
  test("generated CRUD actions expose truthful assistant contracts without changing native results", async () => {
233
308
  const resource = createBookResource();
234
309
  const document = (id, title) => ({
@@ -238,14 +313,14 @@ test("generated CRUD actions expose truthful assistant contracts without changin
238
313
  attributes: { title }
239
314
  }
240
315
  });
241
- const actions = createCrudJsonApiActions({
316
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
242
317
  namespace: "books",
243
318
  resource,
244
319
  service: {
245
320
  async queryDocuments() {
246
321
  return returnJsonApiDocument({
247
322
  data: [document("1", "Kindred").data],
248
- meta: { page: { nextCursor: "cursor-2" } }
323
+ meta: { pagination: { cursor: { next: "cursor-2" } } }
249
324
  });
250
325
  },
251
326
  async getDocumentById() {
@@ -263,7 +338,7 @@ test("generated CRUD actions expose truthful assistant contracts without changin
263
338
  },
264
339
  surface: "admin",
265
340
  permissionForOperation: () => ({ require: "authenticated" })
266
- });
341
+ }));
267
342
  const byOperation = new Map(actions.map((entry) => [entry.id.split(".").at(-1), entry]));
268
343
 
269
344
  assert.ok(actions.every((entry) => entry.output === null));
@@ -348,8 +423,9 @@ test("defineCrudJsonApiFeature lets product services name exact capability depen
348
423
  }
349
424
  });
350
425
  const runtime = createCapabilityRuntime({
426
+ inputs: { "runtime.logger": silentLogger },
351
427
  providers: [
352
- createActionProvider(),
428
+ EventProvider, ActionProvider,
353
429
  ...createFeatureDependencies(routes),
354
430
  valueProvider("test.console-access", "console.access", access),
355
431
  feature,
@@ -393,7 +469,8 @@ test("defineCrudJsonApiFeature lets product repositories add only unique persist
393
469
  }
394
470
  });
395
471
  const runtime = createCapabilityRuntime({
396
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature, observer]
472
+ inputs: { "runtime.logger": silentLogger },
473
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
397
474
  });
398
475
 
399
476
  await runtime.start();
@@ -457,7 +534,8 @@ test("defineCrudJsonApiFeature exposes only deliberately selected operations", a
457
534
  }
458
535
  });
459
536
  const runtime = createCapabilityRuntime({
460
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature, observer]
537
+ inputs: { "runtime.logger": silentLogger },
538
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
461
539
  });
462
540
 
463
541
  await runtime.start();
@@ -484,7 +562,8 @@ test("defineCrudJsonApiFeature supports resources that define only selected oper
484
562
  surface: "app"
485
563
  });
486
564
  const runtime = createCapabilityRuntime({
487
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature]
565
+ inputs: { "runtime.logger": silentLogger },
566
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature]
488
567
  });
489
568
 
490
569
  await runtime.start();
@@ -513,7 +592,8 @@ test("defineCrudJsonApiFeature can expose actions and capability without HTTP ro
513
592
  }
514
593
  });
515
594
  const runtime = createCapabilityRuntime({
516
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature, observer]
595
+ inputs: { "runtime.logger": silentLogger },
596
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
517
597
  });
518
598
 
519
599
  await runtime.start();
@@ -543,7 +623,7 @@ test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit
543
623
  }
544
624
  };
545
625
  const resource = createBookResource();
546
- const actions = createCrudJsonApiActions({
626
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
547
627
  namespace: "books",
548
628
  resource,
549
629
  repository,
@@ -568,7 +648,7 @@ test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit
568
648
  }
569
649
  }
570
650
  }
571
- });
651
+ }));
572
652
  const context = { actor: "tester" };
573
653
  const input = { recordId: "42", title: " Kindred " };
574
654
 
@@ -588,7 +668,7 @@ test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit
588
668
  test("CRUD operation lifecycle does not run after or afterCommit when the transaction fails", async () => {
589
669
  const calls = [];
590
670
  const error = new Error("write failed");
591
- const actions = createCrudJsonApiActions({
671
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
592
672
  namespace: "books",
593
673
  resource: createBookResource(),
594
674
  repository: {
@@ -613,7 +693,7 @@ test("CRUD operation lifecycle does not run after or afterCommit when the transa
613
693
  afterCommit() { calls.push("afterCommit"); }
614
694
  }
615
695
  }
616
- });
696
+ }));
617
697
 
618
698
  await assert.rejects(
619
699
  actions[0].execute({ recordId: "42", title: "Kindred" }, {}),
@@ -622,10 +702,94 @@ test("CRUD operation lifecycle does not run after or afterCommit when the transa
622
702
  assert.deepEqual(calls, ["transaction:begin", "before", "service"]);
623
703
  });
624
704
 
705
+ test("a CRUD create that returns no tagged JSON:API result with the record id fails before its after hooks, in every channel", async () => {
706
+ const createdDocument = { data: { type: "books", id: "7", attributes: { title: "Kindred" } } };
707
+ const results = [
708
+ createdDocument,
709
+ { id: "7", title: "Kindred" },
710
+ { kind: "document", value: createdDocument },
711
+ returnJsonApiDocument({ data: null }),
712
+ returnJsonApiData({ title: "Kindred" })
713
+ ];
714
+ for (const returned of results) {
715
+ const calls = [];
716
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
717
+ namespace: "books",
718
+ resource: createBookResource(),
719
+ repository: {
720
+ async withTransaction(work) {
721
+ calls.push("transaction:begin");
722
+ const result = await work({ id: "transaction" });
723
+ calls.push("transaction:commit");
724
+ return result;
725
+ }
726
+ },
727
+ service: {
728
+ async createDocument() {
729
+ return returnJsonApiDocument(createdDocument);
730
+ }
731
+ },
732
+ surface: "app",
733
+ operations: ["create"],
734
+ permissionForOperation: () => ({ require: "authenticated" }),
735
+ operationLifecycle: {
736
+ create: {
737
+ execute() { return returned; },
738
+ after() { calls.push("after"); },
739
+ afterCommit() { calls.push("afterCommit"); }
740
+ }
741
+ }
742
+ }));
743
+
744
+ await assert.rejects(
745
+ actions[0].execute({ title: "Kindred" }, {}),
746
+ /CRUD books create must return the created record, with its id, as a tagged JSON:API result/
747
+ );
748
+ assert.deepEqual(calls, ["transaction:begin"]);
749
+ }
750
+
751
+ const decoratedActions = createCrudJsonApiActions(crudJsonApiActionOptions({
752
+ namespace: "books",
753
+ resource: createBookResource(),
754
+ repository: {},
755
+ service: {
756
+ async createDocument() {
757
+ return createdDocument;
758
+ }
759
+ },
760
+ surface: "app",
761
+ operations: ["create"],
762
+ permissionForOperation: () => ({ require: "authenticated" })
763
+ }));
764
+ await assert.rejects(
765
+ decoratedActions[0].execute({ title: "Kindred" }, {}),
766
+ /CRUD books create must return the created record, with its id, as a tagged JSON:API result/
767
+ );
768
+
769
+ for (const returned of [returnJsonApiDocument(createdDocument), returnJsonApiData({ id: 7, title: "Kindred" })]) {
770
+ const acceptedActions = createCrudJsonApiActions(crudJsonApiActionOptions({
771
+ namespace: "books",
772
+ resource: createBookResource(),
773
+ repository: {},
774
+ service: {
775
+ async createDocument() {
776
+ return returned;
777
+ }
778
+ },
779
+ surface: "app",
780
+ operations: ["create"],
781
+ permissionForOperation: () => ({ require: "authenticated" })
782
+ }));
783
+ const result = await acceptedActions[0].execute({ title: "Kindred" }, {});
784
+ assert.equal(result, returned);
785
+ assert.equal(acceptedActions[0].events[0]({ input: {}, result, context: {} }).entityId, "7");
786
+ }
787
+ });
788
+
625
789
  test("CRUD afterCommit failures preserve the original cause and acknowledged commit", async () => {
626
790
  for (const failure of [new Error("notification failed"), Object.freeze(new Error("frozen failure")), null, undefined]) {
627
791
  let committed = false;
628
- const actions = createCrudJsonApiActions({
792
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
629
793
  namespace: "books",
630
794
  resource: createBookResource(),
631
795
  repository: {
@@ -644,7 +808,7 @@ test("CRUD afterCommit failures preserve the original cause and acknowledged com
644
808
  operationLifecycle: {
645
809
  update: { afterCommit() { assert.equal(committed, true); throw failure; } }
646
810
  }
647
- });
811
+ }));
648
812
  await assert.rejects(
649
813
  () => actions[0].execute({ recordId: "42", title: "Kindred" }, {}),
650
814
  (error) => {
@@ -662,7 +826,7 @@ test("CRUD failures before acknowledged commit are not marked committed", async
662
826
  const failure = Object.freeze(new Error(`${phase} failed`));
663
827
  let committed = false;
664
828
  let afterCommitCalled = false;
665
- const actions = createCrudJsonApiActions({
829
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
666
830
  namespace: "books",
667
831
  resource: createBookResource(),
668
832
  repository: {
@@ -686,7 +850,7 @@ test("CRUD failures before acknowledged commit are not marked committed", async
686
850
  afterCommit() { afterCommitCalled = true; }
687
851
  }
688
852
  }
689
- });
853
+ }));
690
854
  await assert.rejects(
691
855
  () => actions[0].execute({ recordId: "42", title: "Kindred" }, {}),
692
856
  (error) => error === failure && error.transactionOutcome === undefined
@@ -748,12 +912,13 @@ test("defineCrudJsonApiFeature exposes custom service methods as actions and opt
748
912
  }
749
913
  });
750
914
  const runtime = createCapabilityRuntime({
751
- providers: [createActionProvider(), ...createFeatureDependencies(routes), feature, observer]
915
+ inputs: { "runtime.logger": silentLogger },
916
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies(routes), feature, observer]
752
917
  });
753
918
 
754
919
  await runtime.start();
755
920
  assert.equal(typeof books.service.confirmBook, "function");
756
- const definition = actions.getDefinition("books.confirm");
921
+ const definition = actions.getDefinition("crud.books.confirm");
757
922
  assert.deepEqual(definition.permission.permissions, ["books.confirm"]);
758
923
  assert.equal(routes.at(-1).method, "POST");
759
924
  assert.equal(routes.at(-1).path, "/api/books/:recordId/confirm");
@@ -772,7 +937,7 @@ test("defineCrudJsonApiFeature exposes custom service methods as actions and opt
772
937
  }
773
938
  }, reply);
774
939
  assert.deepEqual(routeCalls, [{
775
- actionId: "books.confirm",
940
+ actionId: "crud.books.confirm",
776
941
  input: { recordId: "42", note: "Ready" }
777
942
  }]);
778
943
  assert.equal(reply.statusCode, 202);
@@ -786,7 +951,7 @@ test("defineCrudJsonApiFeature exposes custom service methods as actions and opt
786
951
  };
787
952
  assert.deepEqual(
788
953
  await actions.execute({
789
- actionId: "books.confirm",
954
+ actionId: "crud.books.confirm",
790
955
  input: { recordId: "42", note: "Ready" },
791
956
  context
792
957
  }),
@@ -849,7 +1014,7 @@ test("registerCrudJsonApiRoutes forwards scope, record, query, and body values t
849
1014
  routes.push({ method, path, contract, handler });
850
1015
  }
851
1016
  },
852
- {
1017
+ crudJsonApiRouteOptions({
853
1018
  namespace: "books",
854
1019
  resource: createBookResource({ autofilter: "workspace" }),
855
1020
  routeBase: "/w/:workspaceSlug",
@@ -858,7 +1023,7 @@ test("registerCrudJsonApiRoutes forwards scope, record, query, and body values t
858
1023
  ownershipFilter: "workspace",
859
1024
  access: "authenticated",
860
1025
  scopeInput: (request) => ({ workspaceSlug: request.input.params.workspaceSlug })
861
- }
1026
+ })
862
1027
  );
863
1028
 
864
1029
  const actionCalls = [];
@@ -11,6 +11,7 @@ import {
11
11
  jsonApiFieldsetsQueryValidator,
12
12
  lookupIncludeQueryValidator
13
13
  } from "../src/server/listQueryValidators.js";
14
+ import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
14
15
  import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
15
16
  import {
16
17
  createCrudServiceRuntime,
@@ -56,6 +57,21 @@ test("crud-core errors carry codes and params rendering their English", async ()
56
57
  }
57
58
  };
58
59
 
60
+ // A record whose lock version has moved on: the guarded update claims no row.
61
+ const movedOnRepository = createCrudJsonApiRepository({
62
+ api: {
63
+ resources: { notes: { async get() { return { data: { type: "notes", id: "7" } }; } } },
64
+ knex: { helpers: { getStorageAdapter: () => ({
65
+ getIdColumn: () => "id",
66
+ translateColumn: (field) => field,
67
+ translateFilterValue: (_field, value) => value,
68
+ buildBaseQuery: () => ({ where() { return this; }, async update() { return 0; } })
69
+ }) } },
70
+ transaction: (work) => work("managed")
71
+ },
72
+ resource: { lockVersionField: "lockVersion", schema: {} },
73
+ resourceScopeName: "notes"
74
+ });
59
75
  const errors = [
60
76
  await rejection(() => crudServiceGetRecord(runtime, missingRepository, {}, 7, {})),
61
77
  await rejection(() => crudServiceUpdateRecord(runtime, missingRepository, {}, 7, {}, {})),
@@ -65,6 +81,7 @@ test("crud-core errors carry codes and params rendering their English", async ()
65
81
  writeMode: "throw"
66
82
  }, { name: "Ada", role: "owner", secret: "x" }, {})),
67
83
  await rejection(() => createCrudJsonApiService({ repository: missingRepository }).getDocumentById(7)),
84
+ await rejection(() => movedOnRepository.patchDocumentIfLockVersion("7", 0, {})),
68
85
  await rejection(() => normalizeCrudListCursor("abc"))
69
86
  ];
70
87
 
@@ -74,6 +91,7 @@ test("crud-core errors carry codes and params rendering their English", async ()
74
91
  [404, "crud.record.notFound"],
75
92
  [403, "crud.fieldAccess.writeDenied"],
76
93
  [404, "crud.document.notFound"],
94
+ [409, "crud.document.lockVersionConflict"],
77
95
  [400, "INVALID_CURSOR"]
78
96
  ]);
79
97
  assert.deepEqual(errors[3].params, { fields: "role, secret" });
@@ -1,12 +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";
4
5
  import {
5
6
  createJsonRestApiHost,
6
7
  createJsonRestResourceScopeOptions
7
8
  } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
8
9
  import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
9
10
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
11
+ import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
10
12
  import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
11
13
  import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
12
14
 
@@ -97,7 +99,7 @@ async function createDatabaseRepository(t) {
97
99
  table.increments("id");
98
100
  table.string("message").notNullable();
99
101
  });
100
- const api = await createJsonRestApiHost({ knex });
102
+ const api = await createJsonRestApiHost({ knex, logger: silentLogger });
101
103
  const resource = { tableName: "books", schema: { title: { type: "string", required: true } } };
102
104
  await api.addResource("books", createJsonRestResourceScopeOptions(resource));
103
105
  const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "books" });
@@ -204,7 +206,7 @@ test("a failing CRUD afterCommit hook reports committed and leaves the actual wr
204
206
  const { knex, repository } = await createDatabaseRepository(t);
205
207
  const book = await repository.createDocument({ title: "Dune" });
206
208
  const failure = Object.freeze(new Error("Notification failed"));
207
- const actions = createCrudJsonApiActions({
209
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
208
210
  namespace: "books",
209
211
  resource: defineCrudResource({
210
212
  namespace: "books",
@@ -224,10 +226,108 @@ test("a failing CRUD afterCommit hook reports committed and leaves the actual wr
224
226
  operations: ["update"],
225
227
  permissionForOperation: () => ({ require: "authenticated" }),
226
228
  operationLifecycle: { update: { afterCommit() { throw failure; } } }
227
- });
229
+ }));
228
230
  await assert.rejects(
229
231
  () => actions[0].execute({ recordId: book.data.id, title: "Kindred" }, {}),
230
232
  (error) => error.transactionOutcome === "committed" && error.cause === failure
231
233
  );
232
234
  assert.equal((await knex("books").where({ id: book.data.id }).first()).title, "Kindred");
233
235
  });
236
+
237
+ async function createLockedNotesRepository(t, { lockVersionField = "lockVersion" } = {}) {
238
+ const knex = knexLib({
239
+ client: "better-sqlite3",
240
+ connection: { filename: ":memory:" },
241
+ useNullAsDefault: true
242
+ });
243
+ t.after(() => knex.destroy());
244
+ await knex.schema.createTable("notes", (table) => {
245
+ table.increments("id");
246
+ table.integer("workspace_id").notNullable();
247
+ table.string("title").notNullable();
248
+ table.integer("lock_version").notNullable().defaultTo(0);
249
+ });
250
+ await knex.schema.createTable("audit_entries", (table) => {
251
+ table.increments("id");
252
+ table.string("message").notNullable();
253
+ });
254
+ await knex("notes").insert([
255
+ { workspace_id: 1, title: "Dune", lock_version: 3 },
256
+ { workspace_id: 2, title: "Kindred", lock_version: 0 }
257
+ ]);
258
+ const resource = defineCrudResource({
259
+ namespace: "notes",
260
+ tableName: "notes",
261
+ autofilter: "workspace",
262
+ lockVersionField,
263
+ schema: {
264
+ workspaceId: { type: "id", required: true, hidden: true, column: "workspace_id" },
265
+ title: { type: "string", required: true },
266
+ lockVersion: { type: "integer", min: 0, readOnly: true, column: "lock_version" }
267
+ }
268
+ });
269
+ const api = await createJsonRestApiHost({ knex, logger: silentLogger });
270
+ await api.addResource("notes", createJsonRestResourceScopeOptions(resource));
271
+ const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "notes" });
272
+ const stored = (id) => knex("notes").where({ id }).first("title", "lock_version");
273
+ return { knex, repository, stored };
274
+ }
275
+
276
+ const WORKSPACE_ONE = Object.freeze({ context: Object.freeze({ scopeValues: Object.freeze({ workspaceId: "1" }) }) });
277
+
278
+ test("a patch at the record's lock version applies and moves the lock version on by one", async (t) => {
279
+ const { repository, stored } = await createLockedNotesRepository(t);
280
+ const document = await repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, WORKSPACE_ONE);
281
+ assert.equal(document.data.attributes.title, "Dune Messiah");
282
+ assert.equal(document.data.attributes.lockVersion, 4);
283
+ assert.deepEqual(await stored(1), { title: "Dune Messiah", lock_version: 4 });
284
+ assert.equal((await repository.patchDocumentIfLockVersion("1", 4, {}, WORKSPACE_ONE)).data.attributes.lockVersion, 5);
285
+ });
286
+
287
+ test("a patch at a stale lock version rejects with a lock version conflict and changes nothing", async (t) => {
288
+ const { repository, stored } = await createLockedNotesRepository(t);
289
+ await assert.rejects(
290
+ () => repository.patchDocumentIfLockVersion("1", 2, { title: "Dune Messiah" }, WORKSPACE_ONE),
291
+ (error) => error.status === 409 && error.code === "crud.document.lockVersionConflict" &&
292
+ error.message === "This record changed. Reload and try again."
293
+ );
294
+ assert.deepEqual(await stored(1), { title: "Dune", lock_version: 3 });
295
+ });
296
+
297
+ test("a record that is missing or out of scope patches to null and keeps its lock version", async (t) => {
298
+ const { repository, stored } = await createLockedNotesRepository(t);
299
+ assert.equal(await repository.patchDocumentIfLockVersion("2", 0, { title: "Fledgling" }, WORKSPACE_ONE), null);
300
+ assert.equal(await repository.patchDocumentIfLockVersion("9", 0, { title: "Fledgling" }, WORKSPACE_ONE), null);
301
+ assert.deepEqual(await stored(2), { title: "Kindred", lock_version: 0 });
302
+ });
303
+
304
+ test("a lock-version patch joins the caller's transaction and rolls back with it", async (t) => {
305
+ const { knex, repository, stored } = await createLockedNotesRepository(t);
306
+ await assert.rejects(() => repository.withTransaction(async (trx) => {
307
+ await repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, { ...WORKSPACE_ONE, trx });
308
+ await trx("audit_entries").insert({ message: "Renamed" });
309
+ assert.deepEqual(await trx("notes").where({ id: 1 }).first("title", "lock_version"), { title: "Dune Messiah", lock_version: 4 });
310
+ throw new Error("Abandon the rename");
311
+ }), /Abandon the rename/);
312
+ assert.deepEqual(await stored(1), { title: "Dune", lock_version: 3 });
313
+ assert.deepEqual(await knex("audit_entries"), []);
314
+ await repository.withTransaction((trx) => repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, { ...WORKSPACE_ONE, trx }));
315
+ assert.deepEqual(await stored(1), { title: "Dune Messiah", lock_version: 4 });
316
+ });
317
+
318
+ test("patchDocumentIfLockVersion needs a lockVersionField, a whole expected version and a patch without the lock", async (t) => {
319
+ const { repository } = await createLockedNotesRepository(t);
320
+ const unlocked = createCrudJsonApiRepository({
321
+ api: { resources: {} },
322
+ resource: { schema: {} },
323
+ resourceScopeName: "notes"
324
+ });
325
+ await assert.rejects(() => unlocked.patchDocumentIfLockVersion("1", 0, {}), /needs resource "notes" to name its lockVersionField/);
326
+ for (const expected of [-1, 1.5, "3", null]) {
327
+ await assert.rejects(() => repository.patchDocumentIfLockVersion("1", expected, {}, WORKSPACE_ONE), /must be a non-negative integer/);
328
+ }
329
+ await assert.rejects(
330
+ () => repository.patchDocumentIfLockVersion("1", 3, { lockVersion: 9 }, WORKSPACE_ONE),
331
+ /advances lockVersion itself, so the patch must leave it out/
332
+ );
333
+ });
@@ -11,7 +11,7 @@ import { listSearchQueryValidator } from "../src/server/listQueryValidators.js";
11
11
  import {
12
12
  CRUD_LIST_FILTER_INVALID_VALUES_REJECT,
13
13
  CRUD_LIST_FILTER_INVALID_VALUES_DISCARD,
14
- createCrudListFilterQueryField,
14
+ buildCrudListFilterQueryField,
15
15
  createCrudListFilterQuerySchema,
16
16
  createCrudListFilterJsonRestSearchSchema,
17
17
  createCrudListFilters,
@@ -28,7 +28,7 @@ function composeSchemaDefinition(...definitions) {
28
28
  test("crud-core exposes createCrudListFilters through the public package export", async () => {
29
29
  const module = await import("@jskit-ai/crud-core/server/listFilters");
30
30
  assert.equal(typeof module.createCrudListFilters, "function");
31
- assert.equal(typeof module.createCrudListFilterQueryField, "function");
31
+ assert.equal(typeof module.buildCrudListFilterQueryField, "function");
32
32
  assert.equal(typeof module.createCrudListFilterQuerySchema, "function");
33
33
  assert.equal(typeof module.createCrudListFilterJsonRestSearchSchema, "function");
34
34
  assert.equal(typeof module.createCrudListFilterContract, "function");
@@ -296,7 +296,7 @@ test("createCrudListFilters query validator stays mergeable with search and curs
296
296
  assert.deepEqual(compiled.schema.querystring.required || [], []);
297
297
  });
298
298
 
299
- test("createCrudListFilterQueryField keeps route query params explicit while reusing filter semantics", () => {
299
+ test("buildCrudListFilterQueryField keeps route query params explicit while reusing filter semantics", () => {
300
300
  const filters = defineCrudListFilters({
301
301
  status: {
302
302
  type: "enum",
@@ -314,10 +314,10 @@ test("createCrudListFilterQueryField keeps route query params explicit while reu
314
314
 
315
315
  const explicitFilterQueryValidator = Object.freeze({
316
316
  schema: createCrudListFilterQuerySchema({
317
- status: createCrudListFilterQueryField(filters.status, {
317
+ status: buildCrudListFilterQueryField(filters.status, {
318
318
  invalidValues: CRUD_LIST_FILTER_INVALID_VALUES_REJECT
319
319
  }),
320
- arrivalDate: createCrudListFilterQueryField(filters.arrivalDate, {
320
+ arrivalDate: buildCrudListFilterQueryField(filters.arrivalDate, {
321
321
  invalidValues: CRUD_LIST_FILTER_INVALID_VALUES_REJECT
322
322
  })
323
323
  }),
@@ -357,9 +357,9 @@ test("createCrudListFilterQueryField keeps route query params explicit while reu
357
357
  });
358
358
  });
359
359
 
360
- test("createCrudListFilterQueryField requires normalized filter definitions", () => {
360
+ test("buildCrudListFilterQueryField requires normalized filter definitions", () => {
361
361
  assert.throws(
362
- () => createCrudListFilterQueryField({
362
+ () => buildCrudListFilterQueryField({
363
363
  type: "enum",
364
364
  label: "Status"
365
365
  }),