@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/README.md CHANGED
@@ -36,7 +36,7 @@ Each operation goes through the steps of the design, and the first failure stops
36
36
  3. the `authorize` hook (`ACCESS_DENIED`);
37
37
  4. the Collection (`COLLECTION_SLUG`, `COLLECTION_NOT_FOUND`, `COLLECTION_CREATE_IMPLICIT`);
38
38
  5. the operation;
39
- 6. Parameters: field lists, sorting (`SORTING_NULLS`), pagination with the smaller maximum of server and provider, unknown Parameters reported as `PARAM_IGNORED`;
39
+ 6. Parameters: field lists (indexes only in the Sorting Parameter, `SORTING_ARRAY_PATH`), sorting (`SORTING_NULLS`), pagination with the smaller maximum of server and provider, unknown Parameters reported as `PARAM_IGNORED`;
40
40
  7. the Subject: Resource IDs, Field names, reserved Fields (`_meta` without Metadata is dropped with `FIELD_IGNORED`), Client IDs (`RES_NO_IDS`), patch well-formedness;
41
41
  8. the Search Query, parsed with UnQuery and checked against the provider's operators;
42
42
  9. extension hooks (`beforeWrite`, `afterRead`);
@@ -64,6 +64,7 @@ Only then does anything get written. Reads and writes are composed from provider
64
64
 
65
65
  - `query` is text in a negotiated format (`{ format, text }`), the same text combined with conditions read elsewhere (`{ format, text, and }`, where `and` is an UnQuery model, such as the query string of an HTTP `QUERY` request), or a model the adapter already built (`{ filter }`). Limits and the provider's operators apply to the final model; a native format cannot be combined with `and` (`UNSUPPORTED`).
66
66
  - `warnings` carries the Warnings the adapter found while reading the request (an unknown control parameter, a condition on a single-Resource endpoint). They come first in `meta.warnings`, and under the strict preference the operation fails with `STRICT_WARNINGS` before any provider call.
67
+ - Every Warning, whoever reports it (the adapter, an extension, the provider), keeps only the members whose names follow WARN_MEMBER_NAMES (lowercase ASCII letters, digits, `_` and `-`, starting with a letter): `docUrl` or `1x` are left out, `doc_url` stays, so every Protocol sends a member under the same name (D114). `isWarningMemberName(name)` tells which names a Client must ignore.
67
68
  - `server.registerProtocol({ name, warningCodes, errorCodes })` registers the codes a Protocol specification defines (`CONDITION_IGNORED` for HTTP). It is idempotent, and throws (registering nothing) on a Base code or a code another extension or Protocol owns.
