@jskit-ai/crud-core 0.2.17 → 0.2.19

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A CRUD contract whose `includeFields` lists a link of the included record as a field is refused at boot, at every depth, with an error that names the form to use: a belongs-to field by its key (`"locationId"`) or its relationship (`"location"`), or a collection relation. A JSON:API document answers a link under the record's relationships, never among its attributes, so such an entry never showed and the included record read as if it had no link, which emptied an app's board grouped by it. List it as `{ location: [] }`, which answers the linked id, with the fields to show of the linked record inside it. `CrudContractsProvider` checks every registered contract when it seals the registry at boot, once every feature owns its tables, against the table resources `runtime.resources` answers; a level whose table no feature owns is left alone.
6
+ - Depends on json-rest-api 3.1.1 exactly (from 3.1.0), from the registry with its published integrity: a sort on the ID, or on a required attribute stored in its own table, carries no null placement, so PostgreSQL and MariaDB read a descending page from an index instead of sorting every matching row.
5
7
  - Depends on json-rest-api 3.1.0 exactly (from 3.0.1), from the registry with its published integrity: `lockMode: "noKeyUpdate"`, ON CONFLICT on the matching unique index's exact columns, the PostgreSQL merge race on an uncommitted insert, and the `xid8` field type the change horizon reads.
6
8
  - `defineCrudFeature` refuses a table resource with ownership `system`, which only a system context reaches: a CRUD surface serves requests, so the owner serves what a request may see through its own methods instead.
7
9
  - The package's data tests run on `createPackageTestKnex`, so CI's `DB_CLIENT=pg` run proves the CRUD paths on PostgreSQL too.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/crud-core",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -22,7 +22,7 @@
22
22
  "dependencies": {
23
23
  "@jskit-ai/resource-core": "0.1.206",
24
24
  "@jskit-ai/resource-crud-core": "0.1.206",
25
- "json-rest-api": "3.1.0",
25
+ "json-rest-api": "3.1.1",
26
26
  "json-rest-schema": "^1.0.17"
27
27
  },
28
28
  "description": "Shared server-side CRUD service, repository, route, and query helpers.",
@@ -51,6 +51,6 @@
51
51
  "peerDependencies": {
52
52
  "@jskit-ai/http-runtime": "0.2.15",
53
53
  "@jskit-ai/kernel": "0.2.15",
54
- "@jskit-ai/resource-runtime": "0.2.14"
54
+ "@jskit-ai/resource-runtime": "0.2.16"
55
55
  }
56
56
  }
@@ -9,7 +9,7 @@
9
9
  "./shared": "./src/shared/index.js"
10
10
  },
11
11
  "dependencies": {
12
- "@jskit-ai/crud-core": "0.2.17",
12
+ "@jskit-ai/crud-core": "0.2.19",
13
13
  "@jskit-ai/resource-core": "0.1.206",
14
14
  "@jskit-ai/resource-crud-core": "0.1.206"
15
15
  },
@@ -1,4 +1,5 @@
1
1
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
2
+ import { checkIncludedFields } from "./jsonApiModule/service.js";
2
3
 
3
4
  /**
4
5
  * The CRUD contracts an application serves, one per namespace. Each CRUD
@@ -29,7 +30,17 @@ function createCrudContracts() {
29
30
  }
30
31
  }
31
32
 
32
- function seal() {
33
+ /**
34
+ * Ends registration. Given the resource runtime's owned table resources by name, it first checks each contract's
35
+ * includes against the tables they include (see checkIncludedFields): at boot every feature owns its tables.
36
+ * @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} [tableResource]
37
+ */
38
+ function seal(tableResource) {
39
+ if (tableResource) {
40
+ for (const crud of registered) {
41
+ checkIncludedFields(crud, tableResource);
42
+ }
43
+ }
33
44
  sealed = true;
34
45
  }
35
46
 
