@crud-api/core 0.0.0-stage → 0.1.1

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.
Files changed (53) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +78 -2
  3. package/dist/conformance.d.ts +7 -0
  4. package/dist/conformance.js +8 -0
  5. package/dist/depth.d.ts +20 -0
  6. package/dist/depth.js +73 -0
  7. package/dist/errors.d.ts +40 -0
  8. package/dist/errors.js +71 -0
  9. package/dist/extensions.d.ts +71 -0
  10. package/dist/extensions.js +69 -0
  11. package/dist/field-list.d.ts +19 -0
  12. package/dist/field-list.js +108 -0
  13. package/dist/ids.d.ts +73 -0
  14. package/dist/ids.js +391 -0
  15. package/dist/index.d.ts +31 -0
  16. package/dist/index.js +17 -0
  17. package/dist/negotiation.d.ts +57 -0
  18. package/dist/negotiation.js +174 -0
  19. package/dist/operation.d.ts +104 -0
  20. package/dist/operation.js +407 -0
  21. package/dist/operations/by-id.d.ts +17 -0
  22. package/dist/operations/by-id.js +98 -0
  23. package/dist/operations/by-query.d.ts +6 -0
  24. package/dist/operations/by-query.js +84 -0
  25. package/dist/operations/context.d.ts +163 -0
  26. package/dist/operations/context.js +274 -0
  27. package/dist/operations/create.d.ts +16 -0
  28. package/dist/operations/create.js +168 -0
  29. package/dist/operations/read.d.ts +10 -0
  30. package/dist/operations/read.js +89 -0
  31. package/dist/pagination.d.ts +43 -0
  32. package/dist/pagination.js +96 -0
  33. package/dist/patch.d.ts +37 -0
  34. package/dist/patch.js +299 -0
  35. package/dist/projection.d.ts +19 -0
  36. package/dist/projection.js +127 -0
  37. package/dist/provider.d.ts +185 -0
  38. package/dist/provider.js +5 -0
  39. package/dist/query.d.ts +34 -0
  40. package/dist/query.js +85 -0
  41. package/dist/server.d.ts +83 -0
  42. package/dist/server.js +85 -0
  43. package/dist/sorting.d.ts +38 -0
  44. package/dist/sorting.js +271 -0
  45. package/dist/subject.d.ts +47 -0
  46. package/dist/subject.js +140 -0
  47. package/dist/types.d.ts +45 -0
  48. package/dist/types.js +15 -0
  49. package/dist/warnings.d.ts +64 -0
  50. package/dist/warnings.js +127 -0
  51. package/dist/write-policy.d.ts +30 -0
  52. package/dist/write-policy.js +29 -0
  53. package/package.json +51 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # @crud-api/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Core of the **CRUD API** reference implementation: the data model, the `createCrudServer` engine, the provider contract, field lists, projection, sorting, pagination, patch engines, negotiation, Warnings and the strict policy, and the conformance declaration. It knows no data source and does no I/O; providers (such as `@crud-api/memory`) and protocol adapters plug into it.