68
69
  - `server.description` lists the specifications, extensions, `customParams`, `queryFormats` (UnQuery JSON, UnQuery SQL, then the provider's) and `representations`.
69
70
  - `meta.limit` is the page size a `list` used (the requested `limit`, the maximum it was reduced to, the default limit, or `null` for a page without limit; D97), so an adapter can build the links of the next page (`Link` header fields).
@@ -72,7 +73,7 @@ Only then does anything get written. Reads and writes are composed from provider
72
73
 
73
74
  ## Providers
74
75
 
75
- A provider implements `Provider` (`capabilities`, `collection`, `createCollection`, `dropEmptyCollection`, `prepare`, `execute`, `transaction`, `testing`; `testing.inspectNative` optionally tells how a stored value is kept, for the conformance kit). `prepare` is pure and synchronous: it translates a primitive and reports the Warnings that depend only on the input, so that the core can fail before writing. Both `prepare` and `execute` receive the Server's ECSON codec as `ctx.codec`. An implicit Collection is created inside the transaction when the transaction object has `createCollection`; otherwise it is created before the writes and removed again with `dropEmptyCollection` when the `create` writes nothing. Capabilities declare what the provider can do exactly (operators, pagination, sorting, counts, transactions, ID kinds, native types, implicit and system Collections, `lateWarnings`); the core rejects anything outside them.
76
+ A provider implements `Provider` (`capabilities`, `collection`, `createCollection`, `dropEmptyCollection`, `prepare`, `execute`, `transaction`, `testing`; `testing.inspectNative` optionally tells how a stored value is kept, for the conformance kit). `prepare` is pure and synchronous: it translates a primitive and reports the Warnings that depend only on the input, so that the core can fail before writing. Both `prepare` and `execute` receive the Server's ECSON codec as `ctx.codec`. A `find` that sorts reads values with `getPath` (or sorts natively by the same rules) and reports from `execute` the `SORT_ARRAY_PATH` Warnings of `sortArrayPathWarnings` over every matched Resource (`SORTING_ARRAY_PATH`). An implicit Collection is created inside the transaction when the transaction object has `createCollection`; otherwise it is created before the writes and removed again with `dropEmptyCollection` when the `create` writes nothing. Capabilities declare what the provider can do exactly (operators, pagination, sorting, counts, transactions, ID kinds, native types, implicit and system Collections, `lateWarnings`); the core rejects anything outside them.
76
77
 
77
78
  ## Conformance
78
79
 
@@ -0,0 +1,19 @@
1
+ import type { Resource } from "./types.ts";
2
+ import { type Codec } from "@ecson/core";
3
+ /**
4
+ * The ECSON tag of a value, or `undefined` for JSON values (and for values outside the ECSON model). `codec` is the
5
+ * Server's (design 6.4), so the types of enabled extensions (`$rel`) have their tag; default the default codec of `@ecson/core`.
6
+ */
7
+ export declare function tagOf(value: unknown, codec?: Codec): string | undefined;
8
+ /** A Resource prepared for storage: the converted copy and the Fields whose values were downgraded, formatted. */
9
+ export interface Downgraded {
10
+ readonly resource: Resource;
11
+ readonly fields: readonly string[];
12
+ }
13
+ /**
14
+ * REPR_DOWNGRADE: a copy of `resource` where every value whose tag is not in `native` is replaced by its plain JSON
15
+ * form (`toPlain`). Plain objects and arrays are JSON containers and are traversed; the elements of a native `$set`
16
+ * or `$map` are traversed too, and reported with the path of the Field holding them (field paths have no indexes).
17
+ * Pure: never mutates `resource`.
18
+ */
19
+ export declare function downgrade(resource: Resource, native: ReadonlySet<string> | "all", codec?: Codec): Downgraded;
@@ -0,0 +1,70 @@
1
+ // REPR_NATIVE_STORAGE, REPR_DOWNGRADE (design 6.6): values are stored as host values; a value whose ECSON tag is not
2
+ // among the provider's declared native types is stored in its plain JSON form, and the Field is reported with
3
+ // TYPE_DOWNGRADED. Moved from `@crud-api/memory` so that providers and extensions share one definition of the stored
4
+ // form (D128): the Metadata hash describes the Resource as stored.
5
+ import { cloneValue, isPlainObject } from "./patch.js";
6
+ import { createCodec, isTypedValue, UnknownTag } from "@ecson/core";
7
+ import { formatPath } from "@unquery/core";
8
+ const DEFAULT_CODEC = createCodec();
9
+ /**
10
+ * The ECSON tag of a value, or `undefined` for JSON values (and for values outside the ECSON model). `codec` is the
11
+ * Server's (design 6.4), so the types of enabled extensions (`$rel`) have their tag; default the default codec of `@ecson/core`.
12
+ */
13
+ export function tagOf(value, codec = DEFAULT_CODEC) {
14
+ if (value === null || typeof value === "string" || typeof value === "boolean")
15
+ return undefined;
16
+ // A finite number other than -0 is a JSON number; NaN, the infinities and -0 are `$number` (ECSON).
17
+ if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0))
18
+ return undefined;
19
+ if (value instanceof UnknownTag)
20
+ return value.tag;
21
+ try {
22
+ const tree = codec.encode(value);
23
+ return isTypedValue(tree) ? Object.keys(tree)[0] : undefined;
24
+ }
25
+ catch {
26
+ // Decision: a value the ECSON codec cannot write (a function, a class instance) has no tag; it is copied as it is.
27
+ return undefined;
28
+ }
29
+ }
30
+ /**
31
+ * REPR_DOWNGRADE: a copy of `resource` where every value whose tag is not in `native` is replaced by its plain JSON
32
+ * form (`toPlain`). Plain objects and arrays are JSON containers and are traversed; the elements of a native `$set`
33
+ * or `$map` are traversed too, and reported with the path of the Field holding them (field paths have no indexes).
34
+ * Pure: never mutates `resource`.
35
+ */
36
+ export function downgrade(resource, native, codec = DEFAULT_CODEC) {
37
+ if (native === "all")
38
+ return { resource: cloneValue(resource), fields: [] };
39
+ const fields = [];
40
+ const report = (path) => {
41
+ const field = formatPath(path);
42
+ if (!fields.includes(field))
43
+ fields.push(field);
44
+ };
45
+ const walk = (value, path) => {
46
+ if (isPlainObject(value)) {
47
+ const copy = {};
48
+ for (const name of Object.keys(value)) {
49
+ // Own data property, so that a `__proto__` Field never reaches the prototype setter.
50
+ Object.defineProperty(copy, name, { value: walk(value[name], [...path, name]), writable: true, enumerable: true, configurable: true });
51
+ }
52
+ return copy;
53
+ }
54
+ if (Array.isArray(value))
55
+ return value.map((element) => walk(element, path));
56
+ const tag = tagOf(value, codec);
57
+ if (tag === undefined)
58
+ return cloneValue(value);
59
+ if (!native.has(tag)) {
60
+ report(path);
61
+ return codec.toPlain(value);
62
+ }
63
+ if (value instanceof Set)
64
+ return new Set([...value].map((element) => walk(element, path)));
65
+ if (value instanceof Map)
66
+ return new Map([...value].map(([k, v]) => [walk(k, path), walk(v, path)]));
67
+ return cloneValue(value);
68
+ };
69
+ return { resource: walk(resource, []), fields };
70
+ }
@@ -1,13 +1,45 @@
1
- import type { OperationName, Resource } from "./types.ts";
1
+ import type { Codec } from "@ecson/core";
2
+ import type { OperationName, Resource, ResourceId } from "./types.ts";
2
3
  import { CodeRegistry, type Warning } from "./warnings.ts";
