@jskit-ai/crud-core 0.2.66 → 0.2.68
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 +3 -0
- package/package.json +3 -3
- package/patterns/crud-feature-package/example/packages/books/package.json +2 -2
- package/src/server/jsonApiModule/actions.js +5 -3
- package/src/server/jsonApiModule/service.js +24 -3
- package/src/server/routeContracts.js +4 -2
- package/test/declaredRecordIds.test.js +170 -0
- package/test/namespaceResourceType.test.js +188 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A CRUD feature's record routes and its view, update and delete actions take the record ids its contract's `recordId` says (`@jskit-ai/resource-crud-core`'s `defineCrudContract`), in place of the kernel's positive-integer `recordIdParamsValidator`, so the assistant and the HTTP routes view, change and delete a legacy row 0 that the owner's `normalizeId` keeps (jskit-ai#503). A contract without `recordId` takes positive integers as before.
|
|
6
|
+
- A CRUD list or view's sparse fieldset for its own records, named by the contract's namespace as its routes and the assistant's description name it (`fields[job_kinds]=name`), narrows them when the table resource's name is not the namespace in camelCase (`taskTypes` as `job_kinds`; jskit-ai#503). The service passed the namespace key on, and json-rest-api refused it with "Unknown resource type 'jobKinds' requested in sparse fields"; it now names that fieldset by the table resource.
|
|
7
|
+
- A CRUD action's documents carry the contract's namespace as their records' JSON:API type, as its HTTP routes answer it, whatever its table resource is named (jskit-ai#503). The CRUD service answered json-rest-api's documents, which type a record by its table resource's name, so a resource served under another namespace (`checklistTypes` as `checklist_types`) answered `checklistTypes` from its list, view, create and update actions; its HTTP routes still answered `checklist_types` because the response schema writes the type it declares. The assistant's result transform, which decodes the action's document as the routes answer it, then refused every such list and view (and create and update) with "Expected JSON:API resource type checklist_types, received checklistTypes.", a 500. The service now gives its own records the namespace as their type; a link and the included record it reaches keep the table resource's name, as the routes answer them, so a reader still pairs them.
|
|
5
8
|
- Each CRUD route names the action it runs (`actionId`, `crud.<namespace>.<operation>` or the custom action's id), so a signed-in CRUD route answers a caller without the action's permission 403 before validating the query, path or body, and before refusing an undeclared list query key (#497).
|
|
6
9
|
- Depends on json-rest-api 3.3.5 exactly (from 3.3.4), the version resource-runtime takes: a read validates and parses only what it must, and a patch answering nothing or its id, and a delete, read no stored row columns that nothing uses (details in `@jskit-ai/resource-runtime`'s changelog). No crud-core code changes.
|
|
7
10
|
- Depends on json-rest-api 3.3.4 exactly (from 3.3.3), the version resource-runtime takes: a write finds the relationships that reference its resource from an index built once per published schema (details in `@jskit-ai/resource-runtime`'s changelog). No crud-core code changes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/crud-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.68",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@jskit-ai/resource-core": "0.1.229",
|
|
24
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
24
|
+
"@jskit-ai/resource-crud-core": "0.1.232",
|
|
25
25
|
"json-rest-api": "3.3.5",
|
|
26
26
|
"json-rest-schema": "^1.0.20"
|
|
27
27
|
},
|
|
@@ -51,6 +51,6 @@
|
|
|
51
51
|
"peerDependencies": {
|
|
52
52
|
"@jskit-ai/http-runtime": "0.2.39",
|
|
53
53
|
"@jskit-ai/kernel": "0.2.38",
|
|
54
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
54
|
+
"@jskit-ai/resource-runtime": "0.2.62"
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
"./shared": "./src/shared/index.js"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@jskit-ai/crud-core": "0.2.
|
|
12
|
+
"@jskit-ai/crud-core": "0.2.68",
|
|
13
13
|
"@jskit-ai/resource-core": "0.1.229",
|
|
14
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.232"
|
|
15
15
|
},
|
|
16
16
|
"jskit": {
|
|
17
17
|
"kind": "runtime",
|
|
@@ -38,6 +38,8 @@ function resolveCrudActionChannels(permission, servedOverHttp) {
|
|
|
38
38
|
|
|
39
39
|
function buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs) {
|
|
40
40
|
const definitions = scopeInputValidator ? [scopeInputValidator] : [];
|
|
41
|
+
// The record ids the contract's recordId says it takes, else positive integers (see defineCrudContract).
|
|
42
|
+
const recordIdParams = resource.recordIdParams ?? recordIdParamsValidator;
|
|
41
43
|
// A fieldset for a type the includes reach below their first level is checked by the action's checkInput, after this
|
|
42
44
|
// schema (see createIncludedFieldsetsCheck): only the tables they cross name that type, and every feature owns its
|
|
43
45
|
// tables at boot.
|
|
@@ -48,15 +50,15 @@ function buildActionInput(resource, operation, scopeInputValidator, listFilterQu
|
|
|
48
50
|
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
|
|
49
51
|
}));
|
|
50
52
|
} else if (operation === "view") {
|
|
51
|
-
definitions.push(
|
|
53
|
+
definitions.push(recordIdParams, ...createStandardCrudViewQueryValidators({
|
|
52
54
|
fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
|
|
53
55
|
}));
|
|
54
56
|
} else if (operation === "create") {
|
|
55
57
|
definitions.push(operationInputs.create || resource.operations.create.body);
|
|
56
58
|
} else if (operation === "update") {
|
|
57
|
-
definitions.push(
|
|
59
|
+
definitions.push(recordIdParams, operationInputs.update || resource.operations.patch.body);
|
|
58
60
|
} else {
|
|
59
|
-
definitions.push(
|
|
61
|
+
definitions.push(recordIdParams);
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
// Only update changes part of a record; every other operation's input is strict.
|
|
@@ -188,6 +188,11 @@ function contractShapes(crud) {
|
|
|
188
188
|
*/
|
|
189
189
|
function createCrudService({ repository, crud }) {
|
|
190
190
|
const resourceName = crud.resource.name;
|
|
191
|
+
// The JSON:API type of the contract's own records: its namespace, the API's public name, which its routes answer and
|
|
192
|
+
// every reader of its documents expects. json-rest-api types a record by its table resource's name, which a contract
|
|
193
|
+
// may serve under another namespace (checklistTypes as checklist_types). A link and the included record it reaches
|
|
194
|
+
// keep that name, so a reader still pairs them.
|
|
195
|
+
const recordType = crud.namespace;
|
|
191
196
|
const { own, linked: shapes } = contractShapes(crud);
|
|
192
197
|
|
|
193
198
|
/**
|
|
@@ -226,7 +231,8 @@ function createCrudService({ repository, crud }) {
|
|
|
226
231
|
if (!document?.data) {
|
|
227
232
|
return returnJsonApiDocument(document);
|
|
228
233
|
}
|
|
229
|
-
const records = (Array.isArray(document.data) ? document.data : [document.data])
|
|
234
|
+
const records = (Array.isArray(document.data) ? document.data : [document.data])
|
|
235
|
+
.map((record) => ({ ...shownRecord(record, own), type: recordType }));
|
|
230
236
|
const shown = { ...document, data: Array.isArray(document.data) ? records : records[0] };
|
|
231
237
|
if (document.included) {
|
|
232
238
|
const included = new Map(document.included.map((record) => [`${record.type}:${record.id}`, record]));
|
|
@@ -251,6 +257,21 @@ function createCrudService({ repository, crud }) {
|
|
|
251
257
|
return returnJsonApiDocument(shown);
|
|
252
258
|
}
|
|
253
259
|
|
|
260
|
+
/**
|
|
261
|
+
* The json-rest-api query params of an HTTP query. Its sparse fieldset for the contract's own records is named by their
|
|
262
|
+
* type, the namespace, and json-rest-api names them by the table resource, which a namespace need not spell
|
|
263
|
+
* (taskTypes as job_kinds).
|
|
264
|
+
* @param {Record<string, unknown>} query
|
|
265
|
+
*/
|
|
266
|
+
function queryParams(query) {
|
|
267
|
+
const fields = query?.fields;
|
|
268
|
+
if (recordType === resourceName || !isRecord(fields) || !Object.hasOwn(fields, recordType)) {
|
|
269
|
+
return buildJsonRestQueryParams(resourceName, query);
|
|
270
|
+
}
|
|
271
|
+
const { [recordType]: ownFields, ...linkedFields } = fields;
|
|
272
|
+
return buildJsonRestQueryParams(resourceName, { ...query, fields: { ...linkedFields, [resourceName]: ownFields } });
|
|
273
|
+
}
|
|
274
|
+
|
|
254
275
|
/**
|
|
255
276
|
* What the repository, or a decorator over it, receives: the caller's context and transaction, and the one setting
|
|
256
277
|
* the service names, JSON:API documents. A decorator passes only `{ context, trx }` on to another table.
|
|
@@ -267,7 +288,7 @@ function createCrudService({ repository, crud }) {
|
|
|
267
288
|
* @param {{ context?: object | null, trx?: object | null }} options
|
|
268
289
|
*/
|
|
269
290
|
async function list(query, options) {
|
|
270
|
-
return answer(await repository.query(
|
|
291
|
+
return answer(await repository.query(queryParams(query), documentOptions(options)));
|
|
271
292
|
}
|
|
272
293
|
|
|
273
294
|
/**
|
|
@@ -283,7 +304,7 @@ function createCrudService({ repository, crud }) {
|
|
|
283
304
|
);
|
|
284
305
|
}
|
|
285
306
|
try {
|
|
286
|
-
return answer(requireDocument(await repository.get(recordId,
|
|
307
|
+
return answer(requireDocument(await repository.get(recordId, queryParams(query), documentOptions(options))));
|
|
287
308
|
} catch (error) {
|
|
288
309
|
throw isNotFound(error, resourceName) ? documentNotFound() : error;
|
|
289
310
|
}
|
|
@@ -392,12 +392,14 @@ function createCrudJsonApiRouteContracts({
|
|
|
392
392
|
includeQueryValidator: lookupIncludeQueryValidator
|
|
393
393
|
})
|
|
394
394
|
);
|
|
395
|
+
// The record ids the contract's recordId says it takes, else positive integers (see defineCrudContract).
|
|
396
|
+
const recordIdParams = resource.recordIdParams ?? recordIdParamsValidator;
|
|
395
397
|
const recordRouteParamsValidator = routeParamsValidator
|
|
396
398
|
? composeSchemaDefinitions([
|
|
397
399
|
routeParamsValidator,
|
|
398
|
-
|
|
400
|
+
recordIdParams
|
|
399
401
|
])
|
|
400
|
-
:
|
|
402
|
+
: recordIdParams;
|
|
401
403
|
const routeType = resource.namespace;
|
|
402
404
|
const viewOutput = resource.operations?.view?.output;
|
|
403
405
|
const createBody = operationInputs.create || resource.operations?.create?.body;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import knexLib from "knex";
|
|
5
|
+
import { createServiceToolCatalog } from "@jskit-ai/assistant-core/server";
|
|
6
|
+
import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
|
|
7
|
+
import { validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
|
|
8
|
+
import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
9
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
10
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
11
|
+
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
12
|
+
import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
|
|
13
|
+
import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
|
|
14
|
+
import { CrudContractsProvider } from "../src/server/crudContracts.js";
|
|
15
|
+
import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
|
|
16
|
+
|
|
17
|
+
// A legacy table with one legitimate row 0, as an application's checklist types have: its owner keeps id "0" with its
|
|
18
|
+
// own normalizeId, and its CRUD contract's recordId says its ids are 0 or a positive integer.
|
|
19
|
+
const ZERO_OR_POSITIVE = "^(0|[1-9][0-9]*)$";
|
|
20
|
+
const checklistTypes = defineTableResource({
|
|
21
|
+
name: "checklistTypes",
|
|
22
|
+
tableName: "checklistTypes",
|
|
23
|
+
ownership: "public",
|
|
24
|
+
schema: { name: { type: "string", required: true } }
|
|
25
|
+
});
|
|
26
|
+
const checklistTemplates = defineTableResource({
|
|
27
|
+
name: "checklistTemplates",
|
|
28
|
+
tableName: "checklistTemplates",
|
|
29
|
+
ownership: "public",
|
|
30
|
+
schema: {
|
|
31
|
+
title: { type: "string", required: true },
|
|
32
|
+
// A link to row 0 is a whole number from 0: an id field takes ids from 1.
|
|
33
|
+
checklistTypeId: { type: "integer", min: 0, nullable: true, lookup: "checklist_types", storage: { column: "checklist_type_id" } }
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
const checklistTemplatesContract = defineCrudContract(checklistTemplates, {
|
|
37
|
+
namespace: "checklist_templates",
|
|
38
|
+
apiAccess: "public",
|
|
39
|
+
operations: ["list", "view", "patch"],
|
|
40
|
+
contract: { lookup: { containerKey: "lookups" } },
|
|
41
|
+
fields: {
|
|
42
|
+
title: { output: "required", patch: "optional" },
|
|
43
|
+
checklistTypeId: { output: { required: false, includeFields: ["name"] }, patch: "optional" }
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
function normalizeChecklistTypeId(value) {
|
|
48
|
+
if (value === 0 || value === 0n || (typeof value === "string" && value.trim() === "0")) return "0";
|
|
49
|
+
return normalizeRecordId(value);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The checklist types' contract, with the keys a test adds. */
|
|
53
|
+
function checklistTypesContract(config = {}) {
|
|
54
|
+
return defineCrudContract(checklistTypes, {
|
|
55
|
+
namespace: "checklist_types",
|
|
56
|
+
apiAccess: "public",
|
|
57
|
+
fields: { name: { output: "required", create: "required", patch: "optional" } },
|
|
58
|
+
...config
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The field errors validating a payload against an output reports, or null when it passes. */
|
|
63
|
+
function outputErrors(output, payload) {
|
|
64
|
+
try {
|
|
65
|
+
validateSchemaPayload(output, payload, { phase: "output" });
|
|
66
|
+
return null;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return error.fieldErrors ?? error.details?.fieldErrors ?? { error: String(error) };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const byId = (left, right) => Number(left.id) - Number(right.id);
|
|
73
|
+
|
|
74
|
+
test("a CRUD contract that says nothing of its record ids answers positive integer ids only", () => {
|
|
75
|
+
const { operations } = checklistTypesContract();
|
|
76
|
+
|
|
77
|
+
assert.equal(outputErrors(operations.list.output, { items: [{ id: "1", name: "Safety" }], nextCursor: null }), null);
|
|
78
|
+
for (const [output, payload, field] of [
|
|
79
|
+
[operations.list.output, { items: [{ id: "0", name: "Legacy" }], nextCursor: null }, "items.0.id"],
|
|
80
|
+
[operations.view.output, { id: "0", name: "Legacy" }, "id"],
|
|
81
|
+
[operations.delete.output, { id: "0", deleted: true }, "id"]
|
|
82
|
+
]) {
|
|
83
|
+
assert.ok(outputErrors(output, payload)?.[field], `${field}: ${JSON.stringify(outputErrors(output, payload))}`);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("a CRUD contract's recordId must stay required text", () => {
|
|
88
|
+
for (const recordId of [ZERO_OR_POSITIVE, { type: "integer" }, { required: false }, { nullable: true }]) {
|
|
89
|
+
assert.throws(() => checklistTypesContract({ recordId }), /defineCrudContract\(checklistTypes\) recordId .*required text/u, JSON.stringify(recordId));
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("a CRUD contract whose recordId says its ids takes and answers them: the assistant and the HTTP routes read, change and delete row 0", async (t) => {
|
|
94
|
+
const contract = checklistTypesContract({ recordId: { pattern: ZERO_OR_POSITIVE } });
|
|
95
|
+
|
|
96
|
+
// The contract's outputs, which the assistant checks each result against, answer the ids it declares, and only those.
|
|
97
|
+
const { operations } = contract;
|
|
98
|
+
assert.equal(outputErrors(operations.list.output, { items: [{ id: "0", name: "Legacy" }], nextCursor: null }), null);
|
|
99
|
+
assert.equal(outputErrors(operations.view.output, { id: "0", name: "Legacy" }), null);
|
|
100
|
+
assert.equal(outputErrors(operations.delete.output, { id: "0", deleted: true }), null);
|
|
101
|
+
assert.ok(outputErrors(operations.view.output, { id: "00", name: "Legacy" })?.id);
|
|
102
|
+
|
|
103
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
104
|
+
t.after(() => knex.destroy());
|
|
105
|
+
const router = createRouter();
|
|
106
|
+
const started = await startTestFeatures({
|
|
107
|
+
knex,
|
|
108
|
+
features: [
|
|
109
|
+
CrudContractsProvider,
|
|
110
|
+
defineCrudFeature({ crud: contract, surface: "home", owns: [{ resource: checklistTypes, normalizeId: normalizeChecklistTypeId }] }),
|
|
111
|
+
defineCrudFeature({ crud: checklistTemplatesContract, surface: "home" })
|
|
112
|
+
],
|
|
113
|
+
requires: { actions: "runtime.actions" },
|
|
114
|
+
inputs: { "runtime.http": { router } },
|
|
115
|
+
createTables: true
|
|
116
|
+
});
|
|
117
|
+
t.after(started.stop);
|
|
118
|
+
await knex("checklistTypes").insert([{ id: 0, name: "Legacy" }, { id: 1, name: "Safety" }]);
|
|
119
|
+
await knex("checklistTemplates").insert({ id: 1, title: "Morning round", checklist_type_id: 1 });
|
|
120
|
+
const { actions } = started.capabilities;
|
|
121
|
+
|
|
122
|
+
// The HTTP routes take the declared ids as their record id, and refuse others.
|
|
123
|
+
const app = Fastify();
|
|
124
|
+
t.after(() => app.close());
|
|
125
|
+
registerApiErrorHandler(app);
|
|
126
|
+
registerRoutes(app, { routes: router.list(), actions });
|
|
127
|
+
const viewPath = router.list().find((route) => route.actionId === "crud.checklist_types.view").path;
|
|
128
|
+
const viewed = await app.inject({ method: "GET", url: viewPath.replace(":recordId", "0") });
|
|
129
|
+
assert.equal(viewed.statusCode, 200, viewed.body);
|
|
130
|
+
assert.deepEqual({ id: viewed.json().data.id, name: viewed.json().data.attributes.name }, { id: "0", name: "Legacy" });
|
|
131
|
+
assert.equal((await app.inject({ method: "GET", url: viewPath.replace(":recordId", "00") })).statusCode, 400);
|
|
132
|
+
|
|
133
|
+
const catalog = createServiceToolCatalog(actions, { maxDirectTools: 0 });
|
|
134
|
+
const context = { actor: { id: "7" }, surface: "home" };
|
|
135
|
+
const toolSet = catalog.resolveToolSet(context);
|
|
136
|
+
const call = (toolName, payload) => catalog.executeToolCall({ toolName, argumentsText: JSON.stringify(payload), context, toolSet });
|
|
137
|
+
const execute = (actionId, input) => call("assistant_action_execute", { actionId, version: 1, input });
|
|
138
|
+
async function run(actionId, input) {
|
|
139
|
+
const described = await call("assistant_action_contract", { actionId, version: 1 });
|
|
140
|
+
assert.equal(described.ok, true, JSON.stringify(described));
|
|
141
|
+
const executed = await execute(actionId, input);
|
|
142
|
+
assert.equal(executed.ok, true, `${actionId}: ${JSON.stringify(executed)}`);
|
|
143
|
+
return executed.result.result;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The model is told the ids a record takes.
|
|
147
|
+
const described = await call("assistant_action_contract", { actionId: "crud.checklist_types.view", version: 1 });
|
|
148
|
+
assert.equal(described.result.inputSchema.properties.recordId.pattern, ZERO_OR_POSITIVE, JSON.stringify(described));
|
|
149
|
+
|
|
150
|
+
const listed = await run("crud.checklist_types.list", { limit: 100 });
|
|
151
|
+
assert.deepEqual({ ...listed, items: listed.items.toSorted(byId) }, {
|
|
152
|
+
items: [{ id: "0", name: "Legacy" }, { id: "1", name: "Safety" }],
|
|
153
|
+
nextCursor: null
|
|
154
|
+
});
|
|
155
|
+
assert.deepEqual(await run("crud.checklist_types.view", { recordId: "0" }), { id: "0", name: "Legacy" });
|
|
156
|
+
assert.equal((await execute("crud.checklist_types.view", { recordId: "00" })).ok, false);
|
|
157
|
+
assert.deepEqual(await run("crud.checklist_types.update", { recordId: "0", name: "Legacy types" }), { id: "0", name: "Legacy types" });
|
|
158
|
+
|
|
159
|
+
// A record linked to row 0 reaches the model with its lookup.
|
|
160
|
+
const moved = await run("crud.checklist_templates.update", { recordId: "1", checklistTypeId: 0 });
|
|
161
|
+
assert.equal(String(moved.checklistTypeId), "0");
|
|
162
|
+
const templates = await run("crud.checklist_templates.list", { include: "checklistType" });
|
|
163
|
+
for (const template of [templates.items[0], await run("crud.checklist_templates.view", { recordId: "1", include: "checklistType" })]) {
|
|
164
|
+
assert.equal(template.title, "Morning round");
|
|
165
|
+
assert.deepEqual(template.lookups.checklistType, { id: "0", name: "Legacy types" });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
assert.deepEqual(await run("crud.checklist_types.delete", { recordId: "0" }), { id: "0", deleted: true });
|
|
169
|
+
assert.deepEqual(await knex("checklistTypes").pluck("id"), [1]);
|
|
170
|
+
});
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import knexLib from "knex";
|
|
5
|
+
import { createServiceToolCatalog } from "@jskit-ai/assistant-core/server";
|
|
6
|
+
import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
7
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
8
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
9
|
+
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
10
|
+
import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
|
|
11
|
+
import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
|
|
12
|
+
import { CrudContractsProvider } from "../src/server/crudContracts.js";
|
|
13
|
+
import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
|
|
14
|
+
|
|
15
|
+
// Tables named in camelCase, served under snake_case namespaces, as an application's checklist types and templates are:
|
|
16
|
+
// the namespace is the API's public name, and the JSON:API type its documents carry.
|
|
17
|
+
const checklistTypes = defineTableResource({
|
|
18
|
+
name: "checklistTypes",
|
|
19
|
+
tableName: "checklistTypes",
|
|
20
|
+
ownership: "public",
|
|
21
|
+
schema: {
|
|
22
|
+
name: { type: "string", required: true }
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
const checklistTemplates = defineTableResource({
|
|
26
|
+
name: "checklistTemplates",
|
|
27
|
+
tableName: "checklistTemplates",
|
|
28
|
+
ownership: "public",
|
|
29
|
+
schema: {
|
|
30
|
+
title: { type: "string", required: true },
|
|
31
|
+
checklistTypeId: { type: "id", nullable: true, lookup: "checklist_types", storage: { column: "checklist_type_id" } }
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
const checklistTypesContract = defineCrudContract(checklistTypes, {
|
|
35
|
+
namespace: "checklist_types",
|
|
36
|
+
apiAccess: "public",
|
|
37
|
+
fields: {
|
|
38
|
+
name: { output: "required", create: "required", patch: "optional" }
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const checklistTemplatesContract = defineCrudContract(checklistTemplates, {
|
|
42
|
+
namespace: "checklist_templates",
|
|
43
|
+
apiAccess: "public",
|
|
44
|
+
operations: ["list", "view", "create", "patch"],
|
|
45
|
+
contract: { lookup: { containerKey: "lookups" } },
|
|
46
|
+
fields: {
|
|
47
|
+
title: { output: "required", create: "required", patch: "optional" },
|
|
48
|
+
checklistTypeId: { output: { required: false, includeFields: ["name"] }, create: "optional", patch: "optional" }
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const API = Object.freeze({ channel: "api", surface: "home" });
|
|
52
|
+
|
|
53
|
+
async function startChecklists(t) {
|
|
54
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
55
|
+
t.after(() => knex.destroy());
|
|
56
|
+
const router = createRouter();
|
|
57
|
+
const started = await startTestFeatures({
|
|
58
|
+
knex,
|
|
59
|
+
features: [
|
|
60
|
+
CrudContractsProvider,
|
|
61
|
+
defineCrudFeature({ crud: checklistTypesContract, surface: "home" }),
|
|
62
|
+
defineCrudFeature({ crud: checklistTemplatesContract, surface: "home" })
|
|
63
|
+
],
|
|
64
|
+
requires: { actions: "runtime.actions" },
|
|
65
|
+
inputs: { "runtime.http": { router } },
|
|
66
|
+
createTables: true
|
|
67
|
+
});
|
|
68
|
+
t.after(started.stop);
|
|
69
|
+
await knex("checklistTypes").insert([{ id: 1, name: "Safety" }, { id: 2, name: "Hygiene" }]);
|
|
70
|
+
await knex("checklistTemplates").insert({ id: 1, title: "Morning round", checklist_type_id: 1 });
|
|
71
|
+
const app = Fastify();
|
|
72
|
+
t.after(() => app.close());
|
|
73
|
+
registerApiErrorHandler(app);
|
|
74
|
+
registerRoutes(app, { routes: router.list(), actions: started.capabilities.actions });
|
|
75
|
+
const pathOf = (actionId) => router.list().find((route) => route.actionId === actionId).path;
|
|
76
|
+
return { actions: started.capabilities.actions, app, pathOf };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const byId = (left, right) => Number(left.id) - Number(right.id);
|
|
80
|
+
|
|
81
|
+
// The JSON:API type of each primary record a document carries.
|
|
82
|
+
function primaryTypes(document) {
|
|
83
|
+
return (Array.isArray(document.data) ? document.data : [document.data]).map(({ type }) => type);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
test("a CRUD action's documents carry its namespace as their JSON:API type, as its HTTP routes answer, whatever its table is named", async (t) => {
|
|
87
|
+
const { actions, app, pathOf } = await startChecklists(t);
|
|
88
|
+
const execute = async (actionId, input) => (await actions.execute({ actionId, input, context: API })).value;
|
|
89
|
+
|
|
90
|
+
// The HTTP routes answer the namespace.
|
|
91
|
+
const listed = await app.inject({ method: "GET", url: pathOf("crud.checklist_types.list") });
|
|
92
|
+
assert.equal(listed.statusCode, 200, listed.body);
|
|
93
|
+
assert.deepEqual(primaryTypes(listed.json()), ["checklist_types", "checklist_types"]);
|
|
94
|
+
|
|
95
|
+
// The actions the routes run answer the same type, for every operation that answers a document.
|
|
96
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.list", {})), ["checklist_types", "checklist_types"]);
|
|
97
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.view", { recordId: "1" })), ["checklist_types"]);
|
|
98
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.create", { name: "Fire" })), ["checklist_types"]);
|
|
99
|
+
assert.deepEqual(primaryTypes(await execute("crud.checklist_types.update", { recordId: "3", name: "Fire drill" })), ["checklist_types"]);
|
|
100
|
+
|
|
101
|
+
// A record's link and the included record it reaches name the same type, in the action's document and over HTTP, so
|
|
102
|
+
// a reader finds the included record from the link.
|
|
103
|
+
const viewUrl = `${pathOf("crud.checklist_templates.view").replace(":recordId", "1")}?include=checklistType`;
|
|
104
|
+
const viewed = await app.inject({ method: "GET", url: viewUrl });
|
|
105
|
+
assert.equal(viewed.statusCode, 200, viewed.body);
|
|
106
|
+
for (const document of [viewed.json(), await execute("crud.checklist_templates.view", { recordId: "1", include: "checklistType" })]) {
|
|
107
|
+
assert.deepEqual(primaryTypes(document), ["checklist_templates"]);
|
|
108
|
+
const link = document.data.relationships.checklistType.data;
|
|
109
|
+
assert.deepEqual(document.included.map(({ type, id, attributes }) => ({ type, id, attributes })), [
|
|
110
|
+
{ type: link.type, id: link.id, attributes: { name: "Safety" } }
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("the assistant lists, views, creates, updates and deletes the records of a resource whose table is not named as its namespace", async (t) => {
|
|
116
|
+
const { actions } = await startChecklists(t);
|
|
117
|
+
const catalog = createServiceToolCatalog(actions, { maxDirectTools: 0 });
|
|
118
|
+
const context = { actor: { id: "7" }, surface: "home" };
|
|
119
|
+
const toolSet = catalog.resolveToolSet(context);
|
|
120
|
+
const call = (toolName, payload) => catalog.executeToolCall({ toolName, argumentsText: JSON.stringify(payload), context, toolSet });
|
|
121
|
+
async function run(actionId, input) {
|
|
122
|
+
const contract = await call("assistant_action_contract", { actionId, version: 1 });
|
|
123
|
+
assert.equal(contract.ok, true, JSON.stringify(contract));
|
|
124
|
+
const executed = await call("assistant_action_execute", { actionId, version: 1, input });
|
|
125
|
+
assert.equal(executed.ok, true, `${actionId}: ${JSON.stringify(executed)}`);
|
|
126
|
+
return executed.result.result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
for (const input of [{ limit: 100 }, { fields: { checklist_types: ["name"] } }]) {
|
|
130
|
+
const listed = await run("crud.checklist_types.list", input);
|
|
131
|
+
assert.deepEqual({ ...listed, items: listed.items.toSorted(byId) }, {
|
|
132
|
+
items: [{ id: "1", name: "Safety" }, { id: "2", name: "Hygiene" }],
|
|
133
|
+
nextCursor: null
|
|
134
|
+
}, JSON.stringify(input));
|
|
135
|
+
}
|
|
136
|
+
assert.deepEqual(await run("crud.checklist_types.view", { recordId: "1" }), { id: "1", name: "Safety" });
|
|
137
|
+
const created = await run("crud.checklist_types.create", { name: "Fire" });
|
|
138
|
+
assert.equal(created.name, "Fire");
|
|
139
|
+
assert.deepEqual(await run("crud.checklist_types.update", { recordId: created.id, name: "Fire drill" }), {
|
|
140
|
+
id: created.id,
|
|
141
|
+
name: "Fire drill"
|
|
142
|
+
});
|
|
143
|
+
assert.deepEqual(await run("crud.checklist_types.delete", { recordId: created.id }), { id: created.id, deleted: true });
|
|
144
|
+
|
|
145
|
+
// A record's included link reaches the model as its lookup, in a list and in a view.
|
|
146
|
+
const listed = await run("crud.checklist_templates.list", { include: "checklistType" });
|
|
147
|
+
assert.equal(listed.items.length, 1);
|
|
148
|
+
for (const template of [listed.items[0], await run("crud.checklist_templates.view", { recordId: "1", include: "checklistType" })]) {
|
|
149
|
+
assert.equal(template.title, "Morning round");
|
|
150
|
+
assert.deepEqual(template.lookups.checklistType, { id: "1", name: "Safety" });
|
|
151
|
+
}
|
|
152
|
+
const moved = await run("crud.checklist_templates.update", { recordId: "1", checklistTypeId: "2" });
|
|
153
|
+
assert.equal(String(moved.checklistTypeId), "2");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("a sparse fieldset named by the namespace narrows the records of a resource whose name the namespace does not spell", async (t) => {
|
|
157
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
158
|
+
t.after(() => knex.destroy());
|
|
159
|
+
const taskTypes = defineTableResource({
|
|
160
|
+
name: "taskTypes",
|
|
161
|
+
tableName: "taskTypes",
|
|
162
|
+
ownership: "public",
|
|
163
|
+
schema: { name: { type: "string", required: true }, code: { type: "string", nullable: true } }
|
|
164
|
+
});
|
|
165
|
+
const jobKinds = defineCrudContract(taskTypes, {
|
|
166
|
+
namespace: "job_kinds",
|
|
167
|
+
apiAccess: "public",
|
|
168
|
+
operations: ["list", "view"],
|
|
169
|
+
fields: { name: { output: "required" }, code: { output: { required: false } } }
|
|
170
|
+
});
|
|
171
|
+
const router = createRouter();
|
|
172
|
+
const started = await startTestFeatures({
|
|
173
|
+
knex,
|
|
174
|
+
features: [CrudContractsProvider, defineCrudFeature({ crud: jobKinds, surface: "home" })],
|
|
175
|
+
requires: { actions: "runtime.actions" },
|
|
176
|
+
inputs: { "runtime.http": { router } },
|
|
177
|
+
createTables: true
|
|
178
|
+
});
|
|
179
|
+
t.after(started.stop);
|
|
180
|
+
await knex("taskTypes").insert({ id: 1, name: "Inspection", code: "INS" });
|
|
181
|
+
const { actions } = started.capabilities;
|
|
182
|
+
|
|
183
|
+
for (const [actionId, input] of [["crud.job_kinds.list", {}], ["crud.job_kinds.view", { recordId: "1" }]]) {
|
|
184
|
+
const document = (await actions.execute({ actionId, input: { ...input, fields: { job_kinds: ["name"] } }, context: API })).value;
|
|
185
|
+
const [record] = Array.isArray(document.data) ? document.data : [document.data];
|
|
186
|
+
assert.deepEqual({ type: record.type, attributes: record.attributes }, { type: "job_kinds", attributes: { name: "Inspection" } }, actionId);
|
|
187
|
+
}
|
|
188
|
+
});
|