@jskit-ai/crud-core 0.2.25 → 0.2.26

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A CRUD list over HTTP takes a filter that holds several values (`recordIdMany`, `enumMany`, and the list's `id`) as one comma-separated value too, `filter[customer]=1,2`, the form JSON:API gives a list, where the route's query validation refused it with 400 before the filter could split it (since 0.2.46 the filter reads `1,2` as `["1", "2"]`, but only a value the client named twice reached it in that form). Each entry must still be valid: `filter[customer]=1,,2` or a value the filter does not offer still answers 400.
6
+ - A `recordIdMany` list filter's search schema entry (`jsonRestSearchSchema`) takes `{ type: "id" }` items, where its items were a JSON Schema `anyOf`, which json-rest-schema refuses: a list asked for such a filter (`filter[customer]=1&filter[customer]=2`) answered 500 instead of the rows of those ids. `listFilterRoutes.test.js` lists orders by customer over HTTP.
7
+ - A CRUD list asked over HTTP with a `dateRange` or `numberRange` filter (`filter[arrival]=2026-03-01..2026-03-31`, `filter[total]=15..35`) answers exactly the rows inside the range, where it answered 400: the list action read the route's parsed `{ from, to }` again and refused it (`@jskit-ai/resource-crud-core` now takes it), and past that `toJsonRestQuery` dropped it. A malformed range still answers 400. A `date` or `dateRange` filter's search keys (`__jskit_<key>_from`, `__jskit_<key>_toExclusive`) now hold the day's start as ISO 8601 in UTC (`2026-03-01T00:00:00.000Z`, was `2026-03-01 00:00:00`), the form json-rest-api's `dateTime` search keys take: the old form was refused with 422, so a date filter never filtered through `jsonRestSearchSchema`. `listFilterRoutes.test.js` lists orders over HTTP through a filter contract's route and action validators, search schema and `toJsonRestQuery`, on SQLite.
8
+ - A CRUD list or view takes a sparse fieldset for a record its includes reach below their first level, so `?include=customer,customer.region&fields[regions]=name` narrows the included regions where it answered 400. Such a `fields[<type>]` names only the fields and links the contract's `includeFields` lists of that type there, by every path that reaches it, and refuses any other field with a 400 coded `crud.query.fieldsNotShown` that names what it shows; a type no include reaches stays refused (`crud.query.fieldsKeysInvalid`, whose allowed keys now list the types reached). The includes still decide what an included record shows: a fieldset only narrows it. Types the contract links to directly keep taking any field name, as before. Only the tables an include crosses name such a type, so `CrudContractsProvider` resolves the types each contract's includes reach when it seals the registry at boot (`resolveIncludedTypes`, which was `checkIncludedFields` and still refuses a link listed as a field; `contracts.includedTypes(crud)`), and the list and view actions check those fieldsets when they run: `createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })` lets such a key through to `createIncludedFieldsetsCheck(resource)`, and without `deferIncludedTypes` refuses it as before. A test proves the narrowing and both refusals through the actions and over HTTP.
5
9
  - Depends on json-rest-api 3.1.4 exactly (from 3.1.3), from the registry with its published integrity: a patch, put or patchMany that stores the values a row already holds answers the row as stored on MySQL and MariaDB (it answered the values this transaction first read), and AnyAPI storage checks its tables' columns with one statement at start-up.
6
10
  - A CRUD list asked over HTTP for two or more values of a filter that takes several (`recordIdMany`, `enumMany`, and the list's `id`) answers the rows matching any of them, where it answered 400 (`@jskit-ai/resource-crud-core` reads the comma-separated value the route makes of them). The list's `id` passes the undeclared-key check, which a test proves.
7
11
  - **Breaking.** A CRUD list refuses a query key its route does not take with a 400 coded `crud.query.undeclaredKeys`, naming the key and the keys the list takes. Fastify's validation dropped an undeclared key without a word, so `?filter[status]=open` on a list that declares no `status` filter answered every row as if it were unfiltered. Upgrading: declare the filter in the feature's `listFilterQueryValidator` and the resource's searchSchema, or stop sending it.
package/locales/en.json CHANGED
@@ -10,6 +10,7 @@
10
10
  "fieldsByTypeInvalid": "fields expects an object keyed by JSON:API resource type, such as {example}.",
11
11
  "fieldsKeysInvalid": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}.",
12
12
  "fieldsKeysInvalidWithAliases": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}. Relationship aliases are invalid keys; {aliasGuidance}.",
13
+ "fieldsNotShown": "fields[{type}] may name only what this read's includes show of {type}: {shown}. It names {fields}.",
13
14
  "undeclaredKeys": "This list does not take {unknown}: an undeclared query key would be dropped, and the list would answer as if it had not been sent. It takes {known}. To filter on a field, add it to the feature's listFilterQueryValidator and the resource's searchSchema; to search, send filter[q] and give the resource searchSchema.q."
14
15
  }
15
16
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/crud-core",
3
- "version": "0.2.25",
3
+ "version": "0.2.26",
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.209",
24
- "@jskit-ai/resource-crud-core": "0.1.210",
24
+ "@jskit-ai/resource-crud-core": "0.1.211",
25
25
  "json-rest-api": "3.1.4",
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.18",
53
53
  "@jskit-ai/kernel": "0.2.18",
54
- "@jskit-ai/resource-runtime": "0.2.22"
54
+ "@jskit-ai/resource-runtime": "0.2.23"
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.25",
12
+ "@jskit-ai/crud-core": "0.2.26",
13
13
  "@jskit-ai/resource-core": "0.1.209",
14
- "@jskit-ai/resource-crud-core": "0.1.210"
14
+ "@jskit-ai/resource-crud-core": "0.1.211"
15
15
  },
16
16
  "jskit": {
17
17
  "kind": "runtime",
@@ -1,5 +1,5 @@
1
1
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
2
- import { checkIncludedFields } from "./jsonApiModule/service.js";
2
+ import { resolveIncludedTypes } from "./jsonApiModule/service.js";
3
3
 
4
4
  /**
5
5
  * The CRUD contracts an application serves, one per namespace. Each CRUD
@@ -10,6 +10,8 @@ import { checkIncludedFields } from "./jsonApiModule/service.js";
10
10
  function createCrudContracts() {
11
11
  /** @type {import("./types.js").CrudContract[]} */
12
12
  const registered = [];
13
+ /** @type {Map<import("./types.js").CrudContract, Map<string, Set<string>>>} What resolveIncludedTypes answered for each contract at boot. */
14
+ const includedTypesByContract = new Map();
13
15
  let sealed = false;
14
16
 
15
17
  /**
@@ -32,21 +34,33 @@ function createCrudContracts() {
32
34
 
33
35
  /**
34
36
  * 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.
37
+ * includes against the tables they include and keeps the types they reach below their first level (see
38
+ * resolveIncludedTypes): at boot every feature owns its tables.
36
39
  * @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} [tableResource]
37
40
  */
38
41
  function seal(tableResource) {
39
42
  if (tableResource) {
40
43
  for (const crud of registered) {
41
- checkIncludedFields(crud, tableResource);
44
+ includedTypesByContract.set(crud, resolveIncludedTypes(crud, tableResource));
42
45
  }
43
46
  }
44
47
  sealed = true;
45
48
  }
46
49
 
50
+ /**
51
+ * The JSON:API types a registered contract's includes reach below their first level, each with the fields it shows
52
+ * there: empty until the registry is sealed with the application's table resources.
53
+ * @param {import("./types.js").CrudContract} crud
54
+ * @returns {ReadonlyMap<string, ReadonlySet<string>>}
55
+ */
56
+ function includedTypes(crud) {
57
+ return includedTypesByContract.get(crud) ?? new Map();
58
+ }
59
+
47
60
  return Object.freeze({
48
61
  register,
49
- seal
62
+ seal,
63
+ includedTypes
50
64
  });
51
65
  }
