@crud-api/core 0.1.1 → 0.3.0

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/dist/sorting.js CHANGED
@@ -1,13 +1,14 @@
1
1
  // Sorting Parameter (Base section 4.2.3): sort keys and the total order of values.
2
2
  import { createCodec, isTypedValue, UnknownTag } from "@ecson/core";
3
3
  import { compareValues, MISSING, parseDecimal, typeOf } from "@unquery/core";
4
+ import { formatFieldPath } from "./field-list.js";
4
5
  import { keyPaths, samePath } from "./projection.js";
5
6
  const DEFAULT_CODEC = createCodec();
6
7
  /**
7
8
  * Sort keys of a `list` operation (SORTING_FIELD_LIST: the `-` modifier means descending). SORTING_DEFAULT: the
8
9
  * Resource ID is added as the last key, ascending: `_id`, or each composite key path in key order
9
10
  * (ID_COMP_KEY_FIELDS), unless the path is already a key. Without a Sorting Parameter (null or empty), the
10
- * keys are the Resource ID alone.
11
+ * keys are the Resource ID alone. Paths may have indexes (SORTING_ARRAY_PATH: `parseFieldList` with `{ indexes: true }`).
11
12
  */
12
13
  export function sortKeys(items, key) {
13
14
  const keys = (items ?? []).map((item) => ({ path: item.path, direction: item.modifier ? "desc" : "asc" }));
@@ -239,24 +240,75 @@ function compareWith(a, b, codec) {
239
240
  }
240
241
  }
241
242
  }
243
+ /** `follow` met an array where the path goes on with a name (SORTING_ARRAY_PATH). */
244
+ const CROSSED = Symbol("crossed");
242
245
  /**
243
- * The value at a field path of a Resource, or `MISSING`. Decision: the path is followed through plain objects
244
- * only; an array (or any other value) in the middle of the path gives `MISSING` (Base does not define sorting by
245
- * a path through arrays).
246
+ * The value at a sort path (SORTING_ARRAY_PATH, D112): a name follows an own property of a plain object; an index
247
+ * (UnQuery PATH_INDEX) selects the element of an array, and gives `MISSING` on anything else or out of range; a name
248
+ * after an array (UnQuery PATH_ARRAYS without an index) gives `CROSSED`; any other value in the middle gives `MISSING`.
249
+ * A path that ends at an array gives the whole array.
246
250
  */
