@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
@@ -9,44 +9,38 @@ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
9
9
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
10
10
  import { validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
11
11
  import { returnJsonApiData, returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
12
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
13
- import { defineCrudJsonApiFeature } from "../src/server/defineCrudJsonApiFeature.js";
12
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
13
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
14
+ import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
15
+ import { CrudContractsProvider } from "../src/server/crudContracts.js";
14
16
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
15
17
  import { crudJsonApiActionOptions, crudJsonApiRouteOptions } from "./support/crudJsonApiActionOptions.js";
16
18
  import { registerCrudJsonApiRoutes } from "../src/server/jsonApiModule/routes.js";
17
19
 
18
- function createBookResource({ apiAccess = "authenticated", autofilter = "user" } = {}) {
19
- return defineCrudResource({
20
- namespace: "books",
20
+ function bookTable(ownership) {
21
+ return defineTableResource({
22
+ name: "books",
21
23
  tableName: "books",
22
- apiAccess,
23
- autofilter,
24
+ ownership,
24
25
  schema: {
25
- title: {
26
- type: "string",
27
- required: true,
28
- operations: {
29
- output: { required: true },
30
- create: { required: true },
31
- patch: { required: false }
32
- }
33
- }
26
+ title: { type: "string", required: true }
34
27
  }
35
28
  });
36
29
  }
37
30
 
31
+ function createBookResource({ apiAccess = "authenticated", ownership = "user" } = {}) {
32
+ return defineCrudContract(bookTable(ownership), {
33
+ namespace: "books",
34
+ apiAccess,
35
+ fields: { title: { output: "required", create: "required", patch: "optional" } }
36
+ });
37
+ }
38
+
38
39
  function createReadOnlyBookResource() {
39
- return defineCrudResource({
40
+ return defineCrudContract(bookTable("public"), {
40
41
  namespace: "books",
41
- tableName: "books",
42
- crudOperations: ["list", "view"],
43
- schema: {
44
- title: {
45
- type: "string",
46
- required: true,
47
- operations: { output: { required: true } }
48
- }
49
- }
42
+ operations: ["list", "view"],
43
+ fields: { title: { output: "required" } }
50
44
  });
51
45
  }
52
46
 
@@ -64,16 +58,43 @@ function valueProvider(id, capability, value) {
64
58
  });
65
59
  }
66
60
 
67
- function createFeatureDependencies(routes) {
68
- const knex = Object.assign(() => {}, {
69
- async transaction(callback) {
70
- return callback({});
61
+ // A stand-in for one owned table's handle: the CRUD service's calls, answered as a JSON:API document.
62
+ function fakeHandle(resource) {
63
+ return Object.freeze({
64
+ name: resource.name,
65
+ pageLimits: () => Object.freeze({ request: 100, server: 1000 }),
66
+ async withTransaction(options, work) {
67
+ return work(Object.freeze({ ...options, trx: "managed" }));
68
+ },
69
+ async query() {
70
+ return { data: [] };
71
+ },
72
+ async get() {
73
+ return null;
74
+ },
75
+ async create(attributes) {
76
+ return { data: { type: resource.name, id: "1", attributes } };
77
+ },
78
+ async patch() {
79
+ return null;
80
+ },
81
+ async delete() {
82
+ return null;
71
83
  }
72
84
  });
73
- const jsonRestApi = {
74
- resources: {},
75
- async addResource(name, config) {
76
- this.resources[name] = { config };
85
+ }
86
+
87
+ function createFeatureDependencies(routes, owned = []) {
88
+ const resources = {
89
+ own(featureId, owns) {
90
+ owned.push({ featureId, owns });
91
+ return Object.freeze(Object.fromEntries(owns.map((entry) => {
92
+ const resource = entry.resource || entry;
93
+ return [resource.name, fakeHandle(resource)];
94
+ })));
95
+ },
96
+ declareSystemScope(feature, systemScope) {
97
+ return (reason) => Object.freeze({ system: true, feature, systemScope, reason });
77
98
  }
78
99
  };
79
100
  const http = {
@@ -84,16 +105,16 @@ function createFeatureDependencies(routes) {
84
105
  }
85
106
  };
86
107
  return [
87
- valueProvider("test.database", "runtime.database", { knex }),
108
+ valueProvider("test.resources", "runtime.resources", resources),
88
109
  valueProvider("test.http", "runtime.http", http),
89
- valueProvider("test.json-rest-api", "runtime.json-rest-api", jsonRestApi)
110
+ CrudContractsProvider
90
111
  ];
91
112
  }
92
113
 
93
- test("defineCrudJsonApiFeature composes one resource without ceremonial token layers", async () => {
114
+ test("defineCrudFeature composes one resource without ceremonial token layers", async () => {
94
115
  const routes = [];
95
- const feature = defineCrudJsonApiFeature({
96
- resource: createBookResource(),
116
+ const feature = defineCrudFeature({
117
+ crud: createBookResource(),
97
118
  surface: "app",
98
119
  relativePath: "/books"
99
120
  });
@@ -125,8 +146,8 @@ test("defineCrudJsonApiFeature composes one resource without ceremonial token la
125
146
 
126
147
  assert.equal(feature.id, "crud.books");
127
148
  assert.deepEqual(feature.provides, { resourceApi: "crud.books" });
128
- assert.equal(resourceApi.resource.namespace, "books");
129
- assert.equal(typeof resourceApi.service.queryDocuments, "function");
149
+ assert.equal(resourceApi.crud.namespace, "books");
150
+ assert.equal(typeof resourceApi.service.list, "function");
130
151
  assert.equal(typeof resourceApi.repository.withTransaction, "function");
131
152
  assert.deepEqual(
132
153
  actions.listDefinitions().map((entry) => entry.id),
@@ -154,7 +175,7 @@ test("defineCrudJsonApiFeature composes one resource without ceremonial token la
154
175
  await runtime.shutdown();
155
176
  });
156
177
 
157
- test("defineCrudJsonApiFeature sends record.changed to its realtime audience", async () => {
178
+ test("defineCrudFeature sends record.changed to its realtime audience", async () => {
158
179
  const execution = { input: { recordId: "5" }, result: returnJsonApiDocument({ data: { id: "5" } }), context: {} };
159
180
  for (const [options, audience] of [[{}, "event_scope"], [{ realtimeAudience: "all_users" }, "all_users"]]) {
160
181
  let actions;
@@ -171,8 +192,8 @@ test("defineCrudJsonApiFeature sends record.changed to its realtime audience", a
171
192
  providers: [
172
193
  EventProvider, ActionProvider,
173
194
  ...createFeatureDependencies([]),
174
- defineCrudJsonApiFeature({
175
- resource: createBookResource({ apiAccess: "public", autofilter: "public" }),
195
+ defineCrudFeature({
196
+ crud: createBookResource({ apiAccess: "public", ownership: "public" }),
176
197
  surface: "home",
177
198
  ...options
178
199
  }),
@@ -194,10 +215,10 @@ test("defineCrudJsonApiFeature sends record.changed to its realtime audience", a
194
215
  }
195
216
  });
196
217
 
197
- test("defineCrudJsonApiFeature makes workspace scope and permissions explicit", async () => {
218
+ test("defineCrudFeature makes workspace scope and permissions explicit", async () => {
198
219
  const routes = [];
199
- const feature = defineCrudJsonApiFeature({
200
- resource: createBookResource({ autofilter: "workspace" }),
220
+ const feature = defineCrudFeature({
221
+ crud: createBookResource({ ownership: "workspace" }),
201
222
  surface: "app",
202
223
  scope: {
203
224
  routeBase: "/w/:workspaceSlug",
@@ -237,8 +258,8 @@ test("defineCrudJsonApiFeature makes workspace scope and permissions explicit",
237
258
 
238
259
  test("a scoped CRUD custom action's input keeps its own mode, and one without a mode is create", async () => {
239
260
  const routes = [];
240
- const feature = defineCrudJsonApiFeature({
241
- resource: createBookResource({ autofilter: "workspace" }),
261
+ const feature = defineCrudFeature({
262
+ crud: createBookResource({ ownership: "workspace" }),
242
263
  surface: "app",
243
264
  scope: {
244
265
  routeBase: "/w/:workspaceSlug",
@@ -282,8 +303,8 @@ test("a scoped CRUD custom action's input keeps its own mode, and one without a
282
303
  });
283
304
 
284
305
  test("a CRUD custom action that declares idempotency stops the feature from starting", async () => {
285
- const feature = defineCrudJsonApiFeature({
286
- resource: createBookResource(),
306
+ const feature = defineCrudFeature({
307
+ crud: createBookResource(),
287
308
  surface: "app",
288
309
  actions: {
289
310
  archive: {
@@ -317,22 +338,22 @@ test("generated CRUD actions expose truthful assistant contracts without changin
317
338
  namespace: "books",
318
339
  resource,
319
340
  service: {
320
- async queryDocuments() {
341
+ async list() {
321
342
  return returnJsonApiDocument({
322
343
  data: [document("1", "Kindred").data],
323
344
  meta: { pagination: { cursor: { next: "cursor-2" } } }
324
345
  });
325
346
  },
326
- async getDocumentById() {
347
+ async view() {
327
348
  return returnJsonApiDocument(document("1", "Kindred"));
328
349
  },
329
- async createDocument() {
350
+ async create() {
330
351
  return returnJsonApiDocument(document("2", "Parable of the Sower"));
331
352
  },
332
- async patchDocumentById() {
353
+ async patch() {
333
354
  return returnJsonApiDocument(document("1", "Kindred (updated)"));
334
355
  },
335
- async deleteDocumentById() {
356
+ async delete() {
336
357
  return null;
337
358
  }
338
359
  },
@@ -389,7 +410,7 @@ test("generated CRUD actions expose truthful assistant contracts without changin
389
410
  returnJsonApiDocument(document("1", "Kindred")));
390
411
  });
391
412
 
392
- test("defineCrudJsonApiFeature lets product services name exact capability dependencies", async () => {
413
+ test("defineCrudFeature lets product services name exact capability dependencies", async () => {
393
414
  const routes = [];
394
415
  const access = {
395
416
  calls: [],
@@ -397,16 +418,16 @@ test("defineCrudJsonApiFeature lets product services name exact capability depen
397
418
  this.calls.push(context);
398
419
  }
399
420
  };
400
- const feature = defineCrudJsonApiFeature({
401
- resource: createBookResource(),
421
+ const feature = defineCrudFeature({
422
+ crud: createBookResource(),
402
423
  surface: "console",
403
424
  requires: { access: "console.access" },
404
- decorateService({ service, repository, resource, access: consoleAccess }) {
405
- assert.equal(resource.namespace, "books");
406
- assert.equal(typeof repository.createDocument, "function");
425
+ decorateService({ service, repository, crud, access: consoleAccess }) {
426
+ assert.equal(crud.namespace, "books");
427
+ assert.equal(typeof repository.create, "function");
407
428
  return {
408
429
  ...service,
409
- async createDocument(payload, options) {
430
+ async create(payload, options) {
410
431
  await consoleAccess.requireOwner(options.context);
411
432
  return { data: { type: "books", attributes: payload } };
412
433
  }
@@ -436,21 +457,21 @@ test("defineCrudJsonApiFeature lets product services name exact capability depen
436
457
  await runtime.start();
437
458
  const context = { auth: { userId: "1" } };
438
459
  assert.deepEqual(
439
- await resourceApi.service.createDocument({ title: "Parable of the Sower" }, { context }),
460
+ await resourceApi.service.create({ title: "Parable of the Sower" }, { context }),
440
461
  { data: { type: "books", attributes: { title: "Parable of the Sower" } } }
441
462
  );
442
463
  assert.deepEqual(access.calls, [context]);
443
464
  await runtime.shutdown();
444
465
  });
445
466
 
446
- test("defineCrudJsonApiFeature lets product repositories add only unique persistence operations", async () => {
467
+ test("defineCrudFeature lets product repositories add only unique persistence operations", async () => {
447
468
  const routes = [];
448
- const feature = defineCrudJsonApiFeature({
449
- resource: createBookResource(),
469
+ const feature = defineCrudFeature({
470
+ crud: createBookResource(),
450
471
  surface: "app",
451
- decorateRepository({ repository, database, resource }) {
452
- assert.equal(resource.namespace, "books");
453
- assert.equal(typeof database.knex.transaction, "function");
472
+ decorateRepository({ repository, resources, crud }) {
473
+ assert.equal(crud.namespace, "books");
474
+ assert.equal(resources.books, repository);
454
475
  return Object.freeze({
455
476
  ...repository,
456
477
  async countBooks() {
@@ -475,38 +496,143 @@ test("defineCrudJsonApiFeature lets product repositories add only unique persist
475
496
 
476
497
  await runtime.start();
477
498
  assert.equal(await resourceApi.repository.countBooks(), 12);
478
- assert.equal(typeof resourceApi.repository.queryDocuments, "function");
499
+ assert.equal(typeof resourceApi.repository.query, "function");
500
+ await runtime.shutdown();
501
+ });
502
+
503
+ test("defineCrudFeature owns its CRUD table, takes its extras from owns, and hands a system context to decorateRepository", async () => {
504
+ const crud = createBookResource({ ownership: "public" });
505
+ const notes = defineTableResource({ name: "bookNotes", tableName: "book_notes", ownership: "public", schema: { body: { type: "string" } } });
506
+ const archived = defineCrudContract(defineTableResource({
507
+ name: "archivedBooks",
508
+ tableName: "archived_books",
509
+ ownership: "public",
510
+ schema: { title: { type: "string", required: true } }
511
+ }), { namespace: "archivedBooks", fields: { title: { output: "required", create: "required", patch: "optional" } } });
512
+ const rowPolicy = () => true;
513
+ const owned = [];
514
+ let received = null;
515
+ const runtime = createCapabilityRuntime({
516
+ inputs: { "runtime.logger": silentLogger },
517
+ providers: [
518
+ EventProvider, ActionProvider,
519
+ ...createFeatureDependencies([], owned),
520
+ defineCrudFeature({ crud, surface: "home", owns: [notes] }),
521
+ defineCrudFeature({
522
+ crud: archived,
523
+ id: "crud.archived-books",
524
+ surface: "home",
525
+ relativePath: "/archived-books",
526
+ owns: [{ resource: archived.resource, rowPolicy }],
527
+ systemScope: "archive old books in every workspace",
528
+ decorateRepository(dependencies) {
529
+ received = dependencies;
530
+ return dependencies.repository;
531
+ }
532
+ })
533
+ ]
534
+ });
535
+
536
+ await runtime.start();
537
+ const ownedBy = Object.fromEntries(owned.map(({ featureId, owns }) => [featureId, owns]));
538
+ assert.deepEqual(Object.fromEntries(Object.entries(ownedBy).map(([featureId, owns]) => [featureId, owns.map((entry) => entry.resource?.name || entry.name)])), {
539
+ "crud.books": ["books", "bookNotes"],
540
+ "crud.archived-books": ["archivedBooks"]
541
+ });
542
+ assert.equal(ownedBy["crud.archived-books"][0].rowPolicy, rowPolicy);
543
+ assert.deepEqual(Object.keys(received.resources), ["archivedBooks"]);
544
+ assert.equal(received.systemContext("move them").reason, "move them");
545
+ assert.equal(Object.keys(received).includes("http"), false);
479
546
  await runtime.shutdown();
480
547
  });
481
548
 
482
- test("defineCrudJsonApiFeature rejects reserved requirements and invalid decorators", () => {
549
+ test("defineCrudFeature serves a table another feature owns through the owner's repository, at the visibility it names", async () => {
550
+ const routes = [];
551
+ const owned = [];
552
+ const usersRepository = Object.freeze({ name: "users", pageLimits: () => Object.freeze({ request: 100, server: 1000 }) });
553
+ const users = defineCrudContract(defineTableResource({
554
+ name: "users",
555
+ tableName: "users",
556
+ ownership: "public",
557
+ schema: { displayName: { type: "string" } }
558
+ }), { namespace: "users", operations: ["list", "view"], fields: { displayName: { output: "optional" } } });
559
+ let actions;
560
+ let resourceApi;
561
+ const runtime = createCapabilityRuntime({
562
+ inputs: { "runtime.logger": silentLogger },
563
+ providers: [
564
+ EventProvider, ActionProvider,
565
+ ...createFeatureDependencies(routes, owned),
566
+ valueProvider("test.users-owner", "users.profiles", usersRepository),
567
+ defineCrudFeature({
568
+ crud: users,
569
+ id: "app.users-workspace",
570
+ surface: "admin",
571
+ ownerRepository: "users.profiles",
572
+ visibility: "workspace",
573
+ scope: {
574
+ routeBase: "/w/:workspaceSlug",
575
+ actionInputValidator: schemaDefinition({ workspaceSlug: { type: "string", required: true } }),
576
+ routeParamsValidator: schemaDefinition({ workspaceSlug: { type: "string", required: true } }),
577
+ inputKeys: ["workspaceSlug"],
578
+ input: (request) => ({ workspaceSlug: request.input.params.workspaceSlug })
579
+ }
580
+ }),
581
+ defineProvider({
582
+ id: "test.users-observer",
583
+ requires: { actions: "runtime.actions", users: "app.users-workspace" },
584
+ setup(dependencies) {
585
+ actions = dependencies.actions;
586
+ resourceApi = dependencies.users;
587
+ return {};
588
+ }
589
+ })
590
+ ]
591
+ });
592
+
593
+ await runtime.start();
594
+ assert.deepEqual(owned, []);
595
+ assert.equal(resourceApi.repository, usersRepository);
596
+ assert.deepEqual(routes.map((entry) => [entry.path, entry.contract.visibility]), [
597
+ ["/api/w/:workspaceSlug/users", "workspace"],
598
+ ["/api/w/:workspaceSlug/users/:recordId", "workspace"]
599
+ ]);
600
+ assert.deepEqual(actions.listDefinitions().map((entry) => entry.permission.permissions), [["crud.users.list"], ["crud.users.view"]]);
601
+ await runtime.shutdown();
483
602
  assert.throws(
484
- () => defineCrudJsonApiFeature({
485
- resource: createBookResource(),
603
+ () => defineCrudFeature({ crud: users, surface: "admin", ownerRepository: "users.profiles", owns: [users.resource] }),
604
+ /serves "users" through users\.profiles, so it cannot own it too/u
605
+ );
606
+ });
607
+
608
+ test("defineCrudFeature rejects reserved requirements and invalid decorators", () => {
609
+ assert.throws(
610
+ () => defineCrudFeature({
611
+ crud: createBookResource(),
486
612
  surface: "app",
487
613
  decorateRepository: {}
488
614
  }),
489
615
  /decorateRepository must be a function/u
490
616
  );
491
617
  assert.throws(
492
- () => defineCrudJsonApiFeature({
493
- resource: createBookResource(),
618
+ () => defineCrudFeature({
619
+ crud: createBookResource(),
494
620
  surface: "app",
495
- requires: { database: "something.else" }
621
+ requires: { repository: "something.else" }
496
622
  }),
497
- /reserves the local name database/u
623
+ /reserves the local name repository/u
498
624
  );
499
625
  assert.throws(
500
- () => defineCrudJsonApiFeature({
501
- resource: createBookResource(),
626
+ () => defineCrudFeature({
627
+ crud: createBookResource(),
502
628
  surface: "app",
503
629
  decorateService: {}
504
630
  }),
505
631
  /decorateService must be a function/u
506
632
  );
507
633
  assert.throws(
508
- () => defineCrudJsonApiFeature({
509
- resource: createBookResource(),
634
+ () => defineCrudFeature({
635
+ crud: createBookResource(),
510
636
  surface: "app",
511
637
  operations: ["publish"]
512
638
  }),
@@ -514,10 +640,138 @@ test("defineCrudJsonApiFeature rejects reserved requirements and invalid decorat
514
640
  );
515
641
  });
516
642
 
517
- test("defineCrudJsonApiFeature exposes only deliberately selected operations", async () => {
643
+ test("defineCrudFeature refuses an option it does not take, naming where an earlier one now goes", () => {
644
+ const base = { crud: createBookResource(), surface: "app" };
645
+ for (const [option, hint] of [
646
+ ["ownershipFilter", /no longer takes ownershipFilter: use visibility/u],
647
+ ["searchSchema", /no longer takes searchSchema: use an owns entry: owns: \[\{ resource, searchSchema \}\]/u],
648
+ ["rowPolicy", /no longer takes rowPolicy: use an owns entry/u],
649
+ ["resource", /no longer takes resource: use crud, the CRUD contract/u],
650
+ ["routePrefix", /does not take routePrefix\. Its options are crud, id, capability, surface/u]
651
+ ]) {
652
+ assert.throws(() => defineCrudFeature({ ...base, [option]: {} }), hint, option);
653
+ }
654
+ });
655
+
656
+ test("defineCrudFeature refuses a permission for an action it does not define", () => {
657
+ const base = { crud: createBookResource(), surface: "app" };
658
+ assert.throws(
659
+ () => defineCrudFeature({ ...base, permissions: { patch: { require: "authenticated" } } }),
660
+ /permissions\.patch names no action of the feature \(a patch is the "update" action\)\. Its actions are list, view, create, update, delete\./u
661
+ );
662
+ assert.throws(
663
+ () => defineCrudFeature({ ...base, permissions: { Update: { require: "authenticated" } } }),
664
+ /reads the permission of action Update as permissions\.update; name it so/u
665
+ );
666
+ defineCrudFeature({ ...base, permissions: { update: { require: "authenticated" } } });
667
+ });
668
+
669
+ /**
670
+ * Starts a CRUD feature on stand-in dependencies, answering how its start ended.
671
+ * @param {object} options defineCrudFeature's options.
672
+ */
673
+ async function startFeature(options) {
674
+ const feature = defineCrudFeature({ crud: createBookResource(), surface: "app", ...options });
675
+ let resourceApi;
676
+ const observer = defineProvider({
677
+ id: "test.removed-api-observer",
678
+ requires: { books: "crud.books" },
679
+ setup({ books }) {
680
+ resourceApi = books;
681
+ return {};
682
+ }
683
+ });
684
+ const runtime = createCapabilityRuntime({
685
+ inputs: { "runtime.logger": silentLogger },
686
+ providers: [EventProvider, ActionProvider, ...createFeatureDependencies([]), feature, observer]
687
+ });
688
+ await runtime.start();
689
+ return { resourceApi, runtime };
690
+ }
691
+
692
+ test("a decorated repository or service still defining a method of the earlier API stops the feature", async () => {
693
+ await assert.rejects(
694
+ () => startFeature({
695
+ decorateRepository: ({ repository }) => ({ ...repository, async queryDocuments() {}, async applyForUpdate() {} })
696
+ }),
697
+ /The repository decorateRepository returned defines queryDocuments\(\), applyForUpdate\(\).*queryDocuments\(\) is now query\(\{ page: \{ size \} \}, options\); applyForUpdate\(\) is now lock\(id, txOptions\) inside withTransaction/su
698
+ );
699
+ await assert.rejects(
700
+ () => startFeature({
701
+ decorateService: ({ service }) => ({ ...service, async updateRecord() {} })
702
+ }),
703
+ /The service decorateService returned defines updateRecord\(\).*updateRecord\(\) is now patch\(recordId, payload, options\)/su
704
+ );
705
+ });
706
+
707
+ test("a decorated service without an enabled operation's method stops the feature", async () => {
708
+ await assert.rejects(
709
+ () => startFeature({
710
+ decorateService: ({ service }) => ({ list: service.list, view: service.view })
711
+ }),
712
+ /decorateService must return a service with its own create\(\), which the create operation calls; spread the service/u
713
+ );
714
+ const { runtime } = await startFeature({
715
+ operations: ["list", "view"],
716
+ decorateService: ({ service }) => ({ list: service.list, view: service.view })
717
+ });
718
+ await runtime.shutdown();
719
+ });
720
+
721
+ test("reading a dependency or capability property the redesign removed throws, naming its replacement", async () => {
722
+ const seen = {};
723
+ const { resourceApi, runtime } = await startFeature({
724
+ decorateRepository(dependencies) {
725
+ for (const name of ["database", "http", "jsonRestApi", "resource"]) {
726
+ seen[name] = captureMessage(() => dependencies[name]);
727
+ }
728
+ // Spreading the dependencies, as a decorator may, skips the removed names.
729
+ assert.deepEqual(Object.keys({ ...dependencies }).sort(), ["crud", "repository", "resources"]);
730
+ return dependencies.repository;
731
+ },
732
+ decorateService(dependencies) {
733
+ seen.serviceResource = captureMessage(() => dependencies.resource);
734
+ return dependencies.service;
735
+ }
736
+ });
737
+ try {
738
+ assert.match(captureMessage(() => resourceApi.resource), /A CRUD feature's capability no longer has resource: it is now crud, the CRUD contract\./u);
739
+ assert.equal(resourceApi.crud.namespace, "books");
740
+ assert.match(seen.database, /decorateRepository's dependencies no longer has database: read and write through repository and resources/u);
741
+ assert.match(seen.http, /no longer has http: defineCrudFeature registers the routes/u);
742
+ assert.match(seen.jsonRestApi, /no longer has jsonRestApi: each owned table's handle is in resources/u);
743
+ assert.match(seen.resource, /no longer has resource: it is now crud, the CRUD contract/u);
744
+ assert.match(seen.serviceResource, /decorateService's dependencies no longer has resource: it is now crud/u);
745
+ } finally {
746
+ await runtime.shutdown();
747
+ }
748
+ });
749
+
750
+ test("the CRUD service's view refuses forUpdate, naming lock()", async () => {
751
+ const { resourceApi, runtime } = await startFeature({});
752
+ try {
753
+ await assert.rejects(
754
+ () => resourceApi.service.view("1", {}, { context: {}, forUpdate: true }),
755
+ /view\(\) no longer takes forUpdate: lock the record with the repository's lock\(recordId, txOptions\) inside repository\.withTransaction/u
756
+ );
757
+ } finally {
758
+ await runtime.shutdown();
759
+ }
760
+ });
761
+
762
+ function captureMessage(read) {
763
+ try {
764
+ read();
765
+ } catch (error) {
766
+ return error.message;
767
+ }
768
+ return assert.fail("expected the read to throw");
769
+ }
770
+
771
+ test("defineCrudFeature exposes only deliberately selected operations", async () => {
518
772
  const routes = [];
519
- const feature = defineCrudJsonApiFeature({
520
- resource: createBookResource(),
773
+ const feature = defineCrudFeature({
774
+ crud: createBookResource(),
521
775
  surface: "app",
522
776
  relativePath: "/books",
523
777
  operations: ["list", "view"]
@@ -547,18 +801,18 @@ test("defineCrudJsonApiFeature exposes only deliberately selected operations", a
547
801
  "GET /api/books",
548
802
  "GET /api/books/:recordId"
549
803
  ]);
550
- assert.equal(typeof resourceApi.service.queryDocuments, "function");
551
- assert.equal(typeof resourceApi.service.getDocumentById, "function");
552
- assert.equal(resourceApi.service.createDocument, undefined);
553
- assert.equal(resourceApi.service.patchDocumentById, undefined);
554
- assert.equal(resourceApi.service.deleteDocumentById, undefined);
804
+ assert.equal(typeof resourceApi.service.list, "function");
805
+ assert.equal(typeof resourceApi.service.view, "function");
806
+ assert.equal(resourceApi.service.create, undefined);
807
+ assert.equal(resourceApi.service.patch, undefined);
808
+ assert.equal(resourceApi.service.delete, undefined);
555
809
  await runtime.shutdown();
556
810
  });
557
811
 
558
- test("defineCrudJsonApiFeature supports resources that define only selected operations", async () => {
812
+ test("defineCrudFeature supports resources that define only selected operations", async () => {
559
813
  const routes = [];
560
- const feature = defineCrudJsonApiFeature({
561
- resource: createReadOnlyBookResource(),
814
+ const feature = defineCrudFeature({
815
+ crud: createReadOnlyBookResource(),
562
816
  surface: "app"
563
817
  });
564
818
  const runtime = createCapabilityRuntime({
@@ -574,10 +828,10 @@ test("defineCrudJsonApiFeature supports resources that define only selected oper
574
828
  await runtime.shutdown();
575
829
  });
576
830
 
577
- test("defineCrudJsonApiFeature can expose actions and capability without HTTP routes", async () => {
831
+ test("defineCrudFeature can expose actions and capability without HTTP routes", async () => {
578
832
  const routes = [];
579
- const feature = defineCrudJsonApiFeature({
580
- resource: createBookResource(),
833
+ const feature = defineCrudFeature({
834
+ crud: createBookResource(),
581
835
  surface: "app",
582
836
  operations: ["list", "view"],
583
837
  routes: false
@@ -607,17 +861,18 @@ test("defineCrudJsonApiFeature can expose actions and capability without HTTP ro
607
861
 
608
862
  test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit last", async () => {
609
863
  const calls = [];
864
+ let txOptions = null;
610
865
  const service = {
611
- patchDocumentById(recordId, patch, options) {
612
- calls.push(["service", recordId, patch, options.trx]);
866
+ patch(recordId, patch, options) {
867
+ calls.push(["service", recordId, patch, options]);
613
868
  return { data: { id: recordId, attributes: patch } };
614
869
  }
615
870
  };
616
- const trx = { id: "transaction" };
617
871
  const repository = {
618
- async withTransaction(work) {
872
+ async withTransaction(options, work) {
619
873
  calls.push("transaction:begin");
620
- const result = await work(trx);
874
+ txOptions = Object.freeze({ ...options, trx: { id: "transaction" } });
875
+ const result = await work(txOptions);
621
876
  calls.push("transaction:commit");
622
877
  return result;
623
878
  }
@@ -633,18 +888,18 @@ test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit
633
888
  permissionForOperation: () => ({ require: "authenticated" }),
634
889
  operationLifecycle: {
635
890
  update: {
636
- before({ operation, input, context, trx: currentTrx }) {
637
- calls.push(["before", operation, input.recordId, context.actor, currentTrx]);
891
+ before({ operation, input, context, options }) {
892
+ calls.push(["before", operation, input.recordId, context.actor, options]);
638
893
  },
639
894
  execute({ input, standard }) {
640
895
  calls.push("execute");
641
896
  return standard({ ...input, title: input.title.trim() });
642
897
  },
643
- after({ result, trx: currentTrx }) {
644
- calls.push(["after", result.data.id, currentTrx]);
898
+ after({ result, options }) {
899
+ calls.push(["after", result.data.id, options]);
645
900
  },
646
- afterCommit({ result, trx: currentTrx }) {
647
- calls.push(["afterCommit", result.data.id, currentTrx]);
901
+ afterCommit({ result, options }) {
902
+ calls.push(["afterCommit", result.data.id, options]);
648
903
  }
649
904
  }
650
905
  }
@@ -654,15 +909,49 @@ test("CRUD operation lifecycle wraps a mutation transaction and runs afterCommit
654
909
 
655
910
  await actions[0].execute(input, context);
656
911
 
912
+ // The hooks and the standard operation share the transaction's options; afterCommit gets the context alone.
657
913
  assert.deepEqual(calls, [
658
914
  "transaction:begin",
659
- ["before", "update", "42", "tester", trx],
915
+ ["before", "update", "42", "tester", txOptions],
660
916
  "execute",
661
- ["service", "42", { title: "Kindred" }, trx],
662
- ["after", "42", trx],
917
+ ["service", "42", { title: "Kindred" }, txOptions],
918
+ ["after", "42", txOptions],
663
919
  "transaction:commit",
664
- ["afterCommit", "42", null]
920
+ ["afterCommit", "42", { context }]
665
921
  ]);
922
+ assert.equal(calls[1][4].context, context);
923
+ });
924
+
925
+ test("a CRUD lifecycle hook reading trx fails, naming options", async () => {
926
+ const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
927
+ namespace: "books",
928
+ resource: createBookResource(),
929
+ repository: {
930
+ async withTransaction(options, work) {
931
+ return work(Object.freeze({ ...options, trx: { id: "transaction" } }));
932
+ }
933
+ },
934
+ service: {
935
+ patch(recordId, patch) {
936
+ return { data: { id: recordId, attributes: patch } };
937
+ }
938
+ },
939
+ surface: "app",
940
+ operations: ["update"],
941
+ permissionForOperation: () => ({ require: "authenticated" }),
942
+ operationLifecycle: {
943
+ update: {
944
+ before({ trx }) {
945
+ return trx;
946
+ }
947
+ }
948
+ }
949
+ }));
950
+
951
+ await assert.rejects(
952
+ () => actions[0].execute({ recordId: "42", title: "Kindred" }, { actor: "tester" }),
953
+ /A CRUD lifecycle hook's argument no longer has trx: pass options, which carries the operation's transaction/u
954
+ );
666
955
  });
667
956
 
668
957
  test("CRUD operation lifecycle does not run after or afterCommit when the transaction fails", async () => {
@@ -672,13 +961,13 @@ test("CRUD operation lifecycle does not run after or afterCommit when the transa
672
961
  namespace: "books",
673
962
  resource: createBookResource(),
674
963
  repository: {
675
- async withTransaction(work) {
964
+ async withTransaction(options, work) {
676
965
  calls.push("transaction:begin");
677
- return work({ id: "transaction" });
966
+ return work({ ...options, trx: "transaction" });
678
967
  }
679
968
  },
680
969
  service: {
681
- async patchDocumentById() {
970
+ async patch() {
682
971
  calls.push("service");
683
972
  throw error;
684
973
  }
@@ -717,15 +1006,15 @@ test("a CRUD create that returns no tagged JSON:API result with the record id fa
717
1006
  namespace: "books",
718
1007
  resource: createBookResource(),
719
1008
  repository: {
720
- async withTransaction(work) {
1009
+ async withTransaction(options, work) {
721
1010
  calls.push("transaction:begin");
722
- const result = await work({ id: "transaction" });
1011
+ const result = await work({ ...options, trx: "transaction" });
723
1012
  calls.push("transaction:commit");
724
1013
  return result;
725
1014
  }
726
1015
  },
727
1016
  service: {
728
- async createDocument() {
1017
+ async create() {
729
1018
  return returnJsonApiDocument(createdDocument);
730
1019
  }
731
1020
  },
@@ -753,7 +1042,7 @@ test("a CRUD create that returns no tagged JSON:API result with the record id fa
753
1042
  resource: createBookResource(),
754
1043
  repository: {},
755
1044
  service: {
756
- async createDocument() {
1045
+ async create() {
757
1046
  return createdDocument;
758
1047
  }
759
1048
  },
@@ -772,7 +1061,7 @@ test("a CRUD create that returns no tagged JSON:API result with the record id fa
772
1061
  resource: createBookResource(),
773
1062
  repository: {},
774
1063
  service: {
775
- async createDocument() {
1064
+ async create() {
776
1065
  return returned;
777
1066
  }
778
1067
  },
@@ -793,14 +1082,14 @@ test("CRUD afterCommit failures preserve the original cause and acknowledged com
793
1082
  namespace: "books",
794
1083
  resource: createBookResource(),
795
1084
  repository: {
796
- async withTransaction(work) {
797
- const result = await work({ id: "transaction" });
1085
+ async withTransaction(options, work) {
1086
+ const result = await work({ ...options, trx: "transaction" });
798
1087
  committed = true;
799
1088
  return result;
800
1089
  }
801
1090
  },
802
1091
  service: {
803
- patchDocumentById(id, attributes) { return { data: { id, attributes } }; }
1092
+ patch(id, attributes) { return { data: { id, attributes } }; }
804
1093
  },
805
1094
  surface: "app",
806
1095
  operations: ["update"],
@@ -830,15 +1119,15 @@ test("CRUD failures before acknowledged commit are not marked committed", async
830
1119
  namespace: "books",
831
1120
  resource: createBookResource(),
832
1121
  repository: {
833
- async withTransaction(work) {
834
- const result = await work({ id: "transaction" });
1122
+ async withTransaction(options, work) {
1123
+ const result = await work({ ...options, trx: "transaction" });
835
1124
  if (phase === "commit") throw failure;
836
1125
  committed = true;
837
1126
  return result;
838
1127
  }
839
1128
  },
840
1129
  service: {
841
- patchDocumentById(id, attributes) { return { data: { id, attributes } }; }
1130
+ patch(id, attributes) { return { data: { id, attributes } }; }
842
1131
  },
843
1132
  surface: "app",
844
1133
  operations: ["update"],
@@ -860,15 +1149,29 @@ test("CRUD failures before acknowledged commit are not marked committed", async
860
1149
  }
861
1150
  });
862
1151
 
863
- test("defineCrudJsonApiFeature exposes custom service methods as actions and optional routes", async () => {
1152
+ test("a CRUD custom action name is lower case: cancelDay is refused with the rule, cancel-day is taken", () => {
1153
+ const actionsNamed = (name) => createCrudJsonApiActions(crudJsonApiActionOptions({
1154
+ namespace: "books",
1155
+ resource: createBookResource(),
1156
+ service: {},
1157
+ surface: "app",
1158
+ permissionForOperation: () => ({ require: "authenticated" }),
1159
+ operations: [],
1160
+ actions: { [name]: { input: schemaDefinition({}), execute: () => null } }
1161
+ }));
1162
+ assert.throws(() => actionsNamed("cancelDay"), /name "cancelDay" is invalid: an action name is lower case, starts with a letter/u);
1163
+ assert.deepEqual(actionsNamed("cancel-day").map(({ id }) => id), ["crud.books.cancel-day"]);
1164
+ });
1165
+
1166
+ test("defineCrudFeature exposes custom service methods as actions and optional routes", async () => {
864
1167
  const routes = [];
865
1168
  const calls = [];
866
1169
  const confirmInput = schemaDefinition({
867
1170
  recordId: { type: "string", required: true },
868
1171
  note: { type: "string", required: false }
869
1172
  });
870
- const feature = defineCrudJsonApiFeature({
871
- resource: createBookResource(),
1173
+ const feature = defineCrudFeature({
1174
+ crud: createBookResource(),
872
1175
  surface: "app",
873
1176
  relativePath: "/books",
874
1177
  decorateService({ service }) {
@@ -965,40 +1268,40 @@ test("defineCrudJsonApiFeature exposes custom service methods as actions and opt
965
1268
  await runtime.shutdown();
966
1269
  });
967
1270
 
968
- test("defineCrudJsonApiFeature rejects implicit workspace scope and public private ownership", () => {
1271
+ test("defineCrudFeature rejects implicit workspace scope and public private ownership", () => {
969
1272
  assert.throws(
970
- () => defineCrudJsonApiFeature({
971
- resource: createBookResource(),
1273
+ () => defineCrudFeature({
1274
+ crud: createBookResource(),
972
1275
  surface: "app",
973
1276
  routes: "sometimes"
974
1277
  }),
975
1278
  /routes must be a boolean/u
976
1279
  );
977
1280
  assert.throws(
978
- () => defineCrudJsonApiFeature({
979
- resource: createBookResource({ autofilter: "workspace" }),
1281
+ () => defineCrudFeature({
1282
+ crud: createBookResource({ ownership: "workspace" }),
980
1283
  surface: "app"
981
1284
  }),
982
1285
  /requires explicit scope routeBase, actionInputValidator, routeParamsValidator, inputKeys, input/u
983
1286
  );
984
1287
  assert.throws(
985
- () => defineCrudJsonApiFeature({
986
- resource: createBookResource({ apiAccess: "public", autofilter: "user" }),
1288
+ () => defineCrudFeature({
1289
+ crud: createBookResource({ apiAccess: "public", ownership: "user" }),
987
1290
  surface: "public"
988
1291
  }),
989
- /public CRUD feature requires ownershipFilter "public"/u
1292
+ /public CRUD feature serves a table resource whose ownership \(or visibility\) is "public"/u
990
1293
  );
991
1294
  assert.throws(
992
- () => defineCrudJsonApiFeature({
993
- resource: createBookResource(),
1295
+ () => defineCrudFeature({
1296
+ crud: createBookResource(),
994
1297
  surface: "app",
995
1298
  operationLifecycle: { list: { afterCommit() {} } }
996
1299
  }),
997
1300
  /afterCommit is only valid for mutations/u
998
1301
  );
999
1302
  assert.throws(
1000
- () => defineCrudJsonApiFeature({
1001
- resource: createBookResource(),
1303
+ () => defineCrudFeature({
1304
+ crud: createBookResource(),
1002
1305
  surface: "app",
1003
1306
  operationLifecycle: { update: { eventually() {} } }
1004
1307
  }),
@@ -1016,7 +1319,7 @@ test("registerCrudJsonApiRoutes forwards scope, record, query, and body values t
1016
1319
  },
1017
1320
  crudJsonApiRouteOptions({
1018
1321
  namespace: "books",
1019
- resource: createBookResource({ autofilter: "workspace" }),
1322
+ resource: createBookResource({ ownership: "workspace" }),
1020
1323
  routeBase: "/w/:workspaceSlug",
1021
1324
  relativePath: "/books",
1022
1325
  surface: "app",