@@ -41,13 +52,19 @@ function createCrudContracts() {
41
52
 
42
53
  const CrudContractsProvider = defineProvider({
43
54
  id: "crud.contracts",
55
+ optional: {
56
+ resources: "runtime.resources"
57
+ },
44
58
  provides: {
45
59
  contracts: "crud.contracts"
46
60
  },
47
61
  setup: () => ({ contracts: createCrudContracts() }),
48
- /** @param {object} _dependencies @param {{ outputs: { contracts: ReturnType<typeof createCrudContracts> } }} context */
49
- boot(_dependencies, { outputs }) {
50
- outputs.contracts.seal();
62
+ /**
63
+ * @param {{ resources?: import("@jskit-ai/resource-runtime/server/types").ResourceRuntime }} dependencies
64
+ * @param {{ outputs: { contracts: ReturnType<typeof createCrudContracts> } }} context
65
+ */
66
+ boot({ resources }, { outputs }) {
67
+ outputs.contracts.seal(resources?.tableResource);
51
68
  }
52
69
  });
53
70
 
@@ -1,5 +1,7 @@
1
1
  import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
2
2
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
3
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
+ import { resolveCrudResourceScopeName } from "@jskit-ai/resource-crud-core/shared/crudLookup";
3
5
  import { buildJsonRestQueryParams, passedOn } from "@jskit-ai/resource-runtime/server";
4
6
  import {
5
7
  resolveDeclaredLookupContainerKey,
@@ -75,6 +77,71 @@ function documentShapes(crud) {
75
77
  return new Map(contractShape(crud).relationships.map((entry) => [entry.relationshipName, includedShape(entry.include, entry.labelKey)]));
76
78
  }
77
79
 
80
+ /**
81
+ * The links a table resource's records carry in a JSON:API document, by relationship name: each belongs-to field's
82
+ * (its `as`, or its key) and each collection relation's, with the field that declares it and the resource it links to.
83
+ * @param {{ schema?: Record<string, any> }} resource
84
+ * @returns {Map<string, { fieldKey: string, target: string }>}
85
+ */
86
+ function linksOf(resource) {
87
+ const links = new Map();
88
+ for (const [fieldKey, definition] of Object.entries(resource.schema ?? {})) {
89
+ const belongsTo = normalizeText(definition?.belongsTo);
90
+ const relation = isRecord(definition?.relation) ? definition.relation : {};
91
+ if (belongsTo) {
92
+ links.set(normalizeText(definition.as) || fieldKey, { fieldKey, target: belongsTo });
93
+ } else if (normalizeText(relation.kind).toLowerCase() === "collection") {
94
+ links.set(normalizeText(relation.as || definition.as) || fieldKey, {
95
+ fieldKey,
96
+ target: resolveCrudResourceScopeName(relation.target || relation.targetResource || relation.namespace || relation.apiPath)
97
+ });
98
+ }
99
+ }
100
+ return links;
101
+ }
102
+
103
+ /**
104
+ * Refuses a field an include lists that is a link of the included record: a belongs-to field, by its key
105
+ * (`locationId`) or its relationship (`location`), or a collection relation. A JSON:API document answers a link
106
+ * under the record's relationships, never among its attributes, so the field would never show and the record would
107
+ * read as if it had no link. The list names a link as `{ location: [] }`, which answers the linked record's id, with
108
+ * the fields to show of that record inside it. Each level is checked against its own table resource; a level whose
109
+ * resource no feature owns is left to the request.
110
+ * @param {import("../types.js").CrudContract} crud
111
+ * @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} tableResource The resource runtime's
112
+ * owned table resources, by name.
113
+ */
114
+ function checkIncludedFields(crud, tableResource) {
115
+ const check = (label, resourceName, { attributes, relationships }) => {
116
+ const resource = tableResource(resourceName);
117
+ if (!resource) {
118
+ return;
119
+ }
120
+ const links = linksOf(resource);
121
+ for (const name of attributes) {
122
+ const relationshipName = links.has(name) ? name : [...links].find(([, { fieldKey }]) => fieldKey === name)?.[0];
123
+ if (relationshipName) {
124
+ throw new TypeError(
125
+ `A CRUD contract's ${label} lists "${name}", which is a link of ${resourceName} to ` +
126
+ `${links.get(relationshipName).target}, not one of its fields: a document answers a link under its ` +
127
+ `relationship, never as a field, so "${name}" would never show. List it as { ${relationshipName}: [] }, ` +
128
+ `which answers the linked record's id, and put the fields to show of that record inside it, such as ` +
129
+ `{ ${relationshipName}: ["name"] }.`
130
+ );
131
+ }
132
+ }
133
+ for (const [relationshipName, nested] of Object.entries(relationships)) {
134
+ const link = links.get(relationshipName);
135
+ if (link?.target) {
136
+ check(`${label}.${relationshipName}`, link.target, nested);
137
+ }
138
+ }
139
+ };
140
+ for (const { attributeKey, relationshipType, include } of contractShape(crud).relationships) {
141
+ check(`${attributeKey}.includeFields`, relationshipType, include);
142
+ }
143
+ }
144
+
78
145
  // What each CRUD contract shows, by contract. defineCrudContract deep-freezes a contract, so what it shows is worked
79
146
  // out once and every service on it reads the same shapes; a contract whose shapes throw keeps nothing.
80
147
  const shapesByContract = new WeakMap();
@@ -253,4 +320,4 @@ function createCrudService({ repository, crud }) {
253
320
  });
254
321
  }
255
322
 
256
- export { createCrudService };
323
+ export { checkIncludedFields, createCrudService };
@@ -3,12 +3,14 @@ import test from "node:test";
3
3
  import { simplifyJsonApiResult } from "@jskit-ai/http-runtime/shared";
4
4
  import { validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
5
5
  import { passedOn } from "@jskit-ai/resource-runtime/server";
6
- import { createPackageTestKnex, createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
6
+ import { createPackageTestKnex, createTestResourceRuntime, startTestFeatures } from "@jskit-ai/resource-runtime/test";
7
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
7
8
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
8
9
  import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
9
10
  import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
10
11
  import { createCrudService } from "../src/server/jsonApiModule/service.js";
11
- import { createCrudContracts } from "../src/server/crudContracts.js";
12
+ import { CrudContractsProvider, createCrudContracts } from "../src/server/crudContracts.js";
13
+ import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
12
14
  import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
13
15
 
14
16
  // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
@@ -321,6 +323,79 @@ test("an include shows the records it links to only as deep, and only with the f
321
323
  }
322
324
  });
323
325
 
326
+ test("an include that lists a link of the included record as a field is refused at boot, naming the link's form, which answers the linked id", async (t) => {
327
+ const publishers = defineTableResource({
328
+ name: "publishers",
329
+ tableName: "publishers",
330
+ ownership: "public",
331
+ schema: {
332
+ name: { type: "string", required: true },
333
+ founderId: { type: "id", nullable: true, lookup: "authors", storage: { column: "founder_id" } }
334
+ }
335
+ });
336
+ const authors = defineTableResource({
337
+ name: "authors",
338
+ tableName: "authors",
339
+ ownership: "public",
340
+ schema: {
341
+ name: { type: "string", required: true },
342
+ publisherId: { type: "id", nullable: true, lookup: "publishers", storage: { column: "publisher_id" } }
343
+ }
344
+ });
345
+ const notes = defineTableResource({
346
+ name: "notes",
347
+ tableName: "notes",
348
+ ownership: "public",
349
+ schema: { title: { type: "string", required: true }, authorId: { type: "id", nullable: true, lookup: "authors", storage: { column: "author_id" } } }
350
+ });
351
+ // The notes feature serves the notes; another feature owns the tables its include reaches.
352
+ const start = async (includeFields) => {
353
+ const knex = await testKnex(t);
354
+ const started = await startTestFeatures({
355
+ knex,
356
+ features: [
357
+ CrudContractsProvider,
358
+ defineFeature({ id: "test.authors", owns: [authors, publishers], setup: () => ({}) }),
359
+ defineCrudFeature({
360
+ crud: defineCrudContract(notes, { namespace: "notes", operations: ["view"], fields: { title: { output: "required" }, authorId: { output: { required: false, includeFields } } } }),
361
+ surface: "home",
362
+ routes: false
363
+ })
364
+ ],
365
+ requires: { notes: "crud.notes" },
366
+ inputs: { "runtime.http": { router: { register() {} } } },
367
+ createTables: true
368
+ });
369
+ t.after(started.stop);
370
+ return { knex, service: started.capabilities.notes.service };
371
+ };
372
+
373
+ // A belongs-to field is a relationship in a JSON:API document, so listed as a field, by its key or by its
374
+ // relationship, it would never show: the boot refuses it, at every depth, and names the form that shows it.
375
+ for (const [includeFields, label, named, form] of [
376
+ [["name", "publisherId"], "authorId.includeFields", "publisherId", "{ publisher: [] }"],
377
+ [["publisher"], "authorId.includeFields", "publisher", "{ publisher: [] }"],
378
+ [["name", { publisher: ["name", "founderId"] }], "authorId.includeFields.publisher", "founderId", "{ founder: [] }"]
379
+ ]) {
380
+ await assert.rejects(start(includeFields), (error) => {
381
+ assert.ok(error instanceof TypeError);
382
+ assert.ok(error.message.startsWith(`A CRUD contract's ${label} lists "${named}", which is a link of `), error.message);
383
+ assert.ok(error.message.includes(`List it as ${form}`), error.message);
384
+ return true;
385
+ });
386
+ }
387
+
388
+ // Listed as a link, it shows: the included author answers its publisher's id, and nothing of the publisher.
389
+ const { knex, service } = await start(["name", { publisher: [] }]);
390
+ await knex("publishers").insert({ name: "Acme" });
391
+ await knex("authors").insert({ name: "Ada", publisher_id: 1 });
392
+ await knex("notes").insert({ title: "First", author_id: 1 });
393
+ const { included } = (await service.view("1", { include: "author" }, {})).value;
394
+ assert.deepEqual(included.map(({ type, attributes, relationships }) => [type, attributes, relationships.publisher.data]), [
395
+ ["authors", { name: "Ada" }, { type: "publishers", id: "1" }]
396
+ ]);
397
+ });
398
+
324
399
  test("the CRUD service answers documents, and 404 for a record that is missing or out of scope", async (t) => {
325
400
  const { service } = await createFixture(t);
326
401
  const page = await service.list({ title: "Note 7", fields: { notes: ["title"] } }, { context: WORKSPACE_ONE });