247
- export function getPath(resource, path) {
251
+ function follow(resource, path) {
248
252
  let value = resource;
249
- for (const segment of path) {
250
- if (typeOf(value) !== "object" || !Object.hasOwn(value, segment))
253
+ for (const element of path) {
254
+ if (typeof element === "number") {
255
+ if (!Array.isArray(value) || element >= value.length)
256
+ return MISSING;
257
+ value = value[element];
258
+ }
259
+ else if (Array.isArray(value))
260
+ return CROSSED;
261
+ else if (typeOf(value) !== "object" || !Object.hasOwn(value, element))
251
262
  return MISSING;
252
- value = value[segment];
263
+ else
264
+ value = value[element];
253
265
  }
254
266
  return value;
255
267
  }
268
+ /**
269
+ * The value at a field path of a Resource, or `MISSING`, as sorting reads it (SORTING_ARRAY_PATH, D112): names follow
270
+ * own properties of plain objects, indexes select array elements (`MISSING` on a non-array or out of range), and a
271
+ * path that crosses an array without an index gives `MISSING`, never an element of the array.
272
+ */
273
+ export function getPath(resource, path) {
274
+ const value = follow(resource, path);
275
+ return value === CROSSED ? MISSING : value;
276
+ }
277
+ /** True when the path crosses an array of the Resource without an index, so it sorts as missing (SORTING_ARRAY_PATH). */
278
+ export function crossesArray(resource, path) {
279
+ return follow(resource, path) === CROSSED;
280
+ }
281
+ /** The `SORT_ARRAY_PATH` Warning for a sort path, written as a field list item in `field` (SORTING_ARRAY_PATH). */
282
+ export function sortArrayPathWarning(path) {
283
+ const field = formatFieldPath(path);
284
+ return { code: "SORT_ARRAY_PATH", message: `the sort path ${field} crosses an array without an index, so it sorts as a missing value`, field };
285
+ }
286
+ /**
287
+ * The `SORT_ARRAY_PATH` Warnings of a sort (SORTING_ARRAY_PATH, D112): one for each distinct key path that crosses an
288
+ * array in at least one of the Resources, in key order. A provider that sorts passes every matched Resource, not
289
+ * only the page, and reports these once per operation.
290
+ */
291
+ export function sortArrayPathWarnings(resources, keys) {
292
+ const paths = [];
293
+ for (const key of keys)
294
+ if (key.path.length > 1 && !paths.some((p) => samePath(p, key.path)))
295
+ paths.push(key.path);
296
+ if (paths.length === 0)
297
+ return [];
298
+ const crossing = new Set();
299
+ for (const resource of resources) {
300
+ for (const path of paths)
301
+ if (!crossing.has(path) && crossesArray(resource, path))
302
+ crossing.add(path);
303
+ if (crossing.size === paths.length)
304
+ break;
305
+ }
306
+ return paths.filter((path) => crossing.has(path)).map(sortArrayPathWarning);
307
+ }
256
308
  /**
257
309
  * A comparator for `Array.prototype.sort` (SORTING_FIELD_LIST): each key in order, descending keys reversed, so
258
- * that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS).
259
- * `options.codec` as in `compareSortValues`.
310
+ * that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS). Values
311
+ * are read with `getPath` (SORTING_ARRAY_PATH). `options.codec` as in `compareSortValues`.
260
312
  */
261
313
  export function compareResources(keys, options = {}) {
262
314
  const codec = options.codec ?? DEFAULT_CODEC;
package/dist/subject.d.ts CHANGED
@@ -32,7 +32,10 @@ export declare function keyIsTopLevel(key: KeySpec): boolean;
32
32
  * INVALID_INPUT for a Subject Resource and INVALID_PATCH for the result of a patch (as D54).
33
33
  */
34
34
  export declare function assertNoStrayId(resource: Resource, key: KeySpec, code?: "INVALID_INPUT" | "INVALID_PATCH"): void;
35
- /** ID_SLUG, ID_COMP_KEY_URLENCODED: the Resource ID of the Subject is well formed. */
35
+ /**
36
+ * SUB_ID, ID_INVALID: the Subject has a Resource ID (SUB_ID when it has none) and it is valid: a string without
37
+ * control characters for an `_id` key (ID_STRING), the urlencoded pairs for a composite key (ID_COMP_KEY_URLENCODED).
38
+ */
36
39
  export declare function assertSubjectId(id: unknown, key: KeySpec, options?: IdOptions): asserts id is ResourceId;
37
40
  /**
38
41
  * The canonical text of a Resource ID: a composite ID has several texts (`%22a%22=1` and `a=1`), so IDs are compared
@@ -40,8 +43,9 @@ export declare function assertSubjectId(id: unknown, key: KeySpec, options?: IdO
40
43
  */
41
44
  export declare function canonicalId(id: ResourceId, key: KeySpec, options?: IdOptions): ResourceId;
42
45
  /**
43
- * SUB_WITH_IDS, RES_NO_IDS: a Client `_id` must be a string Slug of a kind the Collection accepts
44
- * (`info.idKinds ?? capabilities.ids.kinds`), and the provider must accept Client IDs; otherwise NEGOTIATION.
46
+ * SUB_WITH_IDS, RES_NO_IDS: a Client `_id` must first be a valid Resource ID (ID_INVALID: INVALID_INPUT); then the
47
+ * provider must accept Client IDs and the ID must be of a kind the Collection accepts (`info.idKinds ??
48
+ * capabilities.ids.kinds`), otherwise NEGOTIATION: a valid ID the Server cannot give to a new Resource (D113).
45
49
  * Composite keys are data the Client always sends, so they are not subject to `clientIds` (D48).
46
50
  */
47
51
  export declare function assertClientId(id: unknown, info: CollectionInfo, caps: ProviderCapabilities): void;
package/dist/subject.js CHANGED
@@ -103,9 +103,12 @@ export function assertNoStrayId(resource, key, code = "INVALID_INPUT") {
103
103
  });
104
104
  }
105
105
  }