3
- /** The context of an extension hook: Warnings go to the sink of the operation (WARN_EXTENSION_CODES). */
4
+ /**
5
+ * The context of an extension hook: Warnings go to the sink of the operation (WARN_EXTENSION_CODES); the clock and the
6
+ * codec are the Server's, and `principal` is the Client's identity as the Protocol adapter or host gave it (D116).
7
+ */
4
8
  export interface HookCtx {
5
9
  warn(warning: Warning): void;
10
+ /**
11
+ * Reports the Warning unless one with the same code and members (the message aside) was already reported in the
12
+ * operation, so that a hook called once per matched Resource reports what the Client sent once (D116).
13
+ */
14
+ warnOnce(warning: Warning): void;
15
+ /** Unix time in milliseconds, from the Server's injected clock. */
16
+ clock(): number;
17
+ /** `request.meta.principal`, undefined when none was given. */
18
+ readonly principal: unknown;
19
+ /** The ECSON codec of the Server (design 6.4). */
20
+ readonly codec: Codec;
21
+ /**
22
+ * The form the data provider stores the Resource in (REPR_DOWNGRADE): values whose ECSON tag is not among its
23
+ * declared `nativeTypes` in their plain JSON form (D128). Pure; the Resource given is not changed.
24
+ */
25
+ stored(resource: Resource): Resource;
26
+ }
27
+ /**
28
+ * A Parameter an extension adds (design 7, "extra Parameters"; D116): recognized by the listed operations, so that it
29
+ * is not reported as PARAM_IGNORED there (PARAM_CUSTOM_UNKNOWN), and passed to the extension's hooks in `params`.
30
+ */
31
+ export interface ExtensionParameter {
32
+ readonly name: string;
33
+ readonly operations: readonly OperationName[];
34
+ /** Checks the value in step 6 of design 6.3, before anything is read; throws a CrudError when it is invalid. */
35
+ check?(value: unknown): void;
6
36
  }
37
+ /** The Parameters of one extension that the request sent, by name (D116). */
38
+ export type ExtensionParams = Readonly<Record<string, unknown>>;
7
39
  /**
8
40
  * An extension of the Base Specification (design 7): a factory result passed to `createCrudServer`. Phase 2 offers
9
- * the minimum hooks (`beforeWrite`, `afterRead`); later phases add reserved Collection handlers, extra operations and
10
- * the execution mode.
41
+ * `beforeWrite` and `afterRead`, phase 7 (Metadata) Parameters and `precondition` (D116); later phases add reserved
42
+ * Collection handlers, extra operations and the execution mode.
11
43
  */