52
66
 
@@ -516,7 +516,7 @@ function defineCrudFeature(feature) {
516
516
  resourceApi: Object.freeze(withRemovedProperties({ repository: exposed, crud, service }, REMOVED_RESOURCE_API, "A CRUD feature's capability"))
517
517
  };
518
518
  },
519
- actions({ resourceApi, ...required }) {
519
+ actions({ resourceApi, crudContracts, ...required }) {
520
520
  const actionDependencies = Object.freeze(Object.fromEntries(
521
521
  Object.keys(featureRequirements).map((name) => [name, required[name]])
522
522
  ));
@@ -529,7 +529,8 @@ function defineCrudFeature(feature) {
529
529
  dependencies: actionDependencies,
530
530
  scopeInputKeys: normalizedScope.inputKeys,
531
531
  realtimeAudience,
532
- definitions: actionDefinitions()
532
+ definitions: actionDefinitions(),
533
+ includedTypes: () => crudContracts.includedTypes(crud)
533
534
  });
534
535
  }
535
536
  });
@@ -7,6 +7,7 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
7
7
  import { ARCHITECTURE_ID_PATTERN } from "@jskit-ai/kernel/shared/capabilities";
8
8
  import { ACTION_INPUT_DEFAULT_MODE } from "@jskit-ai/kernel/server/actions";
9
9
  import {
10
+ createIncludedFieldsetsCheck,
10
11
  createJsonApiFieldsetsQueryValidator,
11
12
  createStandardCrudListQueryValidators,
12
13
  createStandardCrudViewQueryValidators
@@ -35,15 +36,17 @@ function resolveCrudActionChannels(permission, servedOverHttp) {
35
36
 
36
37
  function buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs) {
37
38
  const definitions = scopeInputValidator ? [scopeInputValidator] : [];
39
+ // A fieldset for a type the includes reach below their first level is checked when the action runs (see
40
+ // createIncludedFieldsetsCheck): only the tables they cross name that type, and every feature owns its tables at boot.
38
41
  if (operation === "list") {
39
42
  definitions.push(...createStandardCrudListQueryValidators({
40
43
  resource,
41
44
  listFilterQueryValidator,
42
- fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource })
45
+ fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
43
46
  }));
44
47
  } else if (operation === "view") {
45
48
  definitions.push(recordIdParamsValidator, ...createStandardCrudViewQueryValidators({
46
- fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource })
49
+ fieldsetsQueryValidator: createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true })
47
50
  }));