106
- /** ID_SLUG, ID_COMP_KEY_URLENCODED: the Resource ID of the Subject is well formed. */
106
+ /**
107
+ * SUB_ID, ID_INVALID: the Subject has a Resource ID (SUB_ID when it has none) and it is valid: a string without
108
+ * control characters for an `_id` key (ID_STRING), the urlencoded pairs for a composite key (ID_COMP_KEY_URLENCODED).
109
+ */
107
110
  export function assertSubjectId(id, key, options = {}) {
108
- if (typeof id !== "string")
111
+ if (id === undefined)
109
112
  throw new CrudError("INVALID_INPUT", "the Subject needs a Resource ID", { rule: "SUB_ID" });
110
113
  assertValidId(id, key, options);
111
114
  }
@@ -117,24 +120,21 @@ export function canonicalId(id, key, options = {}) {
117
120
  return key.kind === "id" ? id : formatCompositeId(parseCompositeId(id, key.paths, options), key.paths, options);
118
121
  }
119
122
  /**
120
- * SUB_WITH_IDS, RES_NO_IDS: a Client `_id` must be a string Slug of a kind the Collection accepts
121
- * (`info.idKinds ?? capabilities.ids.kinds`), and the provider must accept Client IDs; otherwise NEGOTIATION.
123
+ * SUB_WITH_IDS, RES_NO_IDS: a Client `_id` must first be a valid Resource ID (ID_INVALID: INVALID_INPUT); then the
124
+ * provider must accept Client IDs and the ID must be of a kind the Collection accepts (`info.idKinds ??
125
+ * capabilities.ids.kinds`), otherwise NEGOTIATION: a valid ID the Server cannot give to a new Resource (D113).
122
126
  * Composite keys are data the Client always sends, so they are not subject to `clientIds` (D48).
123
127
  */
124
128
  export function assertClientId(id, info, caps) {
125
129
  if (info.key.kind !== "id")
126
130
  return;
131
+ assertValidId(id, info.key);
127
132
  const fail = (reason) => {
128
133
  throw new CrudError("NEGOTIATION", `the Resource ID ${JSON.stringify(id)} cannot be used: ${reason}`, { rule: "RES_NO_IDS" });
129
134
  };
130
135
  if (!caps.ids.clientIds)
131
136
  fail("this Collection does not accept Resource IDs sent by the Client");
132
- if (typeof id !== "string")
133
- fail("a Resource ID is a string"); // ID_SLUG
134
137
  const kinds = info.idKinds ?? caps.ids.kinds;
135
- const own = idKindOf(id);
136
- if (own.length === 0)
137
- fail("a Resource ID must be a Slug"); // ID_SLUG
138
- if (!own.some((kind) => kinds.includes(kind)))
138
+ if (!idKindOf(id).some((kind) => kinds.includes(kind)))
139
139
  fail(`this Collection accepts only ${kinds.join(", ")}`);
140
140
  }
package/dist/types.d.ts CHANGED
@@ -2,7 +2,13 @@
2
2
  export type Resource = Record<string, unknown>;
3
3
  /** A field path: segments without quotes, in the UnQuery syntax (PATH_DOT_NOTATION), never with indexes (FIELD_LIST_NO_INDEX). */
4
4
  export type Path = readonly string[];