12
44
  export interface Extension {
13
45
  /** Unique name, such as `metadata`. */
@@ -31,19 +63,58 @@ export interface Extension {
31
63
  readonly errorCodes?: readonly string[];
32
64
  /** Warning codes of the extension (WARN_EXTENSION_CODES: never a Base code). */
33
65
  readonly warningCodes?: readonly string[];
34
- /** Called on each Resource about to be written, with its previous state (null on create, clone and upsert). */
35
- beforeWrite?(input: {
36
- readonly operation: OperationName;
37
- readonly collection: string;
38
- readonly previous: Resource | null;
39
- readonly next: Resource;
40
- }, ctx: HookCtx): Resource | Promise<Resource>;
66
+ /** Parameters of the extension (D116). */
67
+ readonly parameters?: readonly ExtensionParameter[];
68
+ /**
69
+ * Called on each Resource about to be written, with its previous state (null on create, clone and upsert), the
70
+ * extension's Parameters and, for `clone`, the source Resource as stored.
71
+ */
72
+ beforeWrite?(input: BeforeWriteInput, ctx: HookCtx): Resource | Promise<Resource>;
73
+ /**
74
+ * Called with the current state of each Resource a write by ID or by query targets, before anything changes (D116):
75
+ * `patchById`, `replaceById` and `deleteById` call it right after reading the Resource (`current` null when it does
76
+ * not exist, before NOT_FOUND, UPSERT_DENIED and the upsert), and the ByQuery writes with each matched Resource after
77
+ * PARAM_EXPECT_MATCH. Throwing a CrudError fails the operation without writing (Metadata META_DOC_CONDITIONAL).
78
+ */
79
+ precondition?(input: PreconditionInput, ctx: HookCtx): void | Promise<void>;
41
80
  /** Called on the Resources read by `get` and `list`, after the provider's projection push-down and before the core's own projection (D74). */
42
81
  afterRead?(input: {
43
82
  readonly collection: string;
44
83
  readonly resources: Resource[];
45
84
  }, ctx: HookCtx): Resource[] | Promise<Resource[]>;
46
85
  }
86
+ /** What `beforeWrite` receives (D116). */
87
+ export interface BeforeWriteInput {
88
+ readonly operation: OperationName;
89
+ readonly collection: string;
90
+ readonly previous: Resource | null;
91
+ readonly next: Resource;
92
+ /** The extension's own Parameters the request sent. */
93
+ readonly params: ExtensionParams;
94
+ /** `clone`: the source Resource as stored, with its canonical Resource ID. */
95
+ readonly source?: {
96
+ readonly collection: string;
97
+ readonly id: ResourceId;
98
+ readonly resource: Resource;
99
+ };
100
+ /** `patchById`, `patchByQuery` and `clone` with a patch: the Client's patch, so hooks know what it touched (D128). */
101
+ readonly patch?: {
102
+ readonly type: "json-patch";
103
+ readonly ops: unknown;
104
+ } | {
105
+ readonly type: "merge-patch";
106
+ readonly doc: unknown;
107
+ };
108
+ }
109
+ /** What `precondition` receives (D116). */
110
+ export interface PreconditionInput {
111
+ readonly operation: OperationName;
112
+ readonly collection: string;
113
+ /** The current state, null when the Resource does not exist. */
114
+ readonly current: Resource | null;
115
+ /** The extension's own Parameters the request sent. */
116
+ readonly params: ExtensionParams;
117
+ }
47
118
  /**
48
119
  * Reserved Fields defined by the specifications of the family, with the extension that defines each one
49
120
  * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
@@ -59,13 +130,19 @@ export declare class ExtensionRegistry {
59
130
  get names(): string[];
60
131
  /** The extension that claims a reserved Collection name (design 6.3 step 4), if any. */
61
132
  claimant(collection: string): Extension | undefined;
62
- /** Runs every `beforeWrite` hook in the order of the extensions. */
63
- beforeWrite(input: {
64
- operation: OperationName;
65
- collection: string;
66
- previous: Resource | null;
67
- next: Resource;
133
+ /** The Parameters of the enabled extensions that `operation` recognizes (D116). */
134
+ parametersFor(operation: OperationName): ExtensionParameter[];
135
+ /**
136
+ * Runs every `beforeWrite` hook in the order of the extensions; `params` holds the Parameters of every extension, and
137
+ * each hook gets its own.
138
+ */
139
+ beforeWrite(input: Omit<BeforeWriteInput, "params"> & {
140
+ readonly params?: Readonly<Record<string, unknown>>;
68
141
  }, ctx: HookCtx): Promise<Resource>;
142
+ /** Runs every `precondition` hook in the order of the extensions (D116). */
143
+ precondition(input: Omit<PreconditionInput, "params"> & {
144
+ readonly params?: Readonly<Record<string, unknown>>;
145
+ }, ctx: HookCtx): Promise<void>;
69
146
  /** Runs every `afterRead` hook in the order of the extensions. */
70
147
  afterRead(collection: string, resources: Resource[], ctx: HookCtx): Promise<Resource[]>;
71
148
  }
@@ -1,6 +1,14 @@
1
- // Extensions plugged into the engine (design section 7): the interface and the registry built at server construction.
2
1
  import { isSlug } from "./ids.js";
3
2
  import { CodeRegistry } from "./warnings.js";
3
+ /** The Parameters of `extension` found in `params`, by name. */
4
+ function paramsOf(extension, params) {
5
+ const own = {};
6
+ for (const parameter of extension.parameters ?? []) {
7
+ if (Object.hasOwn(params, parameter.name) && params[parameter.name] !== undefined)
8
+ own[parameter.name] = params[parameter.name];
9
+ }
10
+ return own;
11
+ }
4
12
  /**
5
13
  * Reserved Fields defined by the specifications of the family, with the extension that defines each one
6
14
  * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
@@ -28,7 +36,14 @@ export class ExtensionRegistry {
28
36
  throw new Error(`extension ${extension.name} is enabled twice`);
29
37
  names.add(extension.name);
30
38
  }
39
+ const parameters = new Map();
31
40
  for (const extension of extensions) {
41
+ for (const parameter of extension.parameters ?? []) {
42
+ const owner = parameters.get(parameter.name);
43
+ if (owner !== undefined)
44
+ throw new Error(`extensions ${owner} and ${extension.name} both define the Parameter ${parameter.name}`);
45
+ parameters.set(parameter.name, extension.name);
46
+ }
32
47
  for (const required of extension.requires ?? []) {
33
48
  if (!names.has(required))
34
49
  throw new Error(`extension ${extension.name} requires extension ${required}, which is not enabled`);
@@ -48,15 +63,31 @@ export class ExtensionRegistry {
48
63
  claimant(collection) {
49
64
  return this.list.find((e) => (e.reservedCollections ?? []).some((pattern) => matchesReserved(pattern, collection)));
50
65
  }
51
- /** Runs every `beforeWrite` hook in the order of the extensions. */
66
+ /** The Parameters of the enabled extensions that `operation` recognizes (D116). */
67
+ parametersFor(operation) {
68
+ return this.list.flatMap((e) => (e.parameters ?? []).filter((p) => p.operations.includes(operation)));
69
+ }
70
+ /**
71
+ * Runs every `beforeWrite` hook in the order of the extensions; `params` holds the Parameters of every extension, and
72
+ * each hook gets its own.
73
+ */
52
74
  async beforeWrite(input, ctx) {
75
+ const { params = {}, ...rest } = input;
53
76
  let next = input.next;
54
77
  for (const extension of this.list) {
55
78
  if (extension.beforeWrite !== undefined)
56
- next = await extension.beforeWrite({ ...input, next }, ctx);
79
+ next = await extension.beforeWrite({ ...rest, next, params: paramsOf(extension, params) }, ctx);
57
80
  }
58
81
  return next;
59
82
  }
83
+ /** Runs every `precondition` hook in the order of the extensions (D116). */
84
+ async precondition(input, ctx) {
85
+ const { params = {}, ...rest } = input;
86
+ for (const extension of this.list) {
87
+ if (extension.precondition !== undefined)
88
+ await extension.precondition({ ...rest, params: paramsOf(extension, params) }, ctx);
89
+ }
90
+ }
60
91
  /** Runs every `afterRead` hook in the order of the extensions. */
61
92
  async afterRead(collection, resources, ctx) {
62
93
  let current = resources;
@@ -1,19 +1,42 @@
1
- import type { Path } from "./types.ts";
2
- /** One item of a field list: a field path and whether it carries the `-` modifier (omit, or descending). */
3
- export interface FieldListItem {
4
- readonly path: Path;
1
+ import type { Path, SortPath } from "./types.ts";
2
+ /**
3
+ * One item of a field list: a field path and whether it carries the `-` modifier (omit, or descending). The path is a
4
+ * `SortPath`, with indexes, only for the Sorting Parameter (FIELD_LIST_NO_INDEX, SORTING_ARRAY_PATH).
5
+ */
6
+ export interface FieldListItem<P extends SortPath = Path> {
7
+ readonly path: P;
5
8
  readonly modifier: boolean;
6
9
  }
7
10
  export interface FieldListOptions {
8
11
  /** `target` of the `INVALID_INPUT` error, such as the name of the parameter (`fields`, `sort`). */
9
12
  readonly target?: string;
13
+ /**
14
+ * Accepts array indexes (UnQuery PATH_INDEX), as numbers in the path. Only the Sorting Parameter has them
15
+ * (FIELD_LIST_NO_INDEX, SORTING_ARRAY_PATH); default false: an index fails.
16
+ */
17
+ readonly indexes?: boolean;
10
18
  }
11
19
  /**
12
20
  * Reads a field list: text (FIELD_LIST_TEXT) or an array with one item per element (the JSON array form that
13
21
  * Protocols MAY use, with the same `-` convention; an unquoted `,` is allowed there since nothing is split).
14
22
  * `""` and `[]` are the empty list. Duplicate paths are kept as given. Failures are `INVALID_INPUT` errors with
15
- * rule FIELD_LIST_NO_INDEX (an index) or FIELD_LIST_PATHS (anything else, such as an empty item in `a,,b`).
23
+ * rule FIELD_LIST_NO_INDEX (an index, unless `options.indexes`) or FIELD_LIST_PATHS (anything else, such as an
24
+ * empty item in `a,,b`).
25
+ */
26
+ export declare function parseFieldList(input: string | readonly string[], options: FieldListOptions & {
27
+ readonly indexes: true;
28
+ }): FieldListItem<SortPath>[];
29
+ export declare function parseFieldList(input: string | readonly string[], options?: FieldListOptions & {
30
+ readonly indexes?: false;
31
+ }): FieldListItem[];
32
+ export declare function parseFieldList(input: string | readonly string[], options?: FieldListOptions): FieldListItem<SortPath>[];
33
+ /**
34
+ * Writes one field path as an item of a field list (FIELD_LIST_TEXT), without modifier; indexes as `[n]` (UnQuery
35
+ * PATH_INDEX). Throws UnQueryError for a path UnQuery rejects (PATH_DOT_NOTATION).
36
+ */
37
+ export declare function formatFieldPath(path: SortPath): string;
38
+ /**
39
+ * Writes a field list as text (FIELD_LIST_TEXT); `parseFieldList` reads it back to the same items (with
40
+ * `{ indexes: true }` when a path has indexes).
16
41
  */
17
- export declare function parseFieldList(input: string | readonly string[], options?: FieldListOptions): FieldListItem[];
18
- /** Writes a field list as text (FIELD_LIST_TEXT); `parseFieldList` reads it back to the same items. */
19
- export declare function formatFieldList(items: readonly FieldListItem[]): string;
42
+ export declare function formatFieldList(items: readonly FieldListItem<SortPath>[]): string;
@@ -73,17 +73,12 @@ function parseItem(text, options) {
73
73
  }
74
74
  // FIELD_LIST_NO_INDEX: array indexes (UnQuery PATH_INDEX) are not defined in field lists. A segment made
75
75
  // of digits (`items.0`) is a field name (PATH_NUMERIC_SEGMENT), not an index.
76
- if (elements.some((element) => typeof element === "number")) {
76
+ // FIELD_LIST_NO_INDEX: indexes only in the Sorting Parameter (SORTING_ARRAY_PATH).
77
+ if (options.indexes !== true && elements.some((element) => typeof element === "number")) {
77
78
  throw invalid("FIELD_LIST_NO_INDEX", `field list items must not have array indexes: ${JSON.stringify(pathText)}`, options);
78
79
  }
79
80
  return { path: elements, modifier };
80
81
  }
81
- /**
82
- * Reads a field list: text (FIELD_LIST_TEXT) or an array with one item per element (the JSON array form that
83
- * Protocols MAY use, with the same `-` convention; an unquoted `,` is allowed there since nothing is split).
84
- * `""` and `[]` are the empty list. Duplicate paths are kept as given. Failures are `INVALID_INPUT` errors with
85
- * rule FIELD_LIST_NO_INDEX (an index) or FIELD_LIST_PATHS (anything else, such as an empty item in `a,,b`).
86
- */
87
82
  export function parseFieldList(input, options = {}) {
88
83
  if (typeof input === "string")
89
84
  return input === "" ? [] : splitItems(input).map((item) => parseItem(item, options));
@@ -97,12 +92,25 @@ function formatSegment(segment) {
97
92
  const needsQuotes = /[.,"[\]]/.test(segment) || segment.startsWith(HYPHEN);
98
93
  return needsQuotes ? DQUOTE + segment.replaceAll(DQUOTE, DQUOTE + DQUOTE) + DQUOTE : segment;
99
94
  }
100
- /** Writes a field list as text (FIELD_LIST_TEXT); `parseFieldList` reads it back to the same items. */
95
+ /**
96
+ * Writes one field path as an item of a field list (FIELD_LIST_TEXT), without modifier; indexes as `[n]` (UnQuery
97
+ * PATH_INDEX). Throws UnQueryError for a path UnQuery rejects (PATH_DOT_NOTATION).
98
+ */
99
+ export function formatFieldPath(path) {
100
+ formatPath(path); // validates the path (PATH_DOT_NOTATION, PATH_INDEX); throws UnQueryError otherwise
101
+ let text = "";
102
+ for (const element of path) {
103
+ if (typeof element === "number")
104
+ text += `[${element}]`;
105
+ else
106
+ text += (text === "" ? "" : DOT) + formatSegment(element);
107
+ }
108
+ return text;
109
+ }
110
+ /**
111
+ * Writes a field list as text (FIELD_LIST_TEXT); `parseFieldList` reads it back to the same items (with
112
+ * `{ indexes: true }` when a path has indexes).
113
+ */
101
114
  export function formatFieldList(items) {
102
- return items
103
- .map((item) => {
104
- formatPath(item.path); // validates the path (PATH_DOT_NOTATION); throws UnQueryError otherwise
105
- return (item.modifier ? HYPHEN : "") + item.path.map(formatSegment).join(DOT);
106
- })
107
- .join(COMMA);
115
+ return items.map((item) => (item.modifier ? HYPHEN : "") + formatFieldPath(item.path)).join(COMMA);
108
116
  }
package/dist/ids.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  import { type Codec } from "@ecson/core";
2
2
  import type { IdKind, KeySpec, Path, Resource, ResourceId } from "./types.ts";
3
- /** ID_SLUG: a Slug of section 2.6, `^[a-zA-Z0-9_-]+$`. */
3
+ /** A Slug of section 2.6, `^[a-zA-Z0-9_-]+$`: recommended for Resource IDs (ID_SLUG), required for Collections (COLLECTION_SLUG). */
4
4
  export declare function isSlug(text: string): boolean;
5
+ /**
6
+ * ID_STRING: a simple Resource ID is a non-empty string without control characters (Unicode `Cc`, U+0000 to U+001F
7
+ * and U+007F to U+009F); spaces, `@`, `=`, `&` and letters outside ASCII are allowed. A string with a lone surrogate
8
+ * is not text (it has no UTF-8 encoding, so no Protocol can carry it) and is refused too (D113).
9
+ */
10
+ export declare function isIdString(value: unknown): value is string;
5
11
  /** `uuid-hex`: the standard string format of RFC 9562 section 4, lowercase with hyphens (any version and variant). */
6
12
  export declare function isUuidHex(text: string): boolean;
7
13
  /**
@@ -14,8 +20,9 @@ export declare function uuidHexToBase64url(uuid: string): string;
14
20
  /** ID_UUID_BASE64URL: `uuid-base64url` to `uuid-hex`; fails with INVALID_INPUT when the text is not `uuid-base64url`. */
15
21
  export declare function uuidBase64urlToHex(text: string): string;
16
22
  /**
17
- * The ID kinds (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG) a text belongs to, most specific first.
18
- * Both UUID formats are Slugs, so a UUID text is always also `slug`; a text that is not a Slug has no kind.
23
+ * The ID kinds (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG, ID_STRING) a text belongs to, most specific first.
24
+ * Both UUID formats are Slugs and every Slug is a valid string, so a UUID text is always also `slug` and `string`; a
25
+ * text that is not a valid Resource ID (ID_INVALID) has no kind (D113).
19
26
  */
20
27
  export declare function idKindOf(id: string): IdKind[];
21
28
  /** Whether a text is an ID of the given kind (see `idKindOf`). */
@@ -67,7 +74,9 @@ export declare function setKey(resource: Resource, key: KeySpec, id: ResourceId,
67
74
  */
68
75
  export declare function stripKey(resource: Resource, key: KeySpec): Resource;
69
76
  /**
70
- * ID_SLUG: a Resource ID of the `_id` key must be a Slug; ID_COMP_KEY_URLENCODED: a composite Resource ID must be
71
- * the urlencoded pairs of the key paths. Fails with INVALID_INPUT otherwise. `options.codec` as in `parseCompositeId`.
77
+ * ID_INVALID: a Resource ID of the `_id` key must be a valid string (ID_STRING; a Slug is only recommended, ID_SLUG);
78
+ * a composite Resource ID must be the urlencoded pairs of the key paths (ID_COMP_KEY_URLENCODED). Which of the two
79
+ * applies is decided by the key alone, never by the text (ID_COMP_KEY_TEXT): `a=1&b=2` is one string for an `_id`
80
+ * key. Fails with INVALID_INPUT otherwise. `options.codec` as in `parseCompositeId`.
72
81
  */
73
- export declare function assertValidId(id: ResourceId, key: KeySpec, options?: IdOptions): void;
82
+ export declare function assertValidId(id: unknown, key: KeySpec, options?: IdOptions): asserts id is ResourceId;
package/dist/ids.js CHANGED
@@ -10,10 +10,20 @@ const UUID_HEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
10
10
  // so it is one of the characters whose alphabet index is a multiple of 16.
11
11
  const UUID_BASE64URL = /^[A-Za-z0-9_-]{21}[AQgw]$/;
12
12
  const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
13
- /** ID_SLUG: a Slug of section 2.6, `^[a-zA-Z0-9_-]+$`. */
13
+ /** A Slug of section 2.6, `^[a-zA-Z0-9_-]+$`: recommended for Resource IDs (ID_SLUG), required for Collections (COLLECTION_SLUG). */
14
14
  export function isSlug(text) {
15
15
  return SLUG.test(text);
16
16
  }
17
+ // Unicode general category Cc: C0 controls, DEL and C1 controls.
18
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
19
+ /**
20
+ * ID_STRING: a simple Resource ID is a non-empty string without control characters (Unicode `Cc`, U+0000 to U+001F
21
+ * and U+007F to U+009F); spaces, `@`, `=`, `&` and letters outside ASCII are allowed. A string with a lone surrogate
22
+ * is not text (it has no UTF-8 encoding, so no Protocol can carry it) and is refused too (D113).
23
+ */
24
+ export function isIdString(value) {
25
+ return typeof value === "string" && value !== "" && !CONTROL.test(value) && value.isWellFormed();
26
+ }
17
27
  /** `uuid-hex`: the standard string format of RFC 9562 section 4, lowercase with hyphens (any version and variant). */
18
28
  export function isUuidHex(text) {
19
29
  return UUID_HEX.test(text);
@@ -88,18 +98,21 @@ export function uuidBase64urlToHex(text) {
88
98
  return bytesToHex(base64urlToBytes(text));
89
99
  }
90
100
  /**
91
- * The ID kinds (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG) a text belongs to, most specific first.
92
- * Both UUID formats are Slugs, so a UUID text is always also `slug`; a text that is not a Slug has no kind.
101
+ * The ID kinds (SUB_WITH_IDS, ID_UUID, ID_UUID_BASE64URL, ID_SLUG, ID_STRING) a text belongs to, most specific first.
102
+ * Both UUID formats are Slugs and every Slug is a valid string, so a UUID text is always also `slug` and `string`; a
103
+ * text that is not a valid Resource ID (ID_INVALID) has no kind (D113).
93
104
  */
94
105
  export function idKindOf(id) {
95
- if (!isSlug(id))
106
+ if (!isIdString(id))
96
107
  return [];
97
108
  const kinds = [];
98
109
  if (isUuidHex(id))
99
110
  kinds.push("uuid-hex");
100
111
  if (isUuidBase64url(id))
101
112
  kinds.push("uuid-base64url");
102
- kinds.push("slug");
113
+ if (isSlug(id))
114
+ kinds.push("slug");
115
+ kinds.push("string");
103
116
  return kinds;
104
117
  }
105
118
  /** Whether a text is an ID of the given kind (see `idKindOf`). */
@@ -111,6 +124,8 @@ export function matchesKind(id, kind) {
111
124
  return isUuidBase64url(id);
112
125
  case "slug":
113
126
  return isSlug(id);
127
+ case "string":
128
+ return isIdString(id);
114
129
  }
115
130
  }
116
131
  // ---------------------------------------------------------------------------------------------------------------
@@ -376,16 +391,31 @@ export function stripKey(resource, key) {
376
391
  return result === resource ? { ...resource } : result;
377
392
  }
378
393
  /**
379
- * ID_SLUG: a Resource ID of the `_id` key must be a Slug; ID_COMP_KEY_URLENCODED: a composite Resource ID must be
380
- * the urlencoded pairs of the key paths. Fails with INVALID_INPUT otherwise. `options.codec` as in `parseCompositeId`.
394
+ * ID_INVALID: a Resource ID of the `_id` key must be a valid string (ID_STRING; a Slug is only recommended, ID_SLUG);
395
+ * a composite Resource ID must be the urlencoded pairs of the key paths (ID_COMP_KEY_URLENCODED). Which of the two
396
+ * applies is decided by the key alone, never by the text (ID_COMP_KEY_TEXT): `a=1&b=2` is one string for an `_id`
397
+ * key. Fails with INVALID_INPUT otherwise. `options.codec` as in `parseCompositeId`.
381
398
  */
382
399
  export function assertValidId(id, key, options = {}) {
383
400
  if (key.kind === "id") {
384
- if (typeof id !== "string" || !isSlug(id))
385
- throw invalid(`"${String(id)}" is not a Slug`, "ID_SLUG");
401
+ if (!isIdString(id))
402
+ throw invalid(`${describeInvalid(id)} is not a valid Resource ID`, "ID_INVALID");
386
403
  return;
387
404
  }
388
405
  if (typeof id !== "string")
389
- throw invalid(`"${String(id)}" is not a composite Resource ID`, "ID_COMP_KEY_URLENCODED");
406
+ throw invalid(`${describeInvalid(id)} is not a composite Resource ID`, "ID_COMP_KEY_URLENCODED");
390
407
  parseCompositeId(id, key.paths, options);
391
408
  }
409
+ /** An invalid Resource ID for an error message: JSON text when it has one (control characters escaped). */
410
+ function describeInvalid(id) {
411
+ if (typeof id === "string" && id === "")
412
+ return "the empty string";
413
+ if (typeof id === "string" && !id.isWellFormed())
414
+ return "a string with a lone surrogate";
415
+ try {
416
+ return JSON.stringify(id) ?? String(id);
417
+ }
418
+ catch {
419
+ return typeof id === "bigint" ? `${id}n` : "the value"; // bigint, cycles
420
+ }
421
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  export { conformance } from "./conformance.ts";
2
2
  export { ID_KEY, OPERATIONS } from "./types.ts";
3
- export type { IdKind, KeySpec, OperationName, Page, Path, Projection, Representation, Resource, ResourceId, SortKey } from "./types.ts";
3
+ export type { IdKind, KeySpec, OperationName, Page, Path, Projection, Representation, Resource, ResourceId, SortKey, SortPath } from "./types.ts";
4
4
  export { BASE_ERROR_CODES, CrudError, isNamespacedCode, toProblemDetails } from "./errors.ts";
5
5
  export type { CrudErrorOptions, ErrorData, ProblemDetails } from "./errors.ts";
6
- export { allows, BASE_WARNING_CODES, CodeRegistry, LENIENT, strictPolicy, WarningSink } from "./warnings.ts";
6
+ export { allows, BASE_WARNING_CODES, CodeRegistry, isWarningMemberName, LENIENT, strictPolicy, WarningSink } from "./warnings.ts";
7
7
  export type { StrictPreference, Warning } from "./warnings.ts";
8
8
  export type { CollectionInfo, Ctx, ExecCtx, Prepared, PrepareCtx, PrimitiveRequest, PrimitiveResult, Provider, ProviderCapabilities, ProviderTx, TestHarness, } from "./provider.ts";
9
9
  export { assertOperators, mapUnQueryError, parseSearchQuery, UNQUERY_JSON, UNQUERY_SQL } from "./query.ts";
@@ -12,20 +12,22 @@ export { negotiateQueryFormat, negotiateRepresentation, negotiateSpecs, formatSp
12
12
  export type { Accepted } from "./negotiation.ts";
13
13
  export { isPaginationRequested, normalizePagination } from "./pagination.ts";
14
14
  export type { PaginationCaps, PaginationInput } from "./pagination.ts";
15
- export { assertValidId, createUuidV7, formatCompositeId, idKindOf, idOf, isSlug, isUuidBase64url, isUuidHex, matchesKind, parseCompositeId, setKey, stripKey, uuidBase64urlToHex, uuidHexToBase64url } from "./ids.ts";
15
+ export { assertValidId, createUuidV7, formatCompositeId, idKindOf, idOf, isIdString, isSlug, isUuidBase64url, isUuidHex, matchesKind, parseCompositeId, setKey, stripKey, uuidBase64urlToHex, uuidHexToBase64url } from "./ids.ts";
16
16
  export type { IdOptions } from "./ids.ts";
17
- export { formatFieldList, parseFieldList } from "./field-list.ts";
17
+ export { formatFieldList, formatFieldPath, parseFieldList } from "./field-list.ts";
18
18
  export type { FieldListItem, FieldListOptions } from "./field-list.ts";
19
19
  export { applyProjection, keyPaths, normalizeProjection, samePath } from "./projection.ts";
20
- export { compareResources, compareSortValues, getPath, sortKeys } from "./sorting.ts";
20
+ export { compareResources, compareSortValues, crossesArray, getPath, sortArrayPathWarning, sortArrayPathWarnings, sortKeys } from "./sorting.ts";
21
21
  export type { SortOptions } from "./sorting.ts";
22
22
  export { assertWritableDepth, DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.ts";
23
- export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.ts";
23
+ export { downgrade, tagOf } from "./downgrade.ts";
24
+ export type { Downgraded } from "./downgrade.ts";
25
+ export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.ts";
24
26
  export { createCrudServer, BASE_SPEC } from "./server.ts";
25
27
  export type { CrudServer, CrudServerOptions, ProtocolRegistration, ServerDescription } from "./server.ts";
26
28
  export type { OperationRequest, OperationResult, ResultMeta } from "./operation.ts";
27
29
  export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.ts";
28
- export type { Extension, HookCtx } from "./extensions.ts";
30
+ export type { BeforeWriteInput, Extension, ExtensionParameter, ExtensionParams, HookCtx, PreconditionInput } from "./extensions.ts";
29
31
  export { atomicity, decideWriteMode } from "./write-policy.ts";
30
32
  export type { Atomicity, WriteMode, WritePolicyInput } from "./write-policy.ts";
31
33
  export { assertClientId, assertNoStrayId, assertResource, assertSubjectId, canonicalId, checkFieldNames, dropReservedChanges, dropReservedFields, keyIsTopLevel } from "./subject.ts";
package/dist/index.js CHANGED
@@ -1,16 +1,17 @@
1
1
  export { conformance } from "./conformance.js";
2
2
  export { ID_KEY, OPERATIONS } from "./types.js";
3
3
  export { BASE_ERROR_CODES, CrudError, isNamespacedCode, toProblemDetails } from "./errors.js";
4
- export { allows, BASE_WARNING_CODES, CodeRegistry, LENIENT, strictPolicy, WarningSink } from "./warnings.js";
4
+ export { allows, BASE_WARNING_CODES, CodeRegistry, isWarningMemberName, LENIENT, strictPolicy, WarningSink } from "./warnings.js";
5
5
  export { assertOperators, mapUnQueryError, parseSearchQuery, UNQUERY_JSON, UNQUERY_SQL } from "./query.js";
6
6
  export { negotiateQueryFormat, negotiateRepresentation, negotiateSpecs, formatSpecList, parseSpecList } from "./negotiation.js";
7
7
  export { isPaginationRequested, normalizePagination } from "./pagination.js";
8
- export { assertValidId, createUuidV7, formatCompositeId, idKindOf, idOf, isSlug, isUuidBase64url, isUuidHex, matchesKind, parseCompositeId, setKey, stripKey, uuidBase64urlToHex, uuidHexToBase64url } from "./ids.js";
9
- export { formatFieldList, parseFieldList } from "./field-list.js";
8
+ export { assertValidId, createUuidV7, formatCompositeId, idKindOf, idOf, isIdString, isSlug, isUuidBase64url, isUuidHex, matchesKind, parseCompositeId, setKey, stripKey, uuidBase64urlToHex, uuidHexToBase64url } from "./ids.js";
9
+ export { formatFieldList, formatFieldPath, parseFieldList } from "./field-list.js";
10
10
  export { applyProjection, keyPaths, normalizeProjection, samePath } from "./projection.js";
11
- export { compareResources, compareSortValues, getPath, sortKeys } from "./sorting.js";
11
+ export { compareResources, compareSortValues, crossesArray, getPath, sortArrayPathWarning, sortArrayPathWarnings, sortKeys } from "./sorting.js";
12
12
  export { assertWritableDepth, DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.js";
13
- export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
13
+ export { downgrade, tagOf } from "./downgrade.js";
14
+ export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
14
15
  export { createCrudServer, BASE_SPEC } from "./server.js";
15
16
  export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.js";
16
17
  export { atomicity, decideWriteMode } from "./write-policy.js";