@crud-api/core 0.1.1 → 0.2.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 +3 -2
- package/dist/field-list.d.ts +31 -8
- package/dist/field-list.js +22 -14
- package/dist/ids.d.ts +15 -6
- package/dist/ids.js +40 -10
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/operation.js +10 -7
- package/dist/patch.d.ts +16 -2
- package/dist/patch.js +29 -2
- package/dist/projection.d.ts +3 -3
- package/dist/projection.js +1 -1
- package/dist/provider.d.ts +6 -0
- package/dist/sorting.d.ts +21 -10
- package/dist/sorting.js +62 -10
- package/dist/subject.d.ts +7 -3
- package/dist/subject.js +10 -10
- package/dist/types.d.ts +11 -5
- package/dist/warnings.d.ts +9 -1
- package/dist/warnings.js +22 -2
- package/package.json +1 -1
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
|
|
package/dist/field-list.d.ts
CHANGED
|
@@ -1,19 +1,42 @@
|
|
|
1
|
-
import type { Path } from "./types.ts";
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
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
|
|
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
|
|
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;
|
package/dist/field-list.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
|
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
|
-
*
|
|
71
|
-
* the urlencoded pairs of the key paths
|
|
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:
|
|
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
|
-
/**
|
|
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
|
|
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 (!
|
|
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
|
-
|
|
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
|
-
*
|
|
380
|
-
* the urlencoded pairs of the key paths
|
|
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 (
|
|
385
|
-
throw invalid(
|
|
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(
|
|
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,15 +12,15 @@ 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 { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.ts";
|
|
24
24
|
export { createCrudServer, BASE_SPEC } from "./server.ts";
|
|
25
25
|
export type { CrudServer, CrudServerOptions, ProtocolRegistration, ServerDescription } from "./server.ts";
|
|
26
26
|
export type { OperationRequest, OperationResult, ResultMeta } from "./operation.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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 { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
|
|
14
14
|
export { createCrudServer, BASE_SPEC } from "./server.js";
|
|
15
15
|
export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.js";
|
|
16
16
|
export { atomicity, decideWriteMode } from "./write-policy.js";
|
package/dist/operation.js
CHANGED
|
@@ -3,7 +3,7 @@ import { and } from "@unquery/core";
|
|
|
3
3
|
import { DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.js";
|
|
4
4
|
import { CrudError } from "./errors.js";
|
|
5
5
|
import { parseFieldList } from "./field-list.js";
|
|
6
|
-
import { isSlug, idOf, setKey, stripKey } from "./ids.js";
|
|
6
|
+
import { assertValidId, isSlug, idOf, setKey, stripKey } from "./ids.js";
|
|
7
7
|
import { negotiateQueryFormat, negotiateRepresentation, negotiateSpecs } from "./negotiation.js";
|
|
8
8
|
import { normalizePagination } from "./pagination.js";
|
|
9
9
|
import { isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
|
|
@@ -69,7 +69,8 @@ function parseParams(server, ctx, params) {
|
|
|
69
69
|
let sort = sortKeys(null, ctx.key);
|
|
70
70
|
let page = null;
|
|
71
71
|
if (ctx.operation === "list") {
|
|
72
|
-
|
|
72
|
+
// FIELD_LIST_NO_INDEX: the Sorting Parameter is the field list that may have indexes (SORTING_ARRAY_PATH).
|
|
73
|
+
const items = has("sort") ? parseFieldList(input.sort, { target: "sort", indexes: true }) : null;
|
|
73
74
|
// SORTING_NULLS (design 6.5): a provider that cannot order null and missing lowest cannot sort at all.
|
|
74
75
|
if (items !== null && items.length > 0 && (!ctx.caps.sort.fields || !ctx.caps.sort.nullsLowest)) {
|
|
75
76
|
throw new CrudError("UNSUPPORTED", "this Collection cannot be sorted by Fields", { rule: "SORTING_NULLS" });
|
|
@@ -166,7 +167,7 @@ function checkSubject(ctx) {
|
|
|
166
167
|
for (const resource of resources) {
|
|
167
168
|
if (key.kind === "id") {
|
|
168
169
|
if (keyPresent(resource, key))
|
|
169
|
-
assertClientId(resource._id, info, ctx.caps); // SUB_WITH_IDS, RES_NO_IDS
|
|
170
|
+
assertClientId(resource._id, info, ctx.caps); // ID_INVALID, SUB_WITH_IDS, RES_NO_IDS
|
|
170
171
|
}
|
|
171
172
|
else if (idOf(resource, key, opts) === undefined) {
|
|
172
173
|
throw new CrudError("INVALID_INPUT", "every Field of the composite key must have a value", { rule: "ID_COMP_KEY" });
|
|
@@ -190,9 +191,8 @@ function checkSubject(ctx) {
|
|
|
190
191
|
case "replaceById": {
|
|
191
192
|
let resource = checkResource(ctx, request.resource, "SUB_RESOURCE_REPLACE");
|
|
192
193
|
// SUB_ID_REPLACE: the Resource ID inside the replacement or separately; both present and different fail.
|
|
193
|
-
if (key.kind === "id" && keyPresent(resource, key)
|
|
194
|
-
|
|
195
|
-
}
|
|
194
|
+
if (key.kind === "id" && keyPresent(resource, key))
|
|
195
|
+
assertValidId(resource._id, key); // ID_INVALID
|
|
196
196
|
const inside = idOf(resource, key, opts);
|
|
197
197
|
if (inside === undefined && keyPresent(resource, key)) {
|
|
198
198
|
throw new CrudError("INVALID_INPUT", "the replacement has only part of the composite key", { rule: "SUB_ID_REPLACE" });
|
|
@@ -215,8 +215,11 @@ function checkSubject(ctx) {
|
|
|
215
215
|
case "replaceByQuery": {
|
|
216
216
|
let resource = checkResource(ctx, request.resource, "SUB_RESOURCE_REPLACE");
|
|
217
217
|
if (keyPresent(resource, key)) {
|
|
218
|
+
// ID_INVALID: even an ignored Resource ID must be valid, as any Resource ID an operation receives (D113).
|
|
219
|
+
if (key.kind === "id")
|
|
220
|
+
assertValidId(resource._id, key);
|
|
218
221
|
// SUB_NO_ID: the Resource ID of the replacement is ignored, with ID_IGNORED (reported once, D61).
|
|
219
|
-
const id = idOf(resource, key, opts) ??
|
|
222
|
+
const id = idOf(resource, key, opts) ?? "";
|
|
220
223
|
resource = stripKey(resource, key);
|
|
221
224
|
ctx.sink.warn({ code: "ID_IGNORED", message: "the Resource ID of the replacement was ignored: each matched Resource keeps its own", id });
|
|
222
225
|
}
|
package/dist/patch.d.ts
CHANGED
|
@@ -19,6 +19,19 @@ export declare function applyJsonPatch(doc: Resource, ops: unknown): Resource;
|
|
|
19
19
|
* without applying it, so that the engine can fail with `INVALID_PATCH` before reading anything.
|
|
20
20
|
*/
|
|
21
21
|
export declare function validateJsonPatch(ops: unknown): void;
|
|
22
|
+
/**
|
|
23
|
+
* A patch read as ECSON (MCP_ARGS_ECSON, HTTP_PATCH_ECSON): the whole Merge Patch document, and the `value` member of
|
|
24
|
+
* each JSON Patch operation that has one, go through `decode` (the Server's codec, with the adapter's own errors);
|
|
25
|
+
* other members stay as they are. The shape is left to SUB_JSON_PATCH and SUB_MERGE_PATCH, so a patch of the wrong
|
|
26
|
+
* shape is returned as it is and fails there (D115).
|
|
27
|
+
*/
|
|
28
|
+
export declare function decodePatch<P extends {
|
|
29
|
+
type: "json-patch";
|
|
30
|
+
ops: unknown;
|
|
31
|
+
} | {
|
|
32
|
+
type: "merge-patch";
|
|
33
|
+
doc: unknown;
|
|
34
|
+
}>(patch: P, decode: (tree: unknown, what: string) => unknown): P;
|
|
22
35
|
/** SUB_MERGE_PATCH: a Merge Patch for a Resource must be an object (S03); `INVALID_PATCH` otherwise. */
|
|
23
36
|
export declare function validateMergePatch(patch: unknown): void;
|
|
24
37
|
/**
|
|
@@ -30,8 +43,9 @@ export declare function validateMergePatch(patch: unknown): void;
|
|
|
30
43
|
export declare function applyMergePatch(doc: Resource, patch: unknown): Resource;
|
|
31
44
|
/**
|
|
32
45
|
* PATCH_NO_ID, ID_COMP_KEY_FIELDS: a patch must not change the Resource ID: `_id`, or every Field
|
|
33
|
-
* of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH
|
|
34
|
-
*
|
|
46
|
+
* of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`;
|
|
47
|
+
* setting `_id` to an invalid Resource ID fails `INVALID_INPUT` first (ID_INVALID covers a Resource ID
|
|
48
|
+
* in a patch, D113). Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
|
|
35
49
|
*/
|
|
36
50
|
export declare function assertKeyUnchanged(before: Resource, after: Resource, key: KeySpec): void;
|
|
37
51
|
export {};
|
package/dist/patch.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// bytes, UnknownTag, Temporal, ...) is a leaf value: a pointer cannot go inside it.
|
|
4
4
|
import { formatPath, valuesEqual } from "@unquery/core";
|
|
5
5
|
import { CrudError } from "./errors.js";
|
|
6
|
+
import { assertValidId } from "./ids.js";
|
|
6
7
|
/** True for plain objects (prototype `Object.prototype` or `null`): the only objects a pointer can enter. */
|
|
7
8
|
export function isPlainObject(value) {
|
|
8
9
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
@@ -230,6 +231,29 @@ export function applyJsonPatch(doc, ops) {
|
|
|
230
231
|
export function validateJsonPatch(ops) {
|
|
231
232
|
validate(ops);
|
|
232
233
|
}
|
|
234
|
+
// ---- Patches read as ECSON ----
|
|
235
|
+
/**
|
|
236
|
+
* A patch read as ECSON (MCP_ARGS_ECSON, HTTP_PATCH_ECSON): the whole Merge Patch document, and the `value` member of
|
|
237
|
+
* each JSON Patch operation that has one, go through `decode` (the Server's codec, with the adapter's own errors);
|
|
238
|
+
* other members stay as they are. The shape is left to SUB_JSON_PATCH and SUB_MERGE_PATCH, so a patch of the wrong
|
|
239
|
+
* shape is returned as it is and fails there (D115).
|
|
240
|
+
*/
|
|
241
|
+
export function decodePatch(patch, decode) {
|
|
242
|
+
if (patch.type === "merge-patch")
|
|
243
|
+
return { ...patch, doc: decode(patch.doc, "the patch") };
|
|
244
|
+
if (!Array.isArray(patch.ops))
|
|
245
|
+
return patch;
|
|
246
|
+
const ops = patch.ops.map((op) => {
|
|
247
|
+
if (!isPlainObject(op) || !Object.hasOwn(op, "value"))
|
|
248
|
+
return op;
|
|
249
|
+
const copy = {};
|
|
250
|
+
for (const [key, value] of Object.entries(op))
|
|
251
|
+
define(copy, key, value);
|
|
252
|
+
copy.value = decode(op.value, "the value of a patch operation");
|
|
253
|
+
return copy;
|
|
254
|
+
});
|
|
255
|
+
return { ...patch, ops };
|
|
256
|
+
}
|
|
233
257
|
// ---- JSON Merge Patch (RFC 7396) ----
|
|
234
258
|
/** SUB_MERGE_PATCH: a Merge Patch for a Resource must be an object (S03); `INVALID_PATCH` otherwise. */
|
|
235
259
|
export function validateMergePatch(patch) {
|
|
@@ -281,8 +305,9 @@ function valueAt(resource, path) {
|
|
|
281
305
|
}
|
|
282
306
|
/**
|
|
283
307
|
* PATCH_NO_ID, ID_COMP_KEY_FIELDS: a patch must not change the Resource ID: `_id`, or every Field
|
|
284
|
-
* of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH
|
|
285
|
-
*
|
|
308
|
+
* of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`;
|
|
309
|
+
* setting `_id` to an invalid Resource ID fails `INVALID_INPUT` first (ID_INVALID covers a Resource ID
|
|
310
|
+
* in a patch, D113). Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
|
|
286
311
|
*/
|
|
287
312
|
export function assertKeyUnchanged(before, after, key) {
|
|
288
313
|
const paths = key.kind === "id" ? [["_id"]] : key.paths;
|
|
@@ -292,6 +317,8 @@ export function assertKeyUnchanged(before, after, key) {
|
|
|
292
317
|
// Both missing counts as unchanged (nothing to protect); present on one side only is a change.
|
|
293
318
|
if (a === MISSING && b === MISSING)
|
|
294
319
|
continue;
|
|
320
|
+
if (key.kind === "id" && b !== MISSING && !valuesEqual(a, b))
|
|
321
|
+
assertValidId(b, key); // ID_INVALID
|
|
295
322
|
if (a === MISSING || b === MISSING || !valuesEqual(a, b)) {
|
|
296
323
|
throw new CrudError("INVALID_PATCH", `the patch changes the Resource ID (${formatPath(path)})`, { rule: "PATCH_NO_ID" });
|
|
297
324
|
}
|
package/dist/projection.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { FieldListItem } from "./field-list.ts";
|
|
2
|
-
import type { KeySpec, Path, Projection, Resource } from "./types.ts";
|
|
2
|
+
import type { KeySpec, Path, Projection, Resource, SortPath } from "./types.ts";
|
|
3
3
|
/** The field paths that hold the Resource ID: `_id` (ID_KEY) or the composite key paths in key order (ID_COMP_KEY_FIELDS). */
|
|
4
4
|
export declare function keyPaths(key: KeySpec): readonly Path[];
|
|
5
|
-
/** Two field paths are the same when every segment is the same. */
|
|
6
|
-
export declare function samePath(a:
|
|
5
|
+
/** Two field paths are the same when every segment (or index, in a `SortPath`) is the same. */
|
|
6
|
+
export declare function samePath(a: SortPath, b: SortPath): boolean;
|
|
7
7
|
/**
|
|
8
8
|
* Normalizes a Projection Parameter (PROJECTION_FIELD_LIST: the `-` modifier omits): `include` is the listed
|
|
9
9
|
* paths, or null when none is listed (PROJECTION_EXCLUDE); `exclude` is the omitted paths, removed after the
|
package/dist/projection.js
CHANGED
|
@@ -5,7 +5,7 @@ const ID_PATH = Object.freeze(["_id"]);
|
|
|
5
5
|
export function keyPaths(key) {
|
|
6
6
|
return key.kind === "id" ? [ID_PATH] : key.paths;
|
|
7
7
|
}
|
|
8
|
-
/** Two field paths are the same when every segment is the same. */
|
|
8
|
+
/** Two field paths are the same when every segment (or index, in a `SortPath`) is the same. */
|
|
9
9
|
export function samePath(a, b) {
|
|
10
10
|
return a.length === b.length && a.every((segment, i) => segment === b[i]);
|
|
11
11
|
}
|
package/dist/provider.d.ts
CHANGED
|
@@ -81,6 +81,12 @@ export type PrimitiveRequest = {
|
|
|
81
81
|
readonly format: string;
|
|
82
82
|
readonly text: string;
|
|
83
83
|
};
|
|
84
|
+
/**
|
|
85
|
+
* The sort keys, whose paths may have indexes. SORTING_ARRAY_PATH (D112): `getPath` and `compareResources`
|
|
86
|
+
* read them as the rule says; the provider reports `SORT_ARRAY_PATH` in `execute` for each key path that crosses
|
|
87
|
+
* an array in a matched Resource (`sortArrayPathWarnings` over every matched Resource, not only the page), or
|
|
88
|
+
* fails in `prepare` (UNSUPPORTED) when it cannot sort so.
|
|
89
|
+
*/
|
|
84
90
|
readonly sort: readonly SortKey[];
|
|
85
91
|
readonly projection: Projection | null;
|
|
86
92
|
readonly page: Page;
|
package/dist/sorting.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Codec } from "@ecson/core";
|
|
2
|
-
import type
|
|
3
|
-
import type { KeySpec,
|
|
2
|
+
import { type FieldListItem } from "./field-list.ts";
|
|
3
|
+
import type { KeySpec, Resource, SortKey, SortPath } from "./types.ts";
|
|
4
|
+
import type { Warning } from "./warnings.ts";
|
|
4
5
|
/**
|
|
5
6
|
* Options of the comparators. `codec` is the ECSON codec of the Server, built with `createCodec` from the type sets of
|
|
6
7
|
* the enabled extensions (design 6.4), so extension host values (`Rel` of the References type set, `ObjectId` of
|
|
@@ -14,9 +15,9 @@ export interface SortOptions {
|
|
|
14
15
|
* Sort keys of a `list` operation (SORTING_FIELD_LIST: the `-` modifier means descending). SORTING_DEFAULT: the
|
|
15
16
|
* Resource ID is added as the last key, ascending: `_id`, or each composite key path in key order
|
|
16
17
|
* (ID_COMP_KEY_FIELDS), unless the path is already a key. Without a Sorting Parameter (null or empty), the
|
|
17
|
-
* keys are the Resource ID alone.
|
|
18
|
+
* keys are the Resource ID alone. Paths may have indexes (SORTING_ARRAY_PATH: `parseFieldList` with `{ indexes: true }`).
|
|
18
19
|
*/
|
|
19
|
-
export declare function sortKeys(items: readonly FieldListItem[] | null, key: KeySpec): SortKey[];
|
|
20
|
+
export declare function sortKeys(items: readonly FieldListItem<SortPath>[] | null, key: KeySpec): SortKey[];
|
|
20
21
|
/**
|
|
21
22
|
* The total order of sorted values (SORTING_NULLS, SORTING_TYPES, SORTING_SAME_TYPE): -1, 0 or 1. `null`, missing
|
|
22
23
|
* (`MISSING`) and `undefined` are the lowest and equal among themselves; then numbers, strings, objects, arrays,
|
|
@@ -25,14 +26,24 @@ export declare function sortKeys(items: readonly FieldListItem[] | null, key: Ke
|
|
|
25
26
|
*/
|
|
26
27
|
export declare function compareSortValues(a: unknown, b: unknown, options?: SortOptions): number;
|
|
27
28
|
/**
|
|
28
|
-
* The value at a field path of a Resource, or `MISSING
|
|
29
|
-
*
|
|
30
|
-
*
|
|
29
|
+
* The value at a field path of a Resource, or `MISSING`, as sorting reads it (SORTING_ARRAY_PATH, D112): names follow
|
|
30
|
+
* own properties of plain objects, indexes select array elements (`MISSING` on a non-array or out of range), and a
|
|
31
|
+
* path that crosses an array without an index gives `MISSING`, never an element of the array.
|
|
31
32
|
*/
|
|
32
|
-
export declare function getPath(resource: Resource, path:
|
|
33
|
+
export declare function getPath(resource: Resource, path: SortPath): unknown;
|
|
34
|
+
/** True when the path crosses an array of the Resource without an index, so it sorts as missing (SORTING_ARRAY_PATH). */
|
|
35
|
+
export declare function crossesArray(resource: Resource, path: SortPath): boolean;
|
|
36
|
+
/** The `SORT_ARRAY_PATH` Warning for a sort path, written as a field list item in `field` (SORTING_ARRAY_PATH). */
|
|
37
|
+
export declare function sortArrayPathWarning(path: SortPath): Warning;
|
|
38
|
+
/**
|
|
39
|
+
* The `SORT_ARRAY_PATH` Warnings of a sort (SORTING_ARRAY_PATH, D112): one for each distinct key path that crosses an
|
|
40
|
+
* array in at least one of the Resources, in key order. A provider that sorts passes every matched Resource, not
|
|
41
|
+
* only the page, and reports these once per operation.
|
|
42
|
+
*/
|
|
43
|
+
export declare function sortArrayPathWarnings(resources: Iterable<Resource>, keys: readonly SortKey[]): Warning[];
|
|
33
44
|
/**
|
|
34
45
|
* A comparator for `Array.prototype.sort` (SORTING_FIELD_LIST): each key in order, descending keys reversed, so
|
|
35
|
-
* that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS).
|
|
36
|
-
* `options.codec` as in `compareSortValues`.
|
|
46
|
+
* that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS). Values
|
|
47
|
+
* are read with `getPath` (SORTING_ARRAY_PATH). `options.codec` as in `compareSortValues`.
|
|
37
48
|
*/
|
|
38
49
|
export declare function compareResources(keys: readonly SortKey[], options?: SortOptions): (a: Resource, b: Resource) => number;
|
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
|
|
244
|
-
*
|
|
245
|
-
*
|
|
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
|
-
|
|
251
|
+
function follow(resource, path) {
|
|
248
252
|
let value = resource;
|
|
249
|
-
for (const
|
|
250
|
-
if (
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
|
44
|
-
*
|
|
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
|
-
/**
|
|
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 (
|
|
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
|
|
121
|
-
*
|
|
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
|
-
|
|
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
|
-
/**
|
|
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:
|
|
31
|
+
readonly path: SortPath;
|
|
26
32
|
readonly direction: "asc" | "desc";
|
|
27
33
|
}
|
|
28
34
|
/**
|
package/dist/warnings.d.ts
CHANGED
|
@@ -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.
|
|
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