@crud-api/schema 0.0.0 → 0.1.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 +140 -2
- package/dist/collection.d.ts +20 -0
- package/dist/collection.js +234 -0
- package/dist/conformance.d.ts +7 -0
- package/dist/conformance.js +7 -0
- package/dist/convert.d.ts +23 -0
- package/dist/convert.js +304 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/json-tree.d.ts +8 -0
- package/dist/json-tree.js +31 -0
- package/dist/owned.d.ts +18 -0
- package/dist/owned.js +142 -0
- package/dist/reads.d.ts +14 -0
- package/dist/reads.js +65 -0
- package/dist/schema.d.ts +19 -0
- package/dist/schema.js +98 -0
- package/dist/validate.d.ts +14 -0
- package/dist/validate.js +235 -0
- package/dist/validator.d.ts +52 -0
- package/dist/validator.js +138 -0
- package/dist/vocabulary.d.ts +23 -0
- package/dist/vocabulary.js +52 -0
- package/dist/writes.d.ts +14 -0
- package/dist/writes.js +180 -0
- package/package.json +56 -5
package/dist/convert.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// D147.3 amended: the ESType conversion of a written Resource in one pass, every value that cannot be converted collected
|
|
2
|
+
// (SCHEMA_VALUE_CONVERSION, S64, S66). The walk is the one of `createConverter` of `@estype/core/convert` 0.2 (ESType
|
|
3
|
+
// section 4: CONVERT_NESTED, CONVERT_FORM_PER_FIELD), with two changes: a value that fails is reported and kept as
|
|
4
|
+
// received instead of stopping the conversion, and `patternProperties` use the regular expression engine of the
|
|
5
|
+
// validator (D143 amended).
|
|
6
|
+
import { checkSchema, createIndex, DEFINITIONS_ID, definitions, EstypeError, indexDocument, isCompiledEstype, isObject, jsonEqual, resolveRef, tagOf, toPointer, } from "@estype/core";
|
|
7
|
+
import { convertValue, EcsonError, isEcsonForm, isJsonValue } from "@estype/core/convert";
|
|
8
|
+
/**
|
|
9
|
+
* Builds a converter for a schema, like `createConverter`: the schema is checked first (`checkSchema`), so an invalid
|
|
10
|
+
* `estype` throws here, before any value. Each value that cannot be converted (`CONVERT_FAIL`, `CONVERT_UNSUPPORTED`,
|
|
11
|
+
* `REF_UNRESOLVED`, a malformed ECSON form) is one failure; the walk goes on, so the work is linear in the size of the
|
|
12
|
+
* value whatever the number of failures.
|
|
13
|
+
*/
|
|
14
|
+
export function createCollectingConverter(schema, options) {
|
|
15
|
+
checkSchema(schema, { schemas: [] });
|
|
16
|
+
const index = createIndex();
|
|
17
|
+
indexDocument(index, definitions, DEFINITIONS_ID);
|
|
18
|
+
const base = indexDocument(index, schema);
|
|
19
|
+
return (value) => {
|
|
20
|
+
const ctx = { index, codec: options.codec, matches: options.matches, active: new Map(), root: value, failures: [] };
|
|
21
|
+
return { value: walk(ctx, schema, base, value, []), failures: ctx.failures };
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
// --- copy on write ----------------------------------------------------------------------------------------------
|
|
25
|
+
const define = (target, key, value) => {
|
|
26
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
27
|
+
};
|
|
28
|
+
/** A copy of an array or a plain object, keeping `__proto__` keys as own properties. */
|
|
29
|
+
function shallowCopy(value) {
|
|
30
|
+
if (Array.isArray(value))
|
|
31
|
+
return [...value];
|
|
32
|
+
const copy = Object.create(Object.getPrototypeOf(value));
|
|
33
|
+
for (const key of Object.keys(value))
|
|
34
|
+
define(copy, key, value[key]);
|
|
35
|
+
return copy;
|
|
36
|
+
}
|
|
37
|
+
/** Replaces members of a container, copying it on the first change. */
|
|
38
|
+
class Writer {
|
|
39
|
+
copied = false;
|
|
40
|
+
value;
|
|
41
|
+
constructor(value) {
|
|
42
|
+
this.value = value;
|
|
43
|
+
}
|
|
44
|
+
get(key) {
|
|
45
|
+
return this.value[key];
|
|
46
|
+
}
|
|
47
|
+
set(key, next) {
|
|
48
|
+
if (Object.is(this.get(key), next))
|
|
49
|
+
return;
|
|
50
|
+
if (!this.copied) {
|
|
51
|
+
this.value = shallowCopy(this.value);
|
|
52
|
+
this.copied = true;
|
|
53
|
+
}
|
|
54
|
+
define(this.value, key, next);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// --- walk -------------------------------------------------------------------------------------------------------
|
|
58
|
+
const isPlainObject = (value) => isObject(value) && isJsonValue(value);
|
|
59
|
+
/** The value at `path` inside `root` (own members and array indexes), or undefined. */
|
|
60
|
+
function valueAt(root, path) {
|
|
61
|
+
let node = root;
|
|
62
|
+
for (const segment of path) {
|
|
63
|
+
if (Array.isArray(node) && typeof segment === "number")
|
|
64
|
+
node = node[segment];
|
|
65
|
+
else if (isObject(node) && typeof segment === "string" && Object.hasOwn(node, segment))
|
|
66
|
+
node = node[segment];
|
|
67
|
+
else
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
return node;
|
|
71
|
+
}
|
|
72
|
+
function resolve(ctx, ref, base, path) {
|
|
73
|
+
const target = resolveRef(ctx.index, ref, base);
|
|
74
|
+
if (target === undefined) {
|
|
75
|
+
throw new EstypeError("REF_UNRESOLVED", `cannot resolve $ref ${JSON.stringify(ref)} (base ${base}); pass the document in options.schemas`, { path });
|
|
76
|
+
}
|
|
77
|
+
return target;
|
|
78
|
+
}
|
|
79
|
+
function walk(ctx, node, base, value, path) {
|
|
80
|
+
if (typeof node === "boolean" || !isObject(node))
|
|
81
|
+
return value;
|
|
82
|
+
const key = toPointer(path);
|
|
83
|
+
let active = ctx.active.get(key);
|
|
84
|
+
if (active?.has(node))
|
|
85
|
+
return value;
|
|
86
|
+
if (active === undefined)
|
|
87
|
+
ctx.active.set(key, (active = new Set()));
|
|
88
|
+
active.add(node);
|
|
89
|
+
try {
|
|
90
|
+
return apply(ctx, node, ctx.index.baseOf.get(node) ?? base, value, path);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (!(error instanceof EstypeError) && !(error instanceof EcsonError))
|
|
94
|
+
throw error;
|
|
95
|
+
// The value is left as received (S64) and the walk goes on with the next one.
|
|
96
|
+
ctx.failures.push({ path: [...error.path], error });
|
|
97
|
+
const received = valueAt(ctx.root, path);
|
|
98
|
+
return received === undefined ? value : received;
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
active.delete(node);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function apply(ctx, node, base, value, path) {
|
|
105
|
+
const type = typeof node.estype === "string" ? node.estype : undefined;
|
|
106
|
+
if (type !== undefined) {
|
|
107
|
+
// ECSON form: decoded as a whole, then the nested schemas apply to the members (CONVERT_NESTED).
|
|
108
|
+
if (isEcsonForm(value, type))
|
|
109
|
+
return applyMembers(ctx, node, base, convertValue(type, value, { codec: ctx.codec, path }), [...path, tagOf(type)]);
|
|
110
|
+
if (value === null)
|
|
111
|
+
return value;
|
|
112
|
+
// Already native (for example read by an ECSON decoder): checked against the type.
|
|
113
|
+
if (!isJsonValue(value))
|
|
114
|
+
return applyMembers(ctx, node, base, convertValue(type, value, { codec: ctx.codec, path }), path);
|
|
115
|
+
}
|
|
116
|
+
return type === undefined ? applyDeclared(ctx, node, base, value, path) : convertValue(type, applyDeclared(ctx, node, base, value, path), { codec: ctx.codec, path });
|
|
117
|
+
}
|
|
118
|
+
/** CONVERT_NESTED for a native value: the declared schema applies to the members of a `Set` and the pairs of a `Map`. */
|
|
119
|
+
function applyMembers(ctx, node, base, native, path) {
|
|
120
|
+
if (!(native instanceof Set) && !(native instanceof Map))
|
|
121
|
+
return native;
|
|
122
|
+
const members = [...native];
|
|
123
|
+
const out = applyDeclared(ctx, node, base, members, path);
|
|
124
|
+
if (out === members)
|
|
125
|
+
return native;
|
|
126
|
+
return native instanceof Set ? new Set(out) : new Map(out);
|
|
127
|
+
}
|
|
128
|
+
/** Applies the keywords of `node` other than `estype` to `value`. */
|
|
129
|
+
function applyDeclared(ctx, node, base, value, path) {
|
|
130
|
+
const type = typeof node.estype === "string" ? node.estype : undefined;
|
|
131
|
+
let v = value;
|
|
132
|
+
for (const keyword of ["$ref", "$dynamicRef"]) {
|
|
133
|
+
const ref = node[keyword];
|
|
134
|
+
// $dynamicRef is resolved statically, like $ref.
|
|
135
|
+
if (typeof ref === "string") {
|
|
136
|
+
const target = resolve(ctx, ref, base, path);
|
|
137
|
+
v = walk(ctx, target.schema, target.base, v, path);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (type !== undefined && isCompiledEstype(node)) {
|
|
141
|
+
// The oneOf of compilation: the plain branch (its first allOf member is the plain schema).
|
|
142
|
+
const plain = node.oneOf[1];
|
|
143
|
+
v = walk(ctx, plain.allOf[0], base, v, path);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
if (Array.isArray(node.allOf))
|
|
147
|
+
for (const s of node.allOf)
|
|
148
|
+
v = walk(ctx, s, base, v, path);
|
|
149
|
+
if (Array.isArray(node.anyOf))
|
|
150
|
+
for (const s of node.anyOf)
|
|
151
|
+
if (applies(ctx, s, base, value))
|
|
152
|
+
v = walk(ctx, s, base, v, path);
|
|
153
|
+
if (Array.isArray(node.oneOf)) {
|
|
154
|
+
const branch = node.oneOf.find((s) => applies(ctx, s, base, value));
|
|
155
|
+
if (branch !== undefined)
|
|
156
|
+
v = walk(ctx, branch, base, v, path);
|
|
157
|
+
}
|
|
158
|
+
if (node.if !== undefined) {
|
|
159
|
+
if (applies(ctx, node.if, base, value)) {
|
|
160
|
+
v = walk(ctx, node.if, base, v, path);
|
|
161
|
+
if (node.then !== undefined)
|
|
162
|
+
v = walk(ctx, node.then, base, v, path);
|
|
163
|
+
}
|
|
164
|
+
else if (node.else !== undefined)
|
|
165
|
+
v = walk(ctx, node.else, base, v, path);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (isPlainObject(v)) {
|
|
169
|
+
if (isObject(node.dependentSchemas)) {
|
|
170
|
+
for (const [name, s] of Object.entries(node.dependentSchemas))
|
|
171
|
+
if (isPlainObject(v) && Object.hasOwn(v, name))
|
|
172
|
+
v = walk(ctx, s, base, v, path);
|
|
173
|
+
}
|
|
174
|
+
if (isPlainObject(v))
|
|
175
|
+
v = applyObject(ctx, node, base, v, path);
|
|
176
|
+
}
|
|
177
|
+
else if (Array.isArray(v))
|
|
178
|
+
v = applyArray(ctx, node, base, value, v, path);
|
|
179
|
+
return v;
|
|
180
|
+
}
|
|
181
|
+
function applyObject(ctx, node, base, obj, path) {
|
|
182
|
+
const out = new Writer(obj);
|
|
183
|
+
const properties = isObject(node.properties) ? node.properties : {};
|
|
184
|
+
const patterns = isObject(node.patternProperties) ? Object.entries(node.patternProperties) : [];
|
|
185
|
+
for (const name of Object.keys(obj)) {
|
|
186
|
+
let covered = false;
|
|
187
|
+
if (Object.hasOwn(properties, name)) {
|
|
188
|
+
out.set(name, walk(ctx, properties[name], base, out.get(name), [...path, name]));
|
|
189
|
+
covered = true;
|
|
190
|
+
}
|
|
191
|
+
for (const [pattern, s] of patterns) {
|
|
192
|
+
if (ctx.matches(pattern, name)) {
|
|
193
|
+
out.set(name, walk(ctx, s, base, out.get(name), [...path, name]));
|
|
194
|
+
covered = true;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!covered && node.additionalProperties !== undefined) {
|
|
198
|
+
out.set(name, walk(ctx, node.additionalProperties, base, out.get(name), [...path, name]));
|
|
199
|
+
covered = true;
|
|
200
|
+
}
|
|
201
|
+
// unevaluatedProperties: approximated by the properties this subschema does not cover.
|
|
202
|
+
if (!covered && node.unevaluatedProperties !== undefined)
|
|
203
|
+
out.set(name, walk(ctx, node.unevaluatedProperties, base, out.get(name), [...path, name]));
|
|
204
|
+
}
|
|
205
|
+
return out.value;
|
|
206
|
+
}
|
|
207
|
+
function applyArray(ctx, node, base, original, arr, path) {
|
|
208
|
+
const out = new Writer(arr);
|
|
209
|
+
const items = node.items;
|
|
210
|
+
const prefix = Array.isArray(node.prefixItems) ? node.prefixItems : Array.isArray(items) ? items : [];
|
|
211
|
+
const rest = Array.isArray(items) ? node.additionalItems : items;
|
|
212
|
+
const originals = Array.isArray(original) ? original : arr;
|
|
213
|
+
arr.forEach((_, i) => {
|
|
214
|
+
let covered = false;
|
|
215
|
+
if (i < prefix.length) {
|
|
216
|
+
out.set(i, walk(ctx, prefix[i], base, out.get(i), [...path, i]));
|
|
217
|
+
covered = true;
|
|
218
|
+
}
|
|
219
|
+
else if (rest !== undefined) {
|
|
220
|
+
out.set(i, walk(ctx, rest, base, out.get(i), [...path, i]));
|
|
221
|
+
covered = true;
|
|
222
|
+
}
|
|
223
|
+
if (node.contains !== undefined && applies(ctx, node.contains, base, originals[i]))
|
|
224
|
+
out.set(i, walk(ctx, node.contains, base, out.get(i), [...path, i]));
|
|
225
|
+
if (!covered && node.unevaluatedItems !== undefined)
|
|
226
|
+
out.set(i, walk(ctx, node.unevaluatedItems, base, out.get(i), [...path, i]));
|
|
227
|
+
});
|
|
228
|
+
return out.value;
|
|
229
|
+
}
|
|
230
|
+
// --- conditional applicators --------------------------------------------------------------------------------------
|
|
231
|
+
function applies(ctx, schema, base, value) {
|
|
232
|
+
if (typeof schema === "boolean")
|
|
233
|
+
return schema;
|
|
234
|
+
if (!isObject(schema))
|
|
235
|
+
return true;
|
|
236
|
+
return quickMatch(ctx, schema, ctx.index.baseOf.get(schema) ?? base, value, new Set());
|
|
237
|
+
}
|
|
238
|
+
const TYPE_CHECKS = {
|
|
239
|
+
null: (v) => v === null,
|
|
240
|
+
boolean: (v) => typeof v === "boolean",
|
|
241
|
+
number: (v) => typeof v === "number",
|
|
242
|
+
integer: (v) => typeof v === "number" && Number.isInteger(v),
|
|
243
|
+
string: (v) => typeof v === "string",
|
|
244
|
+
array: (v) => Array.isArray(v),
|
|
245
|
+
object: (v) => isObject(v),
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* The approximate validation of `createConverter` without a `validate` hook: `type`, `const`, `enum`, `required`,
|
|
249
|
+
* `properties`, `additionalProperties: false`, `items`, `prefixItems`, `allOf`, `anyOf`, `oneOf` (as "some"), `$ref` and
|
|
250
|
+
* the ECSON form of `estype`; other keywords are taken as satisfied.
|
|
251
|
+
*/
|
|
252
|
+
function quickMatch(ctx, node, base, value, seen) {
|
|
253
|
+
if (typeof node === "boolean")
|
|
254
|
+
return node;
|
|
255
|
+
if (!isObject(node) || seen.has(node))
|
|
256
|
+
return true;
|
|
257
|
+
seen.add(node);
|
|
258
|
+
const n = node;
|
|
259
|
+
const nodeBase = ctx.index.baseOf.get(node) ?? base;
|
|
260
|
+
const sub = (s, v) => quickMatch(ctx, s, nodeBase, v, seen);
|
|
261
|
+
if (typeof n.estype === "string" && isEcsonForm(value, n.estype))
|
|
262
|
+
return true;
|
|
263
|
+
if (typeof n.$ref === "string") {
|
|
264
|
+
const target = resolveRef(ctx.index, n.$ref, nodeBase);
|
|
265
|
+
if (target !== undefined && !quickMatch(ctx, target.schema, target.base, value, seen))
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
if (n.type !== undefined) {
|
|
269
|
+
const types = Array.isArray(n.type) ? n.type : [n.type];
|
|
270
|
+
if (!types.some((t) => (typeof t === "string" ? (TYPE_CHECKS[t]?.(value) ?? true) : true)))
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
if (Object.hasOwn(n, "const") && !jsonEqual(n.const, value))
|
|
274
|
+
return false;
|
|
275
|
+
if (Array.isArray(n.enum) && !n.enum.some((e) => jsonEqual(e, value)))
|
|
276
|
+
return false;
|
|
277
|
+
if (Array.isArray(n.allOf) && !n.allOf.every((s) => sub(s, value)))
|
|
278
|
+
return false;
|
|
279
|
+
if (Array.isArray(n.anyOf) && !n.anyOf.some((s) => sub(s, value)))
|
|
280
|
+
return false;
|
|
281
|
+
if (Array.isArray(n.oneOf) && !n.oneOf.some((s) => sub(s, value)))
|
|
282
|
+
return false;
|
|
283
|
+
if (isObject(value)) {
|
|
284
|
+
const object = value;
|
|
285
|
+
if (Array.isArray(n.required) && !n.required.every((k) => typeof k === "string" && Object.hasOwn(object, k)))
|
|
286
|
+
return false;
|
|
287
|
+
const properties = isObject(n.properties) ? n.properties : {};
|
|
288
|
+
for (const [name, s] of Object.entries(properties))
|
|
289
|
+
if (Object.hasOwn(object, name) && !sub(s, object[name]))
|
|
290
|
+
return false;
|
|
291
|
+
if (n.additionalProperties === false) {
|
|
292
|
+
const patterns = isObject(n.patternProperties) ? Object.keys(n.patternProperties) : [];
|
|
293
|
+
if (Object.keys(object).some((k) => !Object.hasOwn(properties, k) && !patterns.some((p) => ctx.matches(p, k))))
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
else if (Array.isArray(value)) {
|
|
298
|
+
const prefix = Array.isArray(n.prefixItems) ? n.prefixItems : Array.isArray(n.items) ? n.items : [];
|
|
299
|
+
const rest = Array.isArray(n.items) ? n.additionalItems : n.items;
|
|
300
|
+
if (!value.every((item, i) => (i < prefix.length ? sub(prefix[i], item) : rest === undefined || sub(rest, item))))
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
return true;
|
|
304
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { schema, SCHEMA_VERSION } from "./schema.ts";
|
|
2
|
+
export type { SchemaOptions } from "./schema.ts";
|
|
3
|
+
export { ajvValidator, defaultRegExp } from "./validator.ts";
|
|
4
|
+
export type { AjvValidatorOptions, OutputUnit, RegExpEngine, RegExpLike, SchemaValidator } from "./validator.ts";
|
|
5
|
+
export { META_SCHEMA_URI, SUPPORTED_DIALECTS, VOCABULARY_URI, vocabularyMetaSchema } from "./vocabulary.ts";
|
|
6
|
+
export { conformance } from "./conformance.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { schema, SCHEMA_VERSION } from "./schema.js";
|
|
2
|
+
export { ajvValidator, defaultRegExp } from "./validator.js";
|
|
3
|
+
export { META_SCHEMA_URI, SUPPORTED_DIALECTS, VOCABULARY_URI, vocabularyMetaSchema } from "./vocabulary.js";
|
|
4
|
+
export { conformance } from "./conformance.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Codec } from "@ecson/core";
|
|
2
|
+
/**
|
|
3
|
+
* D141: normalizes a `schema` value to a JSON tree without escaping. A JSON Schema has keys that start with `$`
|
|
4
|
+
* (`$ref`, `$defs`, `$schema`, `$id`) and ECSON encoding would escape them, so plain objects and arrays are walked and
|
|
5
|
+
* keep their keys. A host value becomes its ECSON form with the Server's codec (`Date` becomes `{ "$date": ... }`), and
|
|
6
|
+
* an `UnknownTag` its single member object: `{"$ref": "#/x"}` sent as ECSON decodes to one. Never mutates `value`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function jsonTree(value: unknown, codec: Codec): unknown;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// D141: the `schema` of a Schema Resource is stored as a JSON tree, not as an ECSON tree.
|
|
2
|
+
import { isPlainObject } from "@crud-api/core";
|
|
3
|
+
import { UnknownTag } from "@ecson/core";
|
|
4
|
+
/**
|
|
5
|
+
* D141: normalizes a `schema` value to a JSON tree without escaping. A JSON Schema has keys that start with `$`
|
|
6
|
+
* (`$ref`, `$defs`, `$schema`, `$id`) and ECSON encoding would escape them, so plain objects and arrays are walked and
|
|
7
|
+
* keep their keys. A host value becomes its ECSON form with the Server's codec (`Date` becomes `{ "$date": ... }`), and
|
|
8
|
+
* an `UnknownTag` its single member object: `{"$ref": "#/x"}` sent as ECSON decodes to one. Never mutates `value`.
|
|
9
|
+
*/
|
|
10
|
+
export function jsonTree(value, codec) {
|
|
11
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
12
|
+
return value;
|
|
13
|
+
if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0))
|
|
14
|
+
return value;
|
|
15
|
+
if (value instanceof UnknownTag)
|
|
16
|
+
return Object.fromEntries([[value.tag, value.value]]);
|
|
17
|
+
if (Array.isArray(value))
|
|
18
|
+
return value.map((element) => jsonTree(element, codec));
|
|
19
|
+
if (isPlainObject(value)) {
|
|
20
|
+
const tree = {};
|
|
21
|
+
for (const name of Object.keys(value)) {
|
|
22
|
+
const member = value[name];
|
|
23
|
+
if (member === undefined)
|
|
24
|
+
continue; // like JSON: an undefined member is absent
|
|
25
|
+
// Own data property, so that a `__proto__` key never reaches the prototype setter.
|
|
26
|
+
Object.defineProperty(tree, name, { value: jsonTree(member, codec), writable: true, enumerable: true, configurable: true });
|
|
27
|
+
}
|
|
28
|
+
return tree;
|
|
29
|
+
}
|
|
30
|
+
return codec.encode(value);
|
|
31
|
+
}
|
package/dist/owned.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type OwnedValues } from "@crud-api/core";
|
|
2
|
+
import { type RegExpEngine } from "./validator.ts";
|
|
3
|
+
/** True when the regular expression `pattern` of `patternProperties` matches the member name `name`. */
|
|
4
|
+
export type PatternTest = (pattern: string, name: string) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* D143 amended: `patternProperties` matching with the regular expression engine of the validator (the flag `u`, as
|
|
7
|
+
* Ajv), each expression compiled once, cached by its source. A pattern the engine refuses matches nothing. One per
|
|
8
|
+
* registered schema, so the cache holds only the patterns of that schema.
|
|
9
|
+
*/
|
|
10
|
+
export declare function patternTest(engine?: RegExpEngine): PatternTest;
|
|
11
|
+
/**
|
|
12
|
+
* D147.1: the values under every subschema with `estype` of a registered schema, at the paths of Field names and array
|
|
13
|
+
* indexes that `checkFieldNames` gives (D138), through `properties`, `patternProperties`, `additionalProperties`,
|
|
14
|
+
* `items`, `prefixItems`, the in-place applicators and local `$ref`. A union of every branch, so it may own more than
|
|
15
|
+
* the value needs: what the extension does not convert is checked again after conversion (D147.6). Null when the
|
|
16
|
+
* schema has no `estype`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function ownedValues(schema: unknown, matches?: PatternTest): OwnedValues | null;
|
package/dist/owned.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// D147.1: the Field values of a data Collection that the Schema extension reads itself (D138 `ownedValues`).
|
|
2
|
+
import { isPlainObject } from "@crud-api/core";
|
|
3
|
+
import { DEFINITIONS_ID } from "@estype/core";
|
|
4
|
+
import { defaultRegExp } from "./validator.js";
|
|
5
|
+
/** Applicators whose subschemas apply to the same value (D147.1). */
|
|
6
|
+
const IN_PLACE_ARRAYS = ["allOf", "anyOf", "oneOf"];
|
|
7
|
+
const IN_PLACE_SINGLE = ["then", "else"];
|
|
8
|
+
/** RFC 6901: one reference token of a JSON Pointer, unescaped. */
|
|
9
|
+
const unescape = (token) => token.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
10
|
+
/** The target of a local `$ref` (`#` or `#/...`) in `root`, or undefined. */
|
|
11
|
+
function resolveLocal(root, ref) {
|
|
12
|
+
if (ref === "#")
|
|
13
|
+
return root;
|
|
14
|
+
if (!ref.startsWith("#/"))
|
|
15
|
+
return undefined;
|
|
16
|
+
let tokens;
|
|
17
|
+
try {
|
|
18
|
+
tokens = ref.slice(2).split("/").map((t) => unescape(decodeURIComponent(t)));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined; // a malformed percent-encoding: unresolved, never an error of the write
|
|
22
|
+
}
|
|
23
|
+
let node = root;
|
|
24
|
+
for (const token of tokens) {
|
|
25
|
+
if (Array.isArray(node))
|
|
26
|
+
node = /^(0|[1-9][0-9]*)$/.test(token) ? node[Number(token)] : undefined;
|
|
27
|
+
else if (isPlainObject(node) && Object.hasOwn(node, token))
|
|
28
|
+
node = node[token];
|
|
29
|
+
else
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
return node;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* ESType: a subschema that states an ES type, with `estype` or with a `$ref` to the definitions document, which counts
|
|
36
|
+
* as the `estype` of the entry (ESType DEFS_EQUIVALENT): the converter converts the values under both.
|
|
37
|
+
*/
|
|
38
|
+
const statesType = (node) => Object.hasOwn(node, "estype") || (typeof node.$ref === "string" && node.$ref.startsWith(DEFINITIONS_ID));
|
|
39
|
+
/** `node` and the subschemas that apply to the same value through `allOf`, `anyOf`, `oneOf`, `then`, `else` and a local `$ref`. */
|
|
40
|
+
function inPlace(node, root, into) {
|
|
41
|
+
if (!isPlainObject(node) || into.has(node))
|
|
42
|
+
return; // a `$ref` cycle ends here
|
|
43
|
+
into.add(node);
|
|
44
|
+
for (const keyword of IN_PLACE_ARRAYS) {
|
|
45
|
+
const list = node[keyword];
|
|
46
|
+
if (Array.isArray(list))
|
|
47
|
+
for (const sub of list)
|
|
48
|
+
inPlace(sub, root, into);
|
|
49
|
+
}
|
|
50
|
+
for (const keyword of IN_PLACE_SINGLE)
|
|
51
|
+
inPlace(node[keyword], root, into);
|
|
52
|
+
if (typeof node.$ref === "string")
|
|
53
|
+
inPlace(resolveLocal(root, node.$ref), root, into);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* D143 amended: `patternProperties` matching with the regular expression engine of the validator (the flag `u`, as
|
|
57
|
+
* Ajv), each expression compiled once, cached by its source. A pattern the engine refuses matches nothing. One per
|
|
58
|
+
* registered schema, so the cache holds only the patterns of that schema.
|
|
59
|
+
*/
|
|
60
|
+
export function patternTest(engine = defaultRegExp) {
|
|
61
|
+
const compiled = new Map();
|
|
62
|
+
return (pattern, name) => {
|
|
63
|
+
let re = compiled.get(pattern);
|
|
64
|
+
if (re === undefined) {
|
|
65
|
+
try {
|
|
66
|
+
re = engine(pattern, "u");
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
re = null;
|
|
70
|
+
}
|
|
71
|
+
compiled.set(pattern, re);
|
|
72
|
+
}
|
|
73
|
+
return re !== null && re.test(name);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** The subschemas that apply to the member `segment` of a value that `node` applies to. */
|
|
77
|
+
function step(node, segment, out, matches) {
|
|
78
|
+
const before = out.length;
|
|
79
|
+
if (typeof segment === "string") {
|
|
80
|
+
if (isPlainObject(node.properties) && Object.hasOwn(node.properties, segment))
|
|
81
|
+
out.push(node.properties[segment]);
|
|
82
|
+
if (isPlainObject(node.patternProperties)) {
|
|
83
|
+
for (const [pattern, sub] of Object.entries(node.patternProperties))
|
|
84
|
+
if (matches(pattern, segment))
|
|
85
|
+
out.push(sub);
|
|
86
|
+
}
|
|
87
|
+
if (out.length === before)
|
|
88
|
+
out.push(node.additionalProperties); // only for the members the two above leave out
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (Array.isArray(node.prefixItems) && segment < node.prefixItems.length)
|
|
92
|
+
out.push(node.prefixItems[segment]);
|
|
93
|
+
else
|
|
94
|
+
out.push(node.items); // only for the elements after `prefixItems`
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* D147.1: the values under every subschema with `estype` of a registered schema, at the paths of Field names and array
|
|
98
|
+
* indexes that `checkFieldNames` gives (D138), through `properties`, `patternProperties`, `additionalProperties`,
|
|
99
|
+
* `items`, `prefixItems`, the in-place applicators and local `$ref`. A union of every branch, so it may own more than
|
|
100
|
+
* the value needs: what the extension does not convert is checked again after conversion (D147.6). Null when the
|
|
101
|
+
* schema has no `estype`.
|
|
102
|
+
*/
|
|
103
|
+
export function ownedValues(schema, matches = patternTest()) {
|
|
104
|
+
// A quick test over every object of the schema: a member named `estype` elsewhere (a Field of `properties`, a `const`
|
|
105
|
+
// object) only makes the predicate non-null, which costs the D147.6 re-check and nothing else.
|
|
106
|
+
const all = new Set();
|
|
107
|
+
collect(schema, all);
|
|
108
|
+
if (![...all].some(statesType))
|
|
109
|
+
return null;
|
|
110
|
+
const roots = new Set();
|
|
111
|
+
inPlace(schema, schema, roots);
|
|
112
|
+
return (path) => {
|
|
113
|
+
if (path[0] === "_meta")
|
|
114
|
+
return false; // Metadata's Field, never validated nor converted (SCHEMA_VALIDATE_WRITES)
|
|
115
|
+
let nodes = roots;
|
|
116
|
+
for (const segment of path) {
|
|
117
|
+
const reached = [];
|
|
118
|
+
for (const node of nodes)
|
|
119
|
+
step(node, segment, reached, matches);
|
|
120
|
+
const next = new Set();
|
|
121
|
+
for (const sub of reached)
|
|
122
|
+
inPlace(sub, schema, next);
|
|
123
|
+
if (next.size === 0)
|
|
124
|
+
return false;
|
|
125
|
+
nodes = next;
|
|
126
|
+
}
|
|
127
|
+
return [...nodes].some(statesType);
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/** Every schema object inside `value`, for the quick test of `ownedValues`. */
|
|
131
|
+
function collect(value, into) {
|
|
132
|
+
if (Array.isArray(value)) {
|
|
133
|
+
for (const element of value)
|
|
134
|
+
collect(element, into);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!isPlainObject(value))
|
|
138
|
+
return;
|
|
139
|
+
into.add(value);
|
|
140
|
+
for (const member of Object.values(value))
|
|
141
|
+
collect(member, into);
|
|
142
|
+
}
|
package/dist/reads.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type AfterReadInput, type HookCtx, type Resource } from "@crud-api/core";
|
|
2
|
+
import { type SchemaEnv } from "./collection.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The registered schema Resource of a data Collection, or null when it has none (SCHEMA_NULL), read once per operation
|
|
5
|
+
* from the system storage and cached in `HookCtx.local` (D147).
|
|
6
|
+
*/
|
|
7
|
+
export declare function registeredSchema(env: SchemaEnv, collection: string, ctx: HookCtx): Promise<Resource | null>;
|
|
8
|
+
/**
|
|
9
|
+
* `afterRead` (D144). On `@schema` with `compiled: true`: the annotation `compiled`, the schema compiled by ESType of
|
|
10
|
+
* every returned Resource with a schema; `get` of a placeholder fails with NOT_FOUND, target `schema`
|
|
11
|
+
* (SCHEMA_NOT_FOUND_TARGET). On a data Collection with a registered schema: the annotation `schema`, its Collection and
|
|
12
|
+
* version (`_meta.version`, null when absent).
|
|
13
|
+
*/
|
|
14
|
+
export declare function readSchema(env: SchemaEnv, input: AfterReadInput, ctx: HookCtx): Promise<Resource[]>;
|
package/dist/reads.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Reads (D144): reads never validate (SCHEMA_NO_READ_VALIDATION); they describe the Result with annotations that
|
|
2
|
+
// Protocols turn into links, raw schemas and `_meta` (HTTP_SCHEMA_DESCRIBEDBY, HTTP_SCHEMA_RAW, MCP_SCHEMA_META).
|
|
3
|
+
import { CrudError, ID_KEY, isPlainObject, isSlug } from "@crud-api/core";
|
|
4
|
+
import { compile } from "@estype/core";
|
|
5
|
+
import { isPlaceholder, SCHEMA_COLLECTION } from "./collection.js";
|
|
6
|
+
/** The key of `HookCtx.local` that caches the registered schemas the operation read, by Collection (D138). */
|
|
7
|
+
const CACHE = "@crud-api/schema registered";
|
|
8
|
+
/**
|
|
9
|
+
* The registered schema Resource of a data Collection, or null when it has none (SCHEMA_NULL), read once per operation
|
|
10
|
+
* from the system storage and cached in `HookCtx.local` (D147).
|
|
11
|
+
*/
|
|
12
|
+
export async function registeredSchema(env, collection, ctx) {
|
|
13
|
+
let cache = ctx.local.get(CACHE);
|
|
14
|
+
if (cache === undefined) {
|
|
15
|
+
cache = new Map();
|
|
16
|
+
ctx.local.set(CACHE, cache);
|
|
17
|
+
}
|
|
18
|
+
const cached = cache.get(collection);
|
|
19
|
+
if (cached !== undefined)
|
|
20
|
+
return cached;
|
|
21
|
+
const request = { kind: "findByIds", collection: SCHEMA_COLLECTION, key: ID_KEY, ids: [collection], projection: null };
|
|
22
|
+
const execCtx = { warn: () => { }, codec: ctx.codec };
|
|
23
|
+
const result = await env.system.execute(env.system.prepare(request, execCtx), execCtx);
|
|
24
|
+
const found = result.kind === "findByIds" ? (result.resources.find((r) => r._id === collection) ?? null) : null;
|
|
25
|
+
cache.set(collection, found);
|
|
26
|
+
return found;
|
|
27
|
+
}
|
|
28
|
+
/** Sets an own enumerable member, also one named `__proto__` (a Slug may be). */
|
|
29
|
+
function define(target, key, value) {
|
|
30
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* `afterRead` (D144). On `@schema` with `compiled: true`: the annotation `compiled`, the schema compiled by ESType of
|
|
34
|
+
* every returned Resource with a schema; `get` of a placeholder fails with NOT_FOUND, target `schema`
|
|
35
|
+
* (SCHEMA_NOT_FOUND_TARGET). On a data Collection with a registered schema: the annotation `schema`, its Collection and
|
|
36
|
+
* version (`_meta.version`, null when absent).
|
|
37
|
+
*/
|
|
38
|
+
export async function readSchema(env, input, ctx) {
|
|
39
|
+
const { collection, resources } = input;
|
|
40
|
+
if (collection === SCHEMA_COLLECTION) {
|
|
41
|
+
if (input.params.compiled !== true)
|
|
42
|
+
return resources;
|
|
43
|
+
const compiled = {};
|
|
44
|
+
for (const resource of resources) {
|
|
45
|
+
if (isPlaceholder(resource) || resource.schema === null) {
|
|
46
|
+
if (input.operation === "get") {
|
|
47
|
+
throw new CrudError("NOT_FOUND", `the Collection ${String(resource._id)} has no registered schema`, { rule: "SCHEMA_NOT_FOUND_TARGET", target: "schema" });
|
|
48
|
+
}
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
define(compiled, resource._id, compile(resource.schema));
|
|
52
|
+
}
|
|
53
|
+
ctx.annotate("compiled", compiled);
|
|
54
|
+
return resources;
|
|
55
|
+
}
|
|
56
|
+
if (!isSlug(collection))
|
|
57
|
+
return resources;
|
|
58
|
+
const registered = await registeredSchema(env, collection, ctx);
|
|
59
|
+
if (registered !== null) {
|
|
60
|
+
const meta = registered._meta;
|
|
61
|
+
const version = isPlainObject(meta) && typeof meta.version === "number" ? meta.version : null;
|
|
62
|
+
ctx.annotate("schema", { collection, version });
|
|
63
|
+
}
|
|
64
|
+
return resources;
|
|
65
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Extension } from "@crud-api/core";
|
|
2
|
+
import { type SchemaValidator } from "./validator.ts";
|
|
3
|
+
/** The specification version this package implements. */
|
|
4
|
+
export declare const SCHEMA_VERSION = "0.1.0";
|
|
5
|
+
/** Options of `schema()` (D139). */
|
|
6
|
+
export interface SchemaOptions {
|
|
7
|
+
/** The JSON Schema validator (D143); default `ajvValidator()`. */
|
|
8
|
+
readonly validator?: SchemaValidator;
|
|
9
|
+
/** SCHEMA_FORCED_STRICT: every schema is stored with `validation: strict` (D148); default false. */
|
|
10
|
+
readonly forceStrict?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The Schema extension: pass it to `createCrudServer({ extensions: [schema(), metadata()] })`, before Relationships
|
|
14
|
+
* and Metadata (D139). It needs the system storage of design 6.10 and a data provider that lists its Collections
|
|
15
|
+
* (SCHEMA_LIST_ALL). One instance serves one Server.
|
|
16
|
+
*/
|
|
17
|
+
export declare function schema(options?: SchemaOptions): Extension & {
|
|
18
|
+
readonly validator: SchemaValidator;
|
|
19
|
+
};
|