48
51
  } else if (operation === "create") {
49
52
  definitions.push(operationInputs.create || resource.operations.create.body);
@@ -242,6 +245,9 @@ function createCrudJsonApiActionDefinitions({
242
245
  * @param {boolean} dependencies.servedOverHttp False when the feature is internal or registers no routes.
243
246
  * @param {ReturnType<typeof createCrudJsonApiActionDefinitions>} [dependencies.definitions] What
244
247
  * createCrudJsonApiActionDefinitions built from the same options, when the caller keeps it; built here otherwise.
248
+ * @param {() => ReadonlyMap<string, ReadonlySet<string>>} [dependencies.includedTypes] The types the contract's
249
+ * includes reach below their first level, with the fields each shows there: the CRUD contracts' includedTypes once
250
+ * they are sealed. Without it, a list or view takes no fieldset for such a type.
245
251
  */
246
252
  function createCrudJsonApiActions({
247
253
  namespace,
@@ -253,9 +259,11 @@ function createCrudJsonApiActions({
253
259
  dependencies: actionDependencies,
254
260
  realtimeAudience,
255
261
  definitions: builtDefinitions,
262
+ includedTypes = () => new Map(),
256
263
  ...definitionOptions
257
264
  }) {
258
265
  const definitions = builtDefinitions ?? createCrudJsonApiActionDefinitions({ namespace, resource, ...definitionOptions });
266
+ const checkIncludedFieldsets = createIncludedFieldsetsCheck(resource);
259
267
  const mutationEvent = (operation, entityId) => buildCrudRecordChangedEvent({
260
268
  namespace,
261
269
  operation,
@@ -370,13 +378,19 @@ function createCrudJsonApiActions({
370
378
  operation: "list",
371
379
  kind: "query",
372
380
  events: [],
373
- execute: (input, context) => executeOperation("list", input, context, listDocuments)
381
+ execute: async (input, context) => {
382
+ checkIncludedFieldsets(input.fields, includedTypes());
383
+ return executeOperation("list", input, context, listDocuments);
384
+ }
374
385
  },
375
386
  {
376
387
  operation: "view",
377
388
  kind: "query",
378
389
  events: [],
379
- execute: (input, context) => executeOperation("view", input, context, viewDocument)
390
+ execute: async (input, context) => {
391
+ checkIncludedFieldsets(input.fields, includedTypes());
392
+ return executeOperation("view", input, context, viewDocument);
393
+ }
380
394
  },
381
395
  {
382
396
  operation: "create",
@@ -104,17 +104,23 @@ function linksOf(resource) {
104
104
  }
105
105
 
106
106
  /**
107
+ * Checks each level of a contract's includes against the table resource it reaches, and answers the JSON:API types
108
+ * they reach below their first level, each with the fields it shows there (its listed fields and links, by every
109
+ * path that reaches it). Only those tables name such a type, so the CRUD actions check a sparse fieldset for one
110
+ * against this answer (see createIncludedFieldsetsCheck).
107
111
  * Refuses a field an include lists that is a link of the included record: a belongs-to field, by its key
108
112
  * (`locationId`) or its relationship (`location`), or a collection relation. A JSON:API document answers a link
109
113
  * under the record's relationships, never among its attributes, so the field would never show and the record would
110
114
  * read as if it had no link. The list names a link as `{ location: [] }`, which answers the linked record's id, with
111
115
  * the fields to show of that record inside it. Each level is checked against its own table resource; a level whose
112
- * resource no feature owns is left to the request.
116
+ * resource no feature owns is left to the request, and the types below it are not answered.
113
117
  * @param {import("../types.js").CrudContract} crud
114
118
  * @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} tableResource The resource runtime's
115
119
  * owned table resources, by name.
120
+ * @returns {Map<string, Set<string>>}
116
121
  */
117
- function checkIncludedFields(crud, tableResource) {
122
+ function resolveIncludedTypes(crud, tableResource) {
123
+ const reached = new Map();
118
124
  const check = (label, resourceName, { attributes, relationships }) => {
119
125
  const resource = tableResource(resourceName);
120
126
  if (!resource) {
@@ -136,6 +142,11 @@ function checkIncludedFields(crud, tableResource) {
136
142
  for (const [relationshipName, nested] of Object.entries(relationships)) {
137
143
  const link = links.get(relationshipName);
138
144
  if (link?.target) {
145
+ const shown = reached.get(link.target) ?? new Set();
146
+ reached.set(link.target, shown);
147
+ for (const name of [...nested.attributes, ...Object.keys(nested.relationships)]) {
148
+ shown.add(name);
149
+ }
139
150
  check(`${label}.${relationshipName}`, link.target, nested);
140
151
  }
141
152
  }
@@ -143,6 +154,7 @@ function checkIncludedFields(crud, tableResource) {
143
154
  for (const { attributeKey, relationshipType, include } of contractShape(crud).relationships) {
144
155
  check(`${attributeKey}.includeFields`, relationshipType, include);
145
156
  }
157
+ return reached;
146
158
  }
147
159
 
148
160
  // What each CRUD contract shows, by contract. defineCrudContract deep-freezes a contract, so what it shows is worked
@@ -323,4 +335,4 @@ function createCrudService({ repository, crud }) {
323
335
  });
324
336
  }
325
337
 
326
- export { checkIncludedFields, createCrudService };
338
+ export { createCrudService, resolveIncludedTypes };
@@ -19,8 +19,6 @@ import {
19
19
  CRUD_LIST_FILTER_PRESENCE_MISSING
20
20
  } from "@jskit-ai/resource-crud-core/shared/crudListFilters";
21
21
  import {
22
- recordIdTransportSchema,
23
- cloneTransportSchema,
24
22
  addDaysToDateFilterValue,
25
23
  applyDefaultFilterQuery
26
24
  } from "./listFilterTypes.js";
@@ -81,8 +79,9 @@ function buildJsonRestFilterItemSchema(filter = {}) {
81
79
  };
82
80
  }
83
81
 
82
+ // A json-rest-schema field definition, never JSON Schema: json-rest-schema refuses an `anyOf` item.
84
83
  if (filter.type === CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY) {
85
- return cloneTransportSchema(recordIdTransportSchema);
84
+ return { type: "id" };
86
85
  }
87
86
 
88
87
  return {};
@@ -231,13 +230,19 @@ function createCrudListFilterJsonRestSearchSchema(runtime = {}, { columns = {},
231
230
  return Object.freeze(schema);
232
231
  }
233
232
 
233
+ // The instant a filter's day starts, in the form json-rest-api's dateTime search keys take (ISO 8601 with its zone,
234
+ // which refuses "2026-03-01 00:00:00"): midnight UTC, the zone a dateTime is stored in.
235
+ function dateFilterDayStart(date) {
236
+ return `${date}T00:00:00.000Z`;
237
+ }
238
+
234
239
  function addJsonRestDateFilterValues(target = {}, filter = {}, value = "") {
235
240
  const nextDate = addDaysToDateFilterValue(value, 1);
236
241
  if (value) {
237
- target[renderInternalJsonRestFilterKey(filter, "from")] = `${value} 00:00:00`;
242
+ target[renderInternalJsonRestFilterKey(filter, "from")] = dateFilterDayStart(value);
238
243
  }
239
244
  if (nextDate) {
240
- target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = `${nextDate} 00:00:00`;
245
+ target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = dateFilterDayStart(nextDate);
241
246
  }
242
247
  }
243
248
 
@@ -249,12 +254,12 @@ function addJsonRestFilterValue(target = {}, filter = {}, value) {
249
254
 
250
255
  if (filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
251
256
  if (value?.from) {
252
- target[renderInternalJsonRestFilterKey(filter, "from")] = `${value.from} 00:00:00`;
257
+ target[renderInternalJsonRestFilterKey(filter, "from")] = dateFilterDayStart(value.from);
253
258
  }
254
259
  if (value?.to) {
255
260
  const nextDate = addDaysToDateFilterValue(value.to, 1);
256
261
  if (nextDate) {
257
- target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = `${nextDate} 00:00:00`;
262
+ target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = dateFilterDayStart(nextDate);
258
263
  }
259
264
  }
260
265
  return;
@@ -96,7 +96,9 @@ function cloneTransportSchema(value) {
96
96
  );
97
97
  }
98
98
 
99
- function buildSingleOrMultiTransportSchema(itemSchema) {
99
+ // A filter that takes several values takes them as the client sends them, `filter[x]=1&filter[x]=2`, or as one
100
+ // comma-separated value, `filter[x]=1,2`, the form JSON:API gives a list (and the one the parse reads either as).
101
+ function buildSingleOrMultiTransportSchema(itemSchema, itemPattern = "") {
100
102
  return {
101
103
  anyOf: [
102
104
  cloneTransportSchema(itemSchema),
@@ -104,11 +106,17 @@ function buildSingleOrMultiTransportSchema(itemSchema) {
104
106
  type: "array",
105
107
  items: cloneTransportSchema(itemSchema),
106
108
  minItems: 1
107
- }
109
+ },
110
+ ...(itemPattern ? [{ type: "string", pattern: `^${itemPattern}(?:,${itemPattern})+$` }] : [])
108
111
  ]
109
112
  };
110
113
  }
111
114
 
115
+ function allowedValuesPattern(allowedValues) {
116
+ const alternatives = allowedValues.map((value) => String(value).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"));
117
+ return alternatives.length > 0 ? `(?:${alternatives.join("|")})` : "";
118
+ }
119
+
112
120
  function addDaysToDateFilterValue(value = "", days = 0) {
113
121
  const normalizedValue = parseCrudListFilterQueryValue(
114
122
  { type: CRUD_LIST_FILTER_TYPE_DATE },
@@ -176,14 +184,11 @@ const FILTER_TYPE_SERVER_HANDLERS = Object.freeze({
176
184
  }),
177
185
  [CRUD_LIST_FILTER_TYPE_ENUM_MANY]: Object.freeze({
178
186
  buildTransportSchema({ discardInvalidValues, allowedValues }) {
179
- return buildSingleOrMultiTransportSchema(
180
- discardInvalidValues
181
- ? looseTextTransportSchema
182
- : {
183
- type: "string",
184
- enum: allowedValues
185
- }
186
- );
187
+ if (discardInvalidValues) {
188
+ return buildSingleOrMultiTransportSchema(looseTextTransportSchema);
189
+ }
190
+ const allowedValueSchema = { type: "string", enum: allowedValues };
191
+ return buildSingleOrMultiTransportSchema(allowedValueSchema, allowedValuesPattern(allowedValues));
187
192
  },
188
193
  applyQuery: applyInFilterQuery
189
194
  }),
@@ -197,11 +202,9 @@ const FILTER_TYPE_SERVER_HANDLERS = Object.freeze({
197
202
  }),
198
203
  [CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY]: Object.freeze({
199
204
  buildTransportSchema({ discardInvalidValues }) {
200
- return buildSingleOrMultiTransportSchema(
201
- discardInvalidValues
202
- ? looseStringOrNumberTransportSchema
203
- : recordIdTransportSchema
204
- );
205
+ return discardInvalidValues
206
+ ? buildSingleOrMultiTransportSchema(looseStringOrNumberTransportSchema)
207
+ : buildSingleOrMultiTransportSchema(recordIdTransportSchema, RECORD_ID_PATTERN.slice(1, -1));
205
208
  },
206
209
  applyQuery: applyInFilterQuery
207
210
  }),
@@ -417,8 +420,6 @@ function applyDefaultFilterQuery(queryBuilder, filter = {}, value, column = "")
417
420
  }
418
421
 
419
422
  export {
420
- recordIdTransportSchema,
421
- cloneTransportSchema,
422
423
  addDaysToDateFilterValue,
423
424
  buildCrudListFilterQueryField,
424
425
  createCrudListFilterQuerySchema,
@@ -2,7 +2,9 @@ import { createSchema } from "json-rest-schema";
2
2
  import {
3
3
  cursorPaginationQueryValidator
4
4
  } from "@jskit-ai/kernel/shared/validators";
5
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
5
+ import { createValidationError } from "@jskit-ai/kernel/server/runtime/errors";
6
+ import { normalizeJsonApiFieldList } from "@jskit-ai/kernel/shared/support/jsonApiFieldsets";
7
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
6
8
  import { resolveCrudParentFilterKeys } from "@jskit-ai/resource-crud-core/shared/crudLookup";
7
9
  import {
8
10
  CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY,
@@ -84,22 +86,18 @@ const jsonApiFieldsetsQueryValidator = Object.freeze({
84
86
  mode: "patch"
85
87
  });
86
88
 
87
- function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
88
- const contract = resolveJsonApiFieldsetContract(resource);
89
- if (!contract.primaryType || contract.resourceTypes.length < 1) {
90
- return jsonApiFieldsetsQueryValidator;
91
- }
92
-
93
- const firstRelationship = contract.relationshipEntries[0] || null;
94
- const example = firstRelationship
95
- ? `{"${contract.primaryType}":["${firstRelationship.attributeKey}"],` +
96
- `"${firstRelationship.relationshipType}":["${firstRelationship.labelKey || "id"}"]}`
97
- : `{"${contract.primaryType}":["id"]}`;
98
- const allowedTypes = contract.resourceTypes.map((entry) => `"${entry}"`).join(", ");
89
+ /**
90
+ * The coded refusal of a fieldset key that is none of the resource types a read takes, naming the resource type to
91
+ * use for each of the contract's relationship aliases.
92
+ * @param {ReturnType<typeof resolveJsonApiFieldsetContract>} contract
93
+ * @param {readonly string[]} resourceTypes
94
+ */
95
+ function fieldsetKeysRefusal(contract, resourceTypes) {
96
+ const allowedTypes = resourceTypes.map((entry) => `"${entry}"`).join(", ");
99
97
  const aliasGuidance = contract.aliasMappings
100
98
  .map((entry) => `use "${entry.resourceType}" instead of "${entry.alias}"`)
101
99
  .join("; ");
102
- const additionalPropertiesMessage = aliasGuidance
100
+ return aliasGuidance
103
101
  ? {
104
102
  code: "crud.query.fieldsKeysInvalidWithAliases",
105
103
  message: `fields keys must be JSON:API resource types. Allowed keys: ${allowedTypes}.` +
@@ -111,6 +109,30 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
111
109
  message: `fields keys must be JSON:API resource types. Allowed keys: ${allowedTypes}.`,
112
110
  params: { allowedTypes }
113
111
  };
112
+ }
113
+
114
+ /**
115
+ * The sparse fieldsets a CRUD contract's reads take, keyed by JSON:API resource type: its own type, with the fields
116
+ * its view output names, and each type it links to. A type its includes reach below their first level
117
+ * (`includeFields: ["name", { breed: ["name"] }]` reaches the breed's type) is named only by the tables an include
118
+ * crosses, so this schema cannot name it. Such a key is refused, like any other unknown key, unless
119
+ * `deferIncludedTypes` lets it through to createIncludedFieldsetsCheck, which the CRUD actions run once boot has
120
+ * resolved those types.
121
+ * @param {object} [options]
122
+ * @param {object} [options.resource] The CRUD contract.
123
+ * @param {boolean} [options.deferIncludedTypes]
124
+ */
125
+ function createJsonApiFieldsetsQueryValidator({ resource = {}, deferIncludedTypes = false } = {}) {
126
+ const contract = resolveJsonApiFieldsetContract(resource);
127
+ if (!contract.primaryType || contract.resourceTypes.length < 1) {
128
+ return jsonApiFieldsetsQueryValidator;
129
+ }
130
+
131
+ const firstRelationship = contract.relationshipEntries[0] || null;
132
+ const example = firstRelationship
133
+ ? `{"${contract.primaryType}":["${firstRelationship.attributeKey}"],` +
134
+ `"${firstRelationship.relationshipType}":["${firstRelationship.labelKey || "id"}"]}`
135
+ : `{"${contract.primaryType}":["id"]}`;
114
136
  const fieldsetSchema = createSchema(
115
137
  Object.fromEntries(
116
138
  contract.resourceTypes.map((resourceType) => [
@@ -121,6 +143,7 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
121
143
  ])
122
144
  )
123
145
  );
146
+ const reachesNestedTypes = contract.relationshipEntries.some(({ include }) => Object.keys(include.relationships).length > 0);
124
147
 
125
148
  return Object.freeze({
126
149
  schema: createSchema({
@@ -128,13 +151,14 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
128
151
  type: "object",
129
152
  required: false,
130
153
  schema: fieldsetSchema,
154
+ ...(deferIncludedTypes && reachesNestedTypes ? { additionalProperties: true } : {}),
131
155
  messages: {
132
156
  default: {
133
157
  code: "crud.query.fieldsByTypeInvalid",
134
158
  message: `fields expects an object keyed by JSON:API resource type, such as ${example}.`,
135
159
  params: { example }
136
160
  },
137
- additionalProperties: additionalPropertiesMessage
161
+ additionalProperties: fieldsetKeysRefusal(contract, contract.resourceTypes)
138
162
  }
139
163
  }
140
164
  }),
@@ -142,6 +166,59 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
142
166
  });
143
167
  }
144
168
 
169
+ /**
170
+ * The check of the sparse fieldsets createJsonApiFieldsetsQueryValidator deferred: keys for none of the resource types
171
+ * its schema names. A type the resource's includes reach below their first level takes only the fields they show of
172
+ * it there; any other key is refused as the validator refuses one. So
173
+ * `include=customer,customer.region&fields[regions]=name` narrows the included regions when the include lists
174
+ * `{ region: ["name", ...] }`, and the includes still decide what an included record can show. The check throws a
175
+ * validation error naming each refused fieldset.
176
+ * @param {object} resource The CRUD contract.
177
+ * @returns {(fields: unknown, includedTypes: ReadonlyMap<string, ReadonlySet<string>>) => void} Takes the validated
178
+ * input's `fields` and the types the includes reach below their first level, each with the fields it shows there,
179
+ * as the CRUD contracts resolved them at boot (`includedTypes`).
180
+ */
181
+ function createIncludedFieldsetsCheck(resource) {
182
+ // Worked out at the first read that names fieldsets, so composing a feature costs nothing more.
183
+ let contract = null;
184
+ let namedTypes = null;
185
+
186
+ return function checkIncludedFieldsets(fields, includedTypes) {
187
+ if (!isRecord(fields)) {
188
+ return;
189
+ }
190
+ contract ??= resolveJsonApiFieldsetContract(resource);
191
+ namedTypes ??= new Set(contract.resourceTypes);
192
+ if (namedTypes.size < 1 || !contract.primaryType) {
193
+ return;
194
+ }
195
+ const fieldErrors = {};
196
+ for (const [type, value] of Object.entries(fields)) {
197
+ if (namedTypes.has(type)) {
198
+ continue;
199
+ }
200
+ const shown = includedTypes.get(type);
201
+ if (!shown) {
202
+ fieldErrors[`fields.${type}`] = fieldsetKeysRefusal(contract, [...new Set([...namedTypes, ...includedTypes.keys()])]);
203
+ continue;
204
+ }
205
+ const unshown = normalizeJsonApiFieldList(value).filter((name) => !shown.has(name));
206
+ if (unshown.length > 0) {
207
+ const params = { type, shown: [...shown].join(", ") || "none", fields: unshown.join(", ") };
208
+ fieldErrors[`fields.${type}`] = {
209
+ code: "crud.query.fieldsNotShown",
210
+ message: `fields[${params.type}] may name only what this read's includes show of ${params.type}: ` +
211
+ `${params.shown}. It names ${params.fields}.`,
212
+ params
213
+ };
214
+ }
215
+ }
216
+ if (Object.keys(fieldErrors).length > 0) {
217
+ throw createValidationError(fieldErrors);
218
+ }
219
+ };
220
+ }
221
+
145
222
  function resolveCrudListUsesOrderedCursor(list = {}) {
146
223
  const entries = Array.isArray(list.orderBy)
147
224
  ? list.orderBy
@@ -250,6 +327,7 @@ function createStandardCrudViewQueryValidators({
250
327
 
251
328
  export {
252
329
  createCrudCursorPaginationQueryValidator,
330
+ createIncludedFieldsetsCheck,
253
331
  createJsonApiFieldsetsQueryValidator,
254
332
  listSearchQueryValidator,
255
333
  listRecordIdsQueryValidator,
@@ -0,0 +1,138 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
5
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
6
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
7
+ import { createRouter } from "../../kernel/server/http/lib/router.js";
8
+ import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
9
+ import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
10
+ import { CrudContractsProvider } from "../src/server/crudContracts.js";
11
+ import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
12
+ import { createCrudListFilterContract } from "../src/server/listFilters.js";
13
+
14
+ const orders = defineTableResource({
15
+ name: "orders",
16
+ tableName: "orders",
17
+ ownership: "public",
18
+ schema: {
19
+ reference: { type: "string", required: true },
20
+ arrivedAt: { type: "dateTime", storage: { column: "arrived_at" } },
21
+ total: { type: "number" },
22
+ customerId: { type: "id", nullable: true, storage: { column: "customer_id" } }
23
+ }
24
+ });
25
+
26
+ // Each arrives at noon UTC, well inside its day in any time zone.
27
+ const ORDERS = Object.freeze([
28
+ { reference: "A", arrivedAt: "2026-02-27T12:00:00.000Z", total: 5, customerId: "1" },
29
+ { reference: "B", arrivedAt: "2026-03-02T12:00:00.000Z", total: 10, customerId: "2" },
30
+ { reference: "C", arrivedAt: "2026-03-15T12:00:00.000Z", total: 20, customerId: "3" },
31
+ { reference: "D", arrivedAt: "2026-03-30T12:00:00.000Z", total: 30, customerId: "1" },
32
+ { reference: "E", arrivedAt: "2026-04-03T12:00:00.000Z", total: 40, customerId: null }
33
+ ]);
34
+
35
+ /**
36
+ * An orders list served as an application serves one with structured filters: the filter contract's validator at the
37
+ * route and action, its search schema on the orders table, and its toJsonRestQuery in the service's list, over Fastify.
38
+ * @param {import("node:test").TestContext} t
39
+ * @param {object} definitions The list filters.
40
+ * @param {Record<string, string>} columns Each filter's field, when it is not the filter's own key.
41
+ */
42
+ async function ordersApp(t, definitions, columns) {
43
+ const knex = await createPackageTestKnex(t, { environment: process.env });
44
+ const filters = createCrudListFilterContract(definitions, { columns });
45
+ const router = createRouter();
46
+ const started = await startTestFeatures({
47
+ knex,
48
+ features: [
49
+ CrudContractsProvider,
50
+ defineCrudFeature({
51
+ crud: defineCrudContract(orders, {
52
+ namespace: "orders",
53
+ apiAccess: "public",
54
+ operations: ["list", "view"],
55
+ fields: { reference: { output: "required" } }
56
+ }),
57
+ operations: ["list"],
58
+ surface: "app",
59
+ owns: [{ resource: orders, searchSchema: filters.jsonRestSearchSchema }],
60
+ listFilterQueryValidator: filters.queryValidator,
61
+ decorateService: ({ service }) => ({ ...service, list: (query, options) => service.list(filters.toJsonRestQuery(query), options) })
62
+ })
63
+ ],
64
+ requires: { actions: "runtime.actions", orders: "crud.orders" },
65
+ inputs: { "runtime.http": { router } },
66
+ createTables: true
67
+ });
68
+ t.after(started.stop);
69
+ const context = started.resources.declareSystemScope("test.orders", "The test seeds every order.")("seed the orders");
70
+ for (const order of ORDERS) {
71
+ await started.capabilities.orders.repository.create(order, { context, returning: "none" });
72
+ }
73
+ const app = Fastify();
74
+ t.after(() => app.close());
75
+ registerApiErrorHandler(app);
76
+ registerRoutes(app, { routes: router.list(), actions: started.capabilities.actions });
77
+ return async function list(query) {
78
+ const response = await app.inject({ method: "GET", url: `/api/orders?${query}` });
79
+ return {
80
+ statusCode: response.statusCode,
81
+ body: response.body,
82
+ references: response.statusCode === 200 ? response.json().data.map((record) => record.attributes.reference).sort() : null
83
+ };
84
+ };
85
+ }
86
+
87
+ test("a date range or number range list filter sent over HTTP answers exactly the rows inside it", async (t) => {
88
+ // arrival and arrivedOn are mapped to the arrivedAt field; total filters its own field.
89
+ const list = await ordersApp(t, {
90
+ arrival: { type: "dateRange", label: "Arrival" },
91
+ arrivedOn: { type: "date", label: "Arrived on" },
92
+ total: { type: "numberRange", label: "Total" }
93
+ }, { arrival: "arrivedAt", arrivedOn: "arrivedAt" });
94
+
95
+ for (const [query, references] of [
96
+ ["filter%5Barrival%5D=2026-03-01..2026-03-31", ["B", "C", "D"]],
97
+ ["filter%5Barrival%5D=2026-03-10..", ["C", "D", "E"]],
98
+ ["filter%5Barrival%5D=..2026-03-10", ["A", "B"]],
99
+ ["filter%5Barrival%5D=2026-03-15", ["C"]],
100
+ ["filter%5BarrivedOn%5D=2026-03-30", ["D"]],
101
+ ["filter%5Btotal%5D=15..35", ["C", "D"]],
102
+ ["filter%5Btotal%5D=..10", ["A", "B"]],
103
+ ["filter%5Barrival%5D=2026-03-01..2026-03-31&filter%5Btotal%5D=15..", ["C", "D"]],
104
+ ["page%5Blimit%5D=20", ["A", "B", "C", "D", "E"]]
105
+ ]) {
106
+ const response = await list(query);
107
+ // Before, a range answered 400: the list action read the route's parsed { from, to } again and refused it. Past
108
+ // that, the service's toJsonRestQuery dropped it, and a date bound "2026-03-01 00:00:00" was refused with 422.
109
+ assert.equal(response.statusCode, 200, `${query}: ${response.body}`);
110
+ assert.deepEqual(response.references, references, query);
111
+ }
112
+
113
+ for (const query of ["filter%5Barrival%5D=March", "filter%5Barrival%5D=2026-03-01..soon", "filter%5Btotal%5D=lots", "filter%5Btotal%5D=1..x"]) {
114
+ assert.equal((await list(query)).statusCode, 400, query);
115
+ }
116
+ });
117
+
118
+ test("a recordIdMany list filter builds its search schema and answers the rows of the ids sent over HTTP", async (t) => {
119
+ // Before, json-rest-schema refused the filter's search schema entry, whose items were a JSON Schema anyOf, so the
120
+ // orders feature did not start.
121
+ const list = await ordersApp(t, { customer: { type: "recordIdMany", label: "Customer" } }, { customer: "customerId" });
122
+
123
+ for (const [query, references] of [
124
+ ["filter%5Bcustomer%5D=1&filter%5Bcustomer%5D=2", ["A", "B", "D"]],
125
+ ["filter%5Bcustomer%5D=1,2", ["A", "B", "D"]],
126
+ ["filter%5Bcustomer%5D=1&filter%5Bcustomer%5D=3", ["A", "C", "D"]],
127
+ ["filter%5Bcustomer%5D=3", ["C"]],
128
+ ["filter%5Bcustomer%5D=9", []]
129
+ ]) {
130
+ const response = await list(query);
131
+ assert.equal(response.statusCode, 200, `${query}: ${response.body}`);
132
+ assert.deepEqual(response.references, references, query);
133
+ }
134
+
135
+ for (const query of ["filter%5Bcustomer%5D=abc", "filter%5Bcustomer%5D=1,,2", "filter%5Bcustomer%5D=0"]) {
136
+ assert.equal((await list(query)).statusCode, 400, query);
137
+ }
138
+ });
@@ -415,6 +415,12 @@ test("createCrudListFilters reject validator keeps strict filter schemas", () =>
415
415
  );
416
416
  assert.deepEqual(transportSchema.properties.status.anyOf[1].items.enum, ["active", "archived"]);
417
417
  assert.equal(transportSchema.properties.supplierContactId.anyOf[1].items.anyOf[0].pattern, "^[1-9][0-9]*$");
418
+ // Or one comma-separated value, the form JSON:API gives a list, of valid values only.
419
+ const commaList = (property) => new RegExp(transportSchema.properties[property].anyOf[2].pattern, "u");
420
+ assert.equal(commaList("status").test("active,archived"), true);
421
+ assert.equal(commaList("status").test("active,unexpected"), false);
422
+ assert.equal(commaList("supplierContactId").test("7,4"), true);
423
+ assert.equal(commaList("supplierContactId").test("7,,4"), false);
418
424
  assert.equal(
419
425
  transportSchema.properties.weight.anyOf[0].pattern,
420
426
  "^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?(?:\\.\\.(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)?)?|\\.\\.[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)$"
@@ -596,6 +602,10 @@ test("createCrudListFilterContract builds route validators and JSON REST search
596
602
  assert.equal(contract.jsonRestSearchSchema.status.filterOperator, "in");
597
603
  assert.equal(contract.jsonRestSearchSchema.status.actualField, "status");
598
604
  assert.equal(contract.jsonRestSearchSchema.supplierContactId.filterOperator, "in");
605
+ // json-rest-api validates a search value with json-rest-schema, which takes an item's field definition, not JSON Schema.
606
+ assert.deepEqual(contract.jsonRestSearchSchema.supplierContactId.items, { type: "id" });
607
+ assert.deepEqual(createSchema({ supplierContactId: contract.jsonRestSearchSchema.supplierContactId })
608
+ .patch({ supplierContactId: ["7", "4"] }), { validatedObject: { supplierContactId: [7, 4] }, errors: {} });
599
609
  assert.equal(contract.jsonRestSearchSchema.__jskit_arrivalDate_from.filterOperator, ">=");
600
610
  assert.equal(contract.jsonRestSearchSchema.__jskit_arrivalDate_toExclusive.filterOperator, "<");
601
611
  assert.equal(contract.jsonRestSearchSchema.__jskit_weight_min.filterOperator, ">=");
@@ -614,8 +624,15 @@ test("createCrudListFilterContract builds route validators and JSON REST search
614
624
  status: ["active", "archived"],
615
625
  supplierContactId: ["7", "4"],
616
626
  locationAssignment: "missing",
617
- __jskit_arrivalDate_from: "2026-04-01 00:00:00",
618
- __jskit_arrivalDate_toExclusive: "2026-05-01 00:00:00",
627
+ __jskit_arrivalDate_from: "2026-04-01T00:00:00.000Z",
628
+ __jskit_arrivalDate_toExclusive: "2026-05-01T00:00:00.000Z",
629
+ __jskit_weight_min: 12.5
630
+ });
631
+ // Over HTTP the service's list receives the query the route and the list action already parsed: it maps the same.
632
+ const { validatedObject: parsedQuery } = contract.queryValidator.schema.patch({ arrivalDate: "2026-04-01..2026-04-30", weight: "12.5.." });
633
+ assert.deepEqual(contract.toJsonRestQuery(contract.queryValidator.schema.patch(parsedQuery).validatedObject), {
634
+ __jskit_arrivalDate_from: "2026-04-01T00:00:00.000Z",
635
+ __jskit_arrivalDate_toExclusive: "2026-05-01T00:00:00.000Z",
619
636
  __jskit_weight_min: 12.5
620
637
  });
621
638
 
@@ -12,6 +12,7 @@ import {
12
12
  lookupIncludeQueryValidator,
13
13
  createCrudCursorPaginationQueryValidator,
14
14
  createJsonApiFieldsetsQueryValidator,
15
+ createIncludedFieldsetsCheck,
15
16
  createCrudParentFilterQueryValidator,
16
17
  createStandardCrudListQueryValidators,
17
18
  createStandardCrudViewQueryValidators
@@ -160,6 +161,68 @@ test("resource-aware sparse fieldsets enumerate JSON:API types and reject relati
160
161
  );
161
162
  });
162
163
 
164
+ test("a fieldset for a type the includes reach below their first level waits for the types boot resolves, then names only fields shown there", () => {
165
+ // orders -> customer (customers) -> region (regions): only the customers table names the region's type.
166
+ const resource = createCrudResource({
167
+ namespace: "orders",
168
+ viewFields: {
169
+ reference: { type: "string" },
170
+ customerId: { type: "integer", belongsTo: "customers", as: "customer", includeFields: ["name", { region: ["name", "code"] }] }
171
+ }
172
+ });
173
+ const refusal = (run) => {
174
+ try {
175
+ run();
176
+ } catch (error) {
177
+ return error;
178
+ }
179
+ return assert.fail("expected a refusal");
180
+ };
181
+
182
+ // Without deferIncludedTypes the schema refuses the key, as it refuses any type it does not name.
183
+ const strict = refusal(() => validateSchemaPayload(createJsonApiFieldsetsQueryValidator({ resource }), {
184
+ fields: { regions: ["name"] }
185
+ }, { phase: "input" }));
186
+ assert.equal(strict.fieldErrorCodes?.["fields.regions"]?.code, "crud.query.fieldsKeysInvalidWithAliases");
187
+
188
+ // Deferred, the schema lets the keys it cannot name through, and still checks those it names.
189
+ const deferred = createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true });
190
+ assert.deepEqual(validateSchemaPayload(deferred, {
191
+ fields: { orders: ["reference"], regions: ["name"], tags: ["label"] }
192
+ }, { phase: "input" }), { fields: { orders: ["reference"], regions: ["name"], tags: ["label"] } });
193
+ assert.ok(refusal(() => validateSchemaPayload(deferred, { fields: { orders: ["secret"] } }, { phase: "input" })).fieldErrors);
194
+ // A contract whose includes stop at their first level has nothing to defer.
195
+ const flat = createCrudResource({ namespace: "orders", viewFields: { customerId: { type: "integer", belongsTo: "customers", as: "customer" } } });
196
+ assert.equal(
197
+ refusal(() => validateSchemaPayload(createJsonApiFieldsetsQueryValidator({ resource: flat, deferIncludedTypes: true }), {
198
+ fields: { regions: ["name"] }
199
+ }, { phase: "input" })).fieldErrorCodes?.["fields.regions"]?.code,
200
+ "crud.query.fieldsKeysInvalidWithAliases"
201
+ );
202
+
203
+ // The check takes the region's fields the include shows, and refuses any other field and any type it does not reach.
204
+ const check = createIncludedFieldsetsCheck(resource);
205
+ const includedTypes = new Map([["regions", new Set(["name", "code"])]]);
206
+ check({ orders: ["reference"], customers: ["name"], regions: ["name", "code"] }, includedTypes);
207
+ check(undefined, includedTypes);
208
+ const hidden = refusal(() => check({ regions: ["name", "secret"] }, includedTypes));
209
+ assert.equal(hidden.status, 400);
210
+ assert.deepEqual(hidden.details.fieldErrorCodes["fields.regions"], {
211
+ code: "crud.query.fieldsNotShown",
212
+ params: { type: "regions", shown: "name, code", fields: "secret" }
213
+ });
214
+ assert.equal(
215
+ hidden.details.fieldErrors["fields.regions"],
216
+ "fields[regions] may name only what this read's includes show of regions: name, code. It names secret."
217
+ );
218
+ const unrelated = refusal(() => check({ tags: ["label"] }, includedTypes));
219
+ assert.equal(unrelated.details.fieldErrorCodes["fields.tags"].code, "crud.query.fieldsKeysInvalidWithAliases");
220
+ assert.match(unrelated.details.fieldErrors["fields.tags"], /Allowed keys: "orders", "customers", "regions"\./u);
221
+ // Before boot resolves the types (or with no table resources), no such type is reached.
222
+ assert.equal(refusal(() => check({ regions: ["name"] }, new Map())).details.fieldErrorCodes["fields.regions"].code,
223
+ "crud.query.fieldsKeysInvalidWithAliases");
224
+ });
225
+
163
226
  test("createCrudCursorPaginationQueryValidator keeps numeric cursor validation for unordered lists", () => {
164
227
  const validator = createCrudCursorPaginationQueryValidator({});
165
228
 
@@ -86,9 +86,9 @@ test("a CRUD list refuses a query key it does not take, which Fastify's validati
86
86
  test("a CRUD list takes filter[id], one record id or several, which a lookup sends to label the values it holds", async (t) => {
87
87
  const { app, listed } = await listApp(t);
88
88
 
89
- for (const url of ["/api/notes?filter%5Bid%5D=7", "/api/notes?filter%5Bid%5D=7&filter%5Bid%5D=12&page%5Blimit%5D=20"]) {
89
+ for (const url of ["/api/notes?filter%5Bid%5D=7", "/api/notes?filter%5Bid%5D=7&filter%5Bid%5D=12&page%5Blimit%5D=20", "/api/notes?filter%5Bid%5D=7,12"]) {
90
90
  const response = await app.inject({ method: "GET", url });
91
91
  assert.equal(response.statusCode, 200, `${url}: ${response.body}`);
92
92
  }
93
- assert.deepEqual(listed.map((input) => input.id), [["7"], ["7", "12"]]);
93
+ assert.deepEqual(listed.map((input) => input.id), [["7"], ["7", "12"], ["7", "12"]]);
94
94
  });
@@ -0,0 +1,157 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { catalogMessage, formatMessage, messageKeyForCode, mergeCatalogs } from "@jskit-ai/kernel/shared/i18n";
5
+ import kernelEnglish from "@jskit-ai/kernel/locales/en.json" with { type: "json" };
6
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
7
+ import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
8
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
9
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
10
+ import { createRouter } from "../../kernel/server/http/lib/router.js";
11
+ import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
12
+ import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
13
+ import crudEnglish from "../locales/en.json" with { type: "json" };
14
+ import { CrudContractsProvider } from "../src/server/crudContracts.js";
15
+ import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
16
+
17
+ const english = mergeCatalogs(kernelEnglish, crudEnglish);
18
+ const API = Object.freeze({ channel: "api", surface: "home" });
19
+ const INCLUDE = "customer,customer.region";
20
+
21
+ // orders -> customer (customers) -> region (regions), two levels deep; no include reaches tags.
22
+ const regions = defineTableResource({
23
+ name: "regions",
24
+ tableName: "regions",
25
+ ownership: "public",
26
+ schema: {
27
+ name: { type: "string", required: true },
28
+ code: { type: "string", nullable: true },
29
+ secret: { type: "string", nullable: true }
30
+ }
31
+ });
32
+ const customers = defineTableResource({
33
+ name: "customers",
34
+ tableName: "customers",
35
+ ownership: "public",
36
+ schema: {
37
+ name: { type: "string", required: true },
38
+ regionId: { type: "id", nullable: true, lookup: "regions", storage: { column: "region_id" } }
39
+ }
40
+ });
41
+ const tags = defineTableResource({
42
+ name: "tags",
43
+ tableName: "tags",
44
+ ownership: "public",
45
+ schema: { label: { type: "string", required: true } }
46
+ });
47
+ const orders = defineTableResource({
48
+ name: "orders",
49
+ tableName: "orders",
50
+ ownership: "public",
51
+ schema: {
52
+ reference: { type: "string", required: true },
53
+ customerId: { type: "id", nullable: true, lookup: "customers", storage: { column: "customer_id" } }
54
+ }
55
+ });
56
+ const ordersContract = defineCrudContract(orders, {
57
+ namespace: "orders",
58
+ apiAccess: "public",
59
+ operations: ["list", "view"],
60
+ fields: {
61
+ reference: { output: "required" },
62
+ customerId: { output: { required: false, includeFields: ["name", { region: ["name", "code"] }] } }
63
+ }
64
+ });
65
+
66
+ // The orders feature serves the orders; another feature owns the tables its include reaches.
67
+ async function startOrders(t) {
68
+ const knex = await createPackageTestKnex(t, { environment: process.env });
69
+ const router = createRouter();
70
+ const started = await startTestFeatures({
71
+ knex,
72
+ features: [
73
+ CrudContractsProvider,
74
+ defineFeature({ id: "test.customers", owns: [customers, regions, tags], setup: () => ({}) }),
75
+ defineCrudFeature({ crud: ordersContract, surface: "home" })
76
+ ],
77
+ requires: { actions: "runtime.actions" },
78
+ inputs: { "runtime.http": { router } },
79
+ createTables: true
80
+ });
81
+ t.after(started.stop);
82
+ await knex("regions").insert({ name: "North", code: "N", secret: "private" });
83
+ await knex("customers").insert({ name: "Acme", region_id: 1 });
84
+ await knex("tags").insert({ label: "Urgent" });
85
+ await knex("orders").insert({ reference: "A-1", customer_id: 1 });
86
+ return { actions: started.capabilities.actions, router };
87
+ }
88
+
89
+ function includedOf(document) {
90
+ return document.included
91
+ .map(({ type, attributes }) => [type, attributes])
92
+ .sort(([left], [right]) => left.localeCompare(right));
93
+ }
94
+
95
+ // The client translates a code only when the server's English is the catalog's English for it, with its params.
96
+ function assertCatalogRenders({ code, params }, sentEnglish) {
97
+ assert.equal(formatMessage(catalogMessage(english, messageKeyForCode(code)), params), sentEnglish, code);
98
+ }
99
+
100
+ test("a list or view narrows a record its include reaches two levels down with fields[<type>], to fields the include shows", async (t) => {
101
+ const { actions } = await startOrders(t);
102
+ const read = (actionId, fields, input = {}) => actions.execute({
103
+ actionId,
104
+ input: { ...input, include: INCLUDE, ...(fields ? { fields } : {}) },
105
+ context: API
106
+ });
107
+
108
+ // The include shows the region's name and code; fields[regions] narrows the region, in a list and in a view.
109
+ assert.deepEqual(includedOf((await read("crud.orders.list")).value), [
110
+ ["customers", { name: "Acme" }],
111
+ ["regions", { name: "North", code: "N" }]
112
+ ]);
113
+ for (const [actionId, input] of [["crud.orders.list", {}], ["crud.orders.view", { recordId: "1" }]]) {
114
+ assert.deepEqual(includedOf((await read(actionId, { regions: ["name"] }, input)).value), [
115
+ ["customers", { name: "Acme" }],
116
+ ["regions", { name: "North" }]
117
+ ], actionId);
118
+ }
119
+
120
+ // A field the include does not show, and a type no include reaches, stay refused.
121
+ for (const [fields, code, english] of [
122
+ [{ regions: ["secret"] }, "crud.query.fieldsNotShown", /^fields\[regions\] may name only what this read's includes show of regions: name, code\. It names secret\.$/u],
123
+ [{ tags: ["label"] }, "crud.query.fieldsKeysInvalidWithAliases", /Allowed keys: "orders", "customers", "regions"\./u]
124
+ ]) {
125
+ const [field] = Object.keys(fields).map((type) => `fields.${type}`);
126
+ await assert.rejects(read("crud.orders.list", fields), (error) => {
127
+ assert.equal(error.status, 400);
128
+ assert.equal(error.details.fieldErrorCodes[field].code, code);
129
+ assert.match(error.details.fieldErrors[field], english);
130
+ assertCatalogRenders(error.details.fieldErrorCodes[field], error.details.fieldErrors[field]);
131
+ return true;
132
+ });
133
+ }
134
+ });
135
+
136
+ test("over HTTP, fields[<type>] narrows a record two include levels down and refuses unshown fields and unreached types", async (t) => {
137
+ const { actions, router } = await startOrders(t);
138
+ const app = Fastify();
139
+ t.after(() => app.close());
140
+ registerApiErrorHandler(app);
141
+ registerRoutes(app, { routes: router.list(), actions });
142
+ const { path } = router.list().find((route) => route.method === "GET" && route.path.endsWith("/orders"));
143
+ const get = (query) => app.inject({ method: "GET", url: `${path}?include=${INCLUDE}&${query}` });
144
+
145
+ const narrowed = await get("fields%5Bregions%5D=name");
146
+ assert.equal(narrowed.statusCode, 200, narrowed.body);
147
+ assert.deepEqual(includedOf(narrowed.json()), [["customers", { name: "Acme" }], ["regions", { name: "North" }]]);
148
+
149
+ for (const [query, code] of [
150
+ ["fields%5Bregions%5D=secret", "crud.query.fieldsNotShown"],
151
+ ["fields%5Btags%5D=label", "crud.query.fieldsKeysInvalidWithAliases"]
152
+ ]) {
153
+ const response = await get(query);
154
+ assert.equal(response.statusCode, 400, `${query}: ${response.body}`);
155
+ assert.ok(response.body.includes(`"${code}"`), `${query}: ${response.body}`);
156
+ }
157
+ });