4
+
5
+ ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.
6
+
7
+ ## Usage
8
+
9
+ ```ts
10
+ import { createCrudServer } from "@crud-api/core";
11
+ import { createMemoryProvider } from "@crud-api/memory";
12
+
13
+ const server = createCrudServer({ provider: createMemoryProvider({ implicitCollections: true }) });
14
+
15
+ const created = await server.execute({ operation: "create", collection: "orders", resources: [{ total: 10 }, { total: 25 }] });
16
+ const page = await server.execute({
17
+ operation: "list",
18
+ collection: "orders",
19
+ query: { format: "text/vnd.unquery.sql", text: "total > 15" },
20
+ params: { sort: "-total", limit: 20 },
21
+ });
22
+ if (page.ok) console.log(page.resources, page.meta.matchedCount);
23
+ else console.log(page.error.code, page.error.message);
24
+ ```
25
+
26
+ `execute` never throws for an operation that fails: it returns `{ ok: false, error, meta }`, where `error` is a `CrudError` (Base error codes, `toProblemDetails` for RFC 9457) and `meta` still carries the negotiated specification versions, representation, Correlation ID, Warnings and, for writes, the Modified Count. `createCrudServer` throws when the configuration is invalid (an extension enabled twice or missing a required extension, a reused Base code, an extension that needs system storage without one).
27
+
28
+ ## The engine
29
+
30
+ An `OperationRequest` is protocol-neutral: `operation` (one of the ten Base operations), `collection`, the Subject (`id`, `resources`, `resource`, `patch`, `newId`, `query`), `params` (`fields`, `sort`, `page`, `offset`, `cursor`, `limit`, `expectMatch`, `denyUpsert`, `custom`) and `meta` (`accept`, `returnPreference`, `strict`, `require`, `correlationId`, `principal`), plus the adapter's `warnings`. Values are host values of the ECSON model; the core converts nothing and never serializes.
31
+
32
+ Each operation goes through the steps of the design, and the first failure stops it:
33
+
34
+ 1. specification versions (`META_CRUD_RANGE_MATCH`);
35
+ 2. Output representation and Search Query format (`META_RES_PREFERENCE`, `META_RES_FALLBACK`);
36
+ 3. the `authorize` hook (`ACCESS_DENIED`);
37
+ 4. the Collection (`COLLECTION_SLUG`, `COLLECTION_NOT_FOUND`, `COLLECTION_CREATE_IMPLICIT`);
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`;
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
+ 8. the Search Query, parsed with UnQuery and checked against the provider's operators;
42
+ 9. extension hooks (`beforeWrite`, `afterRead`);
43
+ 10. the write policy (`WRITE_ATOMIC_STRICT`, `WRITE_STRICT_LATE_WARNINGS`);
44
+ 11. `prepare` of every primitive, with the depth check of each Resource to write (a Resource the Server could not answer back inside a list, deeper than 999 levels with the ECSON default `DEPTH_LIMIT` of 1000, is `INVALID_INPUT` with `ecsonCode: "DEPTH_LIMIT"`; D108), then the strict policy on every Warning collected so far.
45
+
46
+ Only then does anything get written. Reads and writes are composed from provider primitives (`find`, `findByIds`, `insert`, `replace`, `remove`): writes by query read the exact matched set once and write each Resource by ID, never re-running the filter. Writes on several Resources run in `provider.transaction()` when the provider has one (all or nothing); without it they are partial in lenient mode (each failure becomes `WRITE_FAILED`) and fail with `UNSUPPORTED` before writing under the strict preference, unless it allows `WRITE_FAILED`.
47
+
48
+ ### Options
49
+
50
+ - `provider`: the data provider.
51
+ - `system`: the system storage of extensions such as Schema, Views and Async; by default the data provider when it declares `systemCollections`, otherwise none.
52
+ - `extensions`: extension objects (`name`, `spec`, `versions`, `requires`, `needsSystemStorage`, `reservedFields`, `reservedCollections`, `errorCodes`, `warningCodes`, `beforeWrite`, `afterRead`).
53
+ - `specs`: specifications and versions declared (default `{ base: ["0.2.0"] }`, plus each extension's).
54
+ - `representations`: Output representations (default `["ecson", "json"]`).
55
+ - `limits`: `maxLimit`, `defaultLimit` and UnQuery `query` limits.
56
+ - `clock`, `random`: injected time and random source (defaults `Date.now` and `crypto.getRandomValues`), used for UUIDv7 Resource IDs and Correlation IDs.
57
+ - `generateId`: replaces the UUIDv7 generator for new Resource IDs.
58
+ - `authorize`: returns false to refuse an operation.
59
+ - `customParams`: Custom Parameters the server recognizes.
60
+ - `onError`: receives the original of every `INTERNAL` error, which never reaches the Client; a throwing `onError` is ignored.
61
+ - `codec`: the ECSON codec (`@ecson/core` `createCodec`) with the types of the enabled extensions; used for sorting, composite keys and Search Queries, and passed to the provider as `ctx.codec`. Default: `createCodec()`, the core, References (`$rel`, `Rel`) and Error (`$error`) type sets of `@ecson/core` 0.2.0 (D111). Exposed as `server.codec`.
62
+
63
+ ### For Protocol adapters
64
+
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
+ - `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
+ - `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
+ - `server.description` lists the specifications, extensions, `customParams`, `queryFormats` (UnQuery JSON, UnQuery SQL, then the provider's) and `representations`.
69
+ - `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).
70
+ - `meta.ids` lists the canonical IDs written by `create`, `clone`, `patchById`, `replaceById` and `deleteById`, in Subject order, also with `returnPreference: "minimal"` (for `Location` header fields).
71
+ - `exceedsDepth(tree, max)`, `DEPTH_LIMIT` and `RESOURCE_MAX_DEPTH` bound the bodies and arguments an adapter reads with the same iterative walk the engine uses, so hostile nesting cannot overflow the stack (D108).
72
+
73
+ ## Providers
74
+
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
+
77
+ ## Conformance
78
+
79
+ `conformance` declares the CRUD Base specification `0.2.0` with its ten operations and no extension.
@@ -0,0 +1,7 @@
1
+ /** Conformance declaration of the CRUD Base spec: the ten Base operations, no extension yet. */
2
+ export declare const conformance: Readonly<{
3
+ spec: "crud-base";
4
+ version: "0.2.0";
5
+ operations: readonly string[];
6
+ extensions: readonly string[];
7
+ }>;
@@ -0,0 +1,8 @@
1
+ import { OPERATIONS } from "./types.js";
2
+ /** Conformance declaration of the CRUD Base spec: the ten Base operations, no extension yet. */
3
+ export const conformance = Object.freeze({
4
+ spec: "crud-base",
5
+ version: "0.2.0",
6
+ operations: Object.freeze([...OPERATIONS]),
7
+ extensions: Object.freeze([]),
8
+ });
@@ -0,0 +1,20 @@
1
+ import type { Codec } from "@ecson/core";
2
+ /**
3
+ * The deepest nesting of arrays and objects an ECSON codec reads and writes: the documented default `DEPTH_LIMIT` of
4
+ * ECSON (`maxDepth`, 1000). A `Codec` does not expose its own limit, so the engine and the adapters use this one.
5
+ */
6
+ export declare const DEPTH_LIMIT = 1000;
7
+ /** The deepest Resource a write may store: one level is left for the list a `list` answers (D108). */
8
+ export declare const RESOURCE_MAX_DEPTH: number;
9
+ /**
10
+ * True when `tree` nests arrays and objects deeper than `max` (`[]` and `{}` are depth 1, scalars 0). Iterative, so
11
+ * hostile nesting cannot overflow the stack.
12
+ */
13
+ export declare function exceedsDepth(tree: unknown, max: number): boolean;
14
+ /**
15
+ * D108: fails with INVALID_INPUT (rule REPR_DEPTH_LIMIT, `ecsonCode: "DEPTH_LIMIT"`) when `resource` could not be encoded
16
+ * by `codec` inside a list. A plain tree is measured by the iterative walk alone; a tree holding typed values is
17
+ * then encoded inside a list, since their ECSON form may nest deeper than the host value (the walk already bounds
18
+ * that recursion).
19
+ */
20
+ export declare function assertWritableDepth(resource: unknown, codec: Codec): void;
package/dist/depth.js ADDED
@@ -0,0 +1,73 @@
1
+ import { CrudError } from "./errors.js";
2
+ /**
3
+ * The deepest nesting of arrays and objects an ECSON codec reads and writes: the documented default `DEPTH_LIMIT` of
4
+ * ECSON (`maxDepth`, 1000). A `Codec` does not expose its own limit, so the engine and the adapters use this one.
5
+ */
6
+ export const DEPTH_LIMIT = 1000;
7
+ /** The deepest Resource a write may store: one level is left for the list a `list` answers (D108). */
8
+ export const RESOURCE_MAX_DEPTH = DEPTH_LIMIT - 1;
9
+ /** True when a value is written by ECSON as itself: JSON scalars other than negative zero. */
10
+ function plainScalar(value) {
11
+ if (value === null || typeof value === "string" || typeof value === "boolean")
12
+ return true;
13
+ return typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0);
14
+ }
15
+ /**
16
+ * One iterative walk: "exceeds" when arrays and objects nest deeper than `max`; otherwise "plain" when every value is
17
+ * a JSON scalar, an array or a plain object (its ECSON tree has the same depth), "typed" when some value has an ECSON
18
+ * form of its own (bigint, Date, Map, a class, negative zero, ...), whose tree may be deeper than the host value.
19
+ */
20
+ function scan(tree, max) {
21
+ let plain = true;
22
+ const stack = [[tree, 0]];
23
+ while (stack.length > 0) {
24
+ const [node, depth] = stack.pop();
25
+ if (node === null || typeof node !== "object") {
26
+ if (plain && !plainScalar(node))
27
+ plain = false;
28
+ continue;
29
+ }
30
+ if (depth + 1 > max)
31
+ return "exceeds";
32
+ if (plain && !Array.isArray(node)) {
33
+ const proto = Object.getPrototypeOf(node);
34
+ if (proto !== Object.prototype && proto !== null)
35
+ plain = false;
36
+ }
37
+ for (const item of Object.values(node))
38
+ stack.push([item, depth + 1]);
39
+ }
40
+ return plain ? "plain" : "typed";
41
+ }
42
+ /**
43
+ * True when `tree` nests arrays and objects deeper than `max` (`[]` and `{}` are depth 1, scalars 0). Iterative, so
44
+ * hostile nesting cannot overflow the stack.
45
+ */
46
+ export function exceedsDepth(tree, max) {
47
+ return scan(tree, max) === "exceeds";
48
+ }
49
+ const tooDeep = () => new CrudError("INVALID_INPUT", `the Resource nests deeper than the Server can represent in a list (${RESOURCE_MAX_DEPTH} levels)`, {
50
+ rule: "REPR_DEPTH_LIMIT",
51
+ data: { ecsonCode: "DEPTH_LIMIT" },
52
+ });
53
+ /**
54
+ * D108: fails with INVALID_INPUT (rule REPR_DEPTH_LIMIT, `ecsonCode: "DEPTH_LIMIT"`) when `resource` could not be encoded
55
+ * by `codec` inside a list. A plain tree is measured by the iterative walk alone; a tree holding typed values is
56
+ * then encoded inside a list, since their ECSON form may nest deeper than the host value (the walk already bounds
57
+ * that recursion).
58
+ */
59
+ export function assertWritableDepth(resource, codec) {
60
+ const result = scan(resource, RESOURCE_MAX_DEPTH);
61
+ if (result === "exceeds")
62
+ throw tooDeep();
63
+ if (result === "plain")
64
+ return;
65
+ try {
66
+ codec.encode([resource]);
67
+ }
68
+ catch (error) {
69
+ if (error instanceof RangeError || (error instanceof Error && error.code === "DEPTH_LIMIT"))
70
+ throw tooDeep();
71
+ // Other encoding failures are not about depth: the write goes on as before.
72
+ }
73
+ }
@@ -0,0 +1,40 @@
1
+ /** The Base error codes (table of section 3.4.4). */
2
+ export declare const BASE_ERROR_CODES: ReadonlySet<string>;
3
+ /** Members a CrudError carries besides code, message and target (RES_ERROR_MORE_DATA). */
4
+ export type ErrorData = Readonly<Record<string, unknown>>;
5
+ export interface CrudErrorOptions {
6
+ /** Code of the rule that requires the failure, for conformance vectors and logs (never sent as error data). */
7
+ rule?: string;
8
+ /** The kind of missing element of NOT_FOUND: `resource`, `collection` or an extension target (RES_ERROR_DATA). */
9
+ target?: string;
10
+ /** Extra members of the error data, such as `unqueryCode`, `supported` or `warnings` (RES_ERROR_MORE_DATA). */
11
+ data?: Record<string, unknown>;
12
+ cause?: unknown;
13
+ }
14
+ /** A failed operation: the error code of section 3.4.4 (or of an extension, or namespaced) and a human-readable message. */
15
+ export declare class CrudError extends Error {
16
+ readonly code: string;
17
+ readonly rule: string | undefined;
18
+ readonly target: string | undefined;
19
+ readonly data: ErrorData;
20
+ constructor(code: string, message: string, options?: CrudErrorOptions);
21
+ }
22
+ /** RFC 9457 Problem Details object with the CRUD members (ERROR_PROBLEM_DETAILS). */
23
+ export interface ProblemDetails {
24
+ type: string;
25
+ title: string;
26
+ detail: string;
27
+ code: string;
28
+ target?: string;
29
+ status?: number;
30
+ [member: string]: unknown;
31
+ }
32
+ /**
33
+ * ERROR_PROBLEM_DETAILS: the error data of a CrudError. `status` only when the Protocol has numeric status codes
34
+ * (it is passed by the adapter); extra data members are added unless they would replace a standard member.
35
+ */
36
+ export declare function toProblemDetails(error: CrudError, options?: {
37
+ status?: number;
38
+ }): ProblemDetails;
39
+ /** ERROR_CUSTOM_CODES, WARN_CUSTOM_CODES: a code prefixed with a namespace and a `.`, such as `acme.QUOTA_EXCEEDED`. */
40
+ export declare function isNamespacedCode(code: string): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,71 @@
1
+ // Errors of CRUD operations (Base section 3.4.4).
2
+ /** The Base error codes (table of section 3.4.4). */
3
+ export const BASE_ERROR_CODES = new Set([
4
+ "INVALID_INPUT",
5
+ "INVALID_PATCH",
6
+ "NOT_FOUND",
7
+ "CONFLICT",
8
+ "EXPECT_MISMATCH",
9
+ "UPSERT_DENIED",
10
+ "NEGOTIATION",
11
+ "UNSUPPORTED",
12
+ "STRICT_WARNINGS",
13
+ "ACCESS_DENIED",
14
+ "INTERNAL",
15
+ ]);
16
+ const TITLES = {
17
+ INVALID_INPUT: "Invalid input",
18
+ INVALID_PATCH: "Invalid patch",
19
+ NOT_FOUND: "Not found",
20
+ CONFLICT: "Conflict",
21
+ EXPECT_MISMATCH: "Expect mismatch",
22
+ UPSERT_DENIED: "Upsert denied",
23
+ NEGOTIATION: "Negotiation failed",
24
+ UNSUPPORTED: "Unsupported",
25
+ STRICT_WARNINGS: "Strict warnings",
26
+ ACCESS_DENIED: "Access denied",
27
+ INTERNAL: "Internal error",
28
+ };
29
+ /** A failed operation: the error code of section 3.4.4 (or of an extension, or namespaced) and a human-readable message. */
30
+ export class CrudError extends Error {
31
+ code;
32
+ rule;
33
+ target;
34
+ data;
35
+ constructor(code, message, options = {}) {
36
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
37
+ this.name = "CrudError";
38
+ this.code = code;
39
+ this.rule = options.rule;
40
+ this.target = options.target;
41
+ this.data = Object.freeze({ ...options.data });
42
+ }
43
+ }
44
+ /** Problem Details members that extra data never overwrites. */
45
+ const RESERVED_MEMBERS = new Set(["type", "title", "detail", "code", "target", "status"]);
46
+ /**
47
+ * ERROR_PROBLEM_DETAILS: the error data of a CrudError. `status` only when the Protocol has numeric status codes
48
+ * (it is passed by the adapter); extra data members are added unless they would replace a standard member.
49
+ */
50
+ export function toProblemDetails(error, options = {}) {
51
+ const problem = {
52
+ type: "about:blank",
53
+ title: TITLES[error.code] ?? error.code,
54
+ detail: error.message,
55
+ code: error.code,
56
+ };
57
+ if (error.target !== undefined)
58
+ problem.target = error.target;
59
+ if (options.status !== undefined)
60
+ problem.status = options.status;
61
+ for (const [member, value] of Object.entries(error.data)) {
62
+ // Own data property, so a member named `__proto__` is a member and never replaces the prototype.
63
+ if (!RESERVED_MEMBERS.has(member))
64
+ Object.defineProperty(problem, member, { value, writable: true, enumerable: true, configurable: true });
65
+ }
66
+ return problem;
67
+ }
68
+ /** ERROR_CUSTOM_CODES, WARN_CUSTOM_CODES: a code prefixed with a namespace and a `.`, such as `acme.QUOTA_EXCEEDED`. */
69
+ export function isNamespacedCode(code) {
70
+ return /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[A-Za-z0-9_]+$/.test(code);
71
+ }
@@ -0,0 +1,71 @@
1
+ import type { OperationName, Resource } from "./types.ts";
2
+ 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
+ export interface HookCtx {
5
+ warn(warning: Warning): void;
6
+ }
7
+ /**
8
+ * 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.
11
+ */
12
+ export interface Extension {
13
+ /** Unique name, such as `metadata`. */
14
+ readonly name: string;
15
+ /** Specification name declared in META_CRUD_SPECS, such as `metadata`. */
16
+ readonly spec: string;
17
+ /** Versions of that specification the extension implements (META_CRUD_SPECS). */
18
+ readonly versions: readonly string[];
19
+ /** Names of the extensions this one needs (Schema needs Metadata, `schema/spec.yaml`). */
20
+ readonly requires?: readonly string[];
21
+ /** Needs the system storage of design 6.10 (Schema, Views, Async). */
22
+ readonly needsSystemStorage?: boolean;
23
+ /** Reserved Fields this extension defines and handles (FIELDS_EXTENSION_RESERVED), such as `_meta`. */
24
+ readonly reservedFields?: readonly string[];
25
+ /**
26
+ * Reserved Collection names this extension handles (design 6.3 step 4): exact names such as `@schema`, or a
27
+ * pattern `*\/@views` where `*` stands for any Slug.
28
+ */
29
+ readonly reservedCollections?: readonly string[];
30
+ /** Error codes of the extension (ERROR_EXTENSION_CODES: never a Base code). */
31
+ readonly errorCodes?: readonly string[];
32
+ /** Warning codes of the extension (WARN_EXTENSION_CODES: never a Base code). */
33
+ 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>;
41
+ /** 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
+ afterRead?(input: {
43
+ readonly collection: string;
44
+ readonly resources: Resource[];
45
+ }, ctx: HookCtx): Resource[] | Promise<Resource[]>;
46
+ }
47
+ /**
48
+ * Reserved Fields defined by the specifications of the family, with the extension that defines each one
49
+ * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
50
+ */
51
+ export declare const KNOWN_RESERVED_FIELDS: Readonly<Record<string, string>>;
52
+ /** The enabled extensions of a server, checked once at construction (design 7). */
53
+ export declare class ExtensionRegistry {
54
+ readonly list: readonly Extension[];
55
+ readonly codes: CodeRegistry;
56
+ /** Reserved Fields handled by an enabled extension: they are kept (FIELDS_RESERVED_UNSUPPORTED does not apply). */
57
+ readonly handledFields: ReadonlySet<string>;
58
+ constructor(extensions: readonly Extension[], codes?: CodeRegistry);
59
+ get names(): string[];
60
+ /** The extension that claims a reserved Collection name (design 6.3 step 4), if any. */
61
+ 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;
68
+ }, ctx: HookCtx): Promise<Resource>;
69
+ /** Runs every `afterRead` hook in the order of the extensions. */
70
+ afterRead(collection: string, resources: Resource[], ctx: HookCtx): Promise<Resource[]>;
71
+ }
@@ -0,0 +1,69 @@
1
+ // Extensions plugged into the engine (design section 7): the interface and the registry built at server construction.
2
+ import { isSlug } from "./ids.js";
3
+ import { CodeRegistry } from "./warnings.js";
4
+ /**
5
+ * Reserved Fields defined by the specifications of the family, with the extension that defines each one
6
+ * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
7
+ */
8
+ export const KNOWN_RESERVED_FIELDS = Object.freeze({ _meta: "metadata" });
9
+ function matchesReserved(pattern, collection) {
10
+ if (pattern.startsWith("*/")) {
11
+ const suffix = pattern.slice(1); // "/@views"
12
+ return collection.endsWith(suffix) && isSlug(collection.slice(0, collection.length - suffix.length));
13
+ }
14
+ return pattern === collection;
15
+ }
16
+ /** The enabled extensions of a server, checked once at construction (design 7). */
17
+ export class ExtensionRegistry {
18
+ list;
19
+ codes;
20
+ /** Reserved Fields handled by an enabled extension: they are kept (FIELDS_RESERVED_UNSUPPORTED does not apply). */
21
+ handledFields;
22
+ constructor(extensions, codes = new CodeRegistry()) {
23
+ const names = new Set();
24
+ for (const extension of extensions) {
25
+ if (typeof extension.name !== "string" || extension.name === "")
26
+ throw new Error("an extension needs a name");
27
+ if (names.has(extension.name))
28
+ throw new Error(`extension ${extension.name} is enabled twice`);
29
+ names.add(extension.name);
30
+ }
31
+ for (const extension of extensions) {
32
+ for (const required of extension.requires ?? []) {
33
+ if (!names.has(required))
34
+ throw new Error(`extension ${extension.name} requires extension ${required}, which is not enabled`);
35
+ }
36
+ // ERROR_EXTENSION_CODES, WARN_EXTENSION_CODES: CodeRegistry throws when a Base code is reused.
37
+ codes.registerErrorCodes(extension.name, extension.errorCodes ?? []);
38
+ codes.registerWarningCodes(extension.name, extension.warningCodes ?? []);
39
+ }
40
+ this.list = Object.freeze([...extensions]);
41
+ this.codes = codes;
42
+ this.handledFields = new Set(extensions.flatMap((e) => e.reservedFields ?? []));
43
+ }
44
+ get names() {
45
+ return this.list.map((e) => e.name);
46
+ }
47
+ /** The extension that claims a reserved Collection name (design 6.3 step 4), if any. */
48
+ claimant(collection) {
49
+ return this.list.find((e) => (e.reservedCollections ?? []).some((pattern) => matchesReserved(pattern, collection)));
50
+ }
51
+ /** Runs every `beforeWrite` hook in the order of the extensions. */
52
+ async beforeWrite(input, ctx) {
53
+ let next = input.next;
54
+ for (const extension of this.list) {
55
+ if (extension.beforeWrite !== undefined)
56
+ next = await extension.beforeWrite({ ...input, next }, ctx);
57
+ }
58
+ return next;
59
+ }
60
+ /** Runs every `afterRead` hook in the order of the extensions. */
61
+ async afterRead(collection, resources, ctx) {
62
+ let current = resources;
63
+ for (const extension of this.list) {
64
+ if (extension.afterRead !== undefined)
65
+ current = await extension.afterRead({ collection, resources: current }, ctx);
66
+ }
67
+ return current;
68
+ }
69
+ }