5
- /** A Resource ID in its text form: a Slug (ID_SLUG) or a composite key in its urlencoded form (ID_COMP_KEY_URLENCODED). */
5
+ /**
6
+ * A field path of the Sorting Parameter: names, and numbers for the array indexes that only this field list may have
7
+ * (UnQuery PATH_INDEX, FIELD_LIST_NO_INDEX, SORTING_ARRAY_PATH): `items[0].price` is `["items", 0, "price"]`. Every
8
+ * `Path` is a `SortPath`.
9
+ */
10
+ export type SortPath = readonly (string | number)[];
11
+ /** A Resource ID in its text form: a non-empty string (ID_STRING, preferably a Slug) or a composite key in its urlencoded form (ID_COMP_KEY_URLENCODED). */
6
12
  export type ResourceId = string;
7
13
  /** Where a Collection keeps its Resource ID: the `_id` Field (ID_KEY) or an ordered list of field paths (ID_COMP_KEY). */
8
14
  export type KeySpec = {
@@ -11,8 +17,8 @@ export type KeySpec = {
11
17
  readonly kind: "composite";
12
18
  readonly paths: readonly Path[];
13
19
  };
14
- /** Resource ID types a Collection accepts from Clients (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG). */
15
- export type IdKind = "uuid-hex" | "uuid-base64url" | "slug";
20
+ /** Resource ID types a Collection accepts from Clients (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG); `string` is any valid ID (ID_STRING, D113). */
21
+ export type IdKind = "uuid-hex" | "uuid-base64url" | "slug" | "string";
16
22
  /** Resource Representations of the Output (REPR_ECSON, REPR_PLAIN_JSON). */
17
23
  export type Representation = "ecson" | "json";
18
24
  /** The Base operations (section 2.4); `listByView` belongs to the Views extension. */
@@ -20,9 +26,9 @@ export type OperationName = "get" | "list" | "create" | "clone" | "patchById" |
20
26
  export declare const OPERATIONS: readonly OperationName[];
21
27
  /** The default key: the `_id` Field. */
22
28
  export declare const ID_KEY: KeySpec;
23
- /** One key of a Sorting Parameter (SORTING_FIELD_LIST). */
29
+ /** One key of a Sorting Parameter (SORTING_FIELD_LIST), possibly with indexes (SORTING_ARRAY_PATH). */
24
30
  export interface SortKey {
25
- readonly path: Path;
31
+ readonly path: SortPath;
26
32
  readonly direction: "asc" | "desc";
27
33
  }
28
34
  /**
@@ -8,6 +8,11 @@ export interface Warning {
8
8
  error?: string;
9
9
  [member: string]: unknown;
10
10
  }
11
+ /**
12
+ * True when `name` may name a Warning member other than `code` and `message` (WARN_MEMBER_NAMES), in every Protocol
13
+ * under the same name. Servers leave out members with other names and Clients ignore them (D114).
14
+ */
15
+ export declare function isWarningMemberName(name: string): boolean;
11
16
  /** The Base Warning codes (table of section 3.4.5). */
12
17
  export declare const BASE_WARNING_CODES: ReadonlySet<string>;
13
18
  /**
@@ -51,7 +56,10 @@ export declare function allows(preference: StrictPreference, code: string): bool
51
56
  /**
52
57
  * Collects the Warnings of one operation. A code the server does not know, a missing message or a missing member
53
58
  * required by the Base table is a programming error of the component that reported it (WARN_STANDARD_CODES,
54
- * WARN_CUSTOM_CODES), so it throws instead of reaching the Client.
59
+ * WARN_CUSTOM_CODES), so it throws instead of reaching the Client. A member whose name does not follow
60
+ * WARN_MEMBER_NAMES (`docUrl`, `Doc`, `1x`) is left out of the collected copy, so no Protocol ever sends it (D114).
61
+ * `SORT_ARRAY_PATH` is kept once for each `field` (SORTING_ARRAY_PATH: once per operation for each path, D112),
62
+ * whoever reports it and however many reads sort.
55
63
  */
56
64
  export declare class WarningSink {
57
65
  #private;
package/dist/warnings.js CHANGED
@@ -1,5 +1,14 @@
1
1
  // Warnings and the strict preference (Base section 3.4.5).
2
2
  import { BASE_ERROR_CODES, isNamespacedCode } from "./errors.js";
3
+ /** WARN_MEMBER_NAMES: lowercase ASCII letters, digits, `_` and `-`, starting with a letter (keys of RFC 9651 too). */
4
+ const MEMBER_NAME = /^[a-z][a-z0-9_-]*$/;
5
+ /**
6
+ * True when `name` may name a Warning member other than `code` and `message` (WARN_MEMBER_NAMES), in every Protocol
7
+ * under the same name. Servers leave out members with other names and Clients ignore them (D114).
8
+ */
9
+ export function isWarningMemberName(name) {
10
+ return MEMBER_NAME.test(name);
11
+ }
3
12
  /** The Base Warning codes (table of section 3.4.5). */
4
13
  export const BASE_WARNING_CODES = new Set([
5
14
  "PARAM_IGNORED",
@@ -10,6 +19,7 @@ export const BASE_WARNING_CODES = new Set([
10
19
  "WRITE_FAILED",
11
20
  "TYPE_DOWNGRADED",
12
21
  "DEPRECATED",
22
+ "SORT_ARRAY_PATH",
13
23
  ]);
14
24
  /** WARN_STANDARD_CODES: members the Base table requires for each code (`id` of WRITE_FAILED only "when known"). */
15
25
  const REQUIRED_MEMBERS = {
@@ -19,6 +29,7 @@ const REQUIRED_MEMBERS = {
19
29
  FIELD_IGNORED: ["field"],
20
30
  WRITE_FAILED: ["error"],
21
31
  TYPE_DOWNGRADED: ["field"],
32
+ SORT_ARRAY_PATH: ["field"],
22
33
  };
23
34
  /**
24
35
  * Error and Warning codes known to a server: the Base codes, the codes registered by extensions and Protocols
@@ -93,7 +104,10 @@ export function allows(preference, code) {
93
104
  /**
94
105
  * Collects the Warnings of one operation. A code the server does not know, a missing message or a missing member
95
106
  * required by the Base table is a programming error of the component that reported it (WARN_STANDARD_CODES,
96
- * WARN_CUSTOM_CODES), so it throws instead of reaching the Client.
107
+ * WARN_CUSTOM_CODES), so it throws instead of reaching the Client. A member whose name does not follow
108
+ * WARN_MEMBER_NAMES (`docUrl`, `Doc`, `1x`) is left out of the collected copy, so no Protocol ever sends it (D114).
109
+ * `SORT_ARRAY_PATH` is kept once for each `field` (SORTING_ARRAY_PATH: once per operation for each path, D112),
110
+ * whoever reports it and however many reads sort.
97
111
  */
98
112
  export class WarningSink {
99
113
  #registry;
@@ -112,7 +126,13 @@ export class WarningSink {
112
126
  if (typeof warning[member] !== "string")
113
127
  throw new TypeError(`Warning ${warning.code} needs the member ${member} (WARN_STANDARD_CODES)`);
114
128
  }
115
- this.#list.push({ ...warning });
129
+ if (warning.code === "SORT_ARRAY_PATH" && this.#list.some((w) => w.code === warning.code && w.field === warning.field))
130
+ return;
131
+ const collected = { code: warning.code, message: warning.message };
132
+ for (const [name, value] of Object.entries(warning))
133
+ if (isWarningMemberName(name))
134
+ collected[name] = value;
135
+ this.#list.push(collected);
116
136
  }
117
137
  get list() {
118
138
  return this.#list;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crud-api/core",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "CRUD API reference implementation: data model, engine, provider contract, field lists, projection, sorting, pagination, patch engines, negotiation",
5
5
  "keywords": [
6
6
  "crud",