@alexify/metaschema 2.0.0 → 3.0.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/CHANGELOG.md +324 -1
- package/README.md +117 -12
- package/SECURITY.md +27 -8
- package/index.d.ts +319 -83
- package/package.json +21 -6
- package/src/codec.js +490 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +512 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +65 -19
- package/src/errors.js +10 -1
- package/src/generators/index.d.ts +29 -0
- package/src/generators/index.js +90 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +0 -2
- package/src/issues.js +117 -22
- package/src/kinds.js +9 -12
- package/src/lint.js +20 -12
- package/src/locales/en.js +10 -2
- package/src/locales/uk.js +7 -2
- package/src/metadata.js +41 -44
- package/src/metautil.js +8 -1
- package/src/model.js +10 -15
- package/src/preprocessor.js +5 -10
- package/src/prototypes/abstract.js +14 -1
- package/src/prototypes/collections.js +20 -3
- package/src/prototypes/reference.js +17 -3
- package/src/prototypes/scalars.js +1 -3
- package/src/prototypes/schema.js +12 -0
- package/src/prototypes/tuple.js +14 -9
- package/src/prototypes/union.js +57 -18
- package/src/result.js +5 -14
- package/src/rules.js +55 -26
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +120 -101
- package/src/struct.js +18 -7
- package/src/types.js +5 -11
- package/src/util.js +39 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexify/metaschema",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — data validation, domain models and TypeScript generation",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Alex Dolid <dolid.sasha@gmail.com>",
|
|
@@ -34,6 +34,14 @@
|
|
|
34
34
|
"./locales/uk": {
|
|
35
35
|
"types": "./src/locales/uk.d.ts",
|
|
36
36
|
"default": "./src/locales/uk.js"
|
|
37
|
+
},
|
|
38
|
+
"./generators": {
|
|
39
|
+
"types": "./src/generators/index.d.ts",
|
|
40
|
+
"default": "./src/generators/index.js"
|
|
41
|
+
},
|
|
42
|
+
"./compile": {
|
|
43
|
+
"types": "./src/compile/index.d.ts",
|
|
44
|
+
"default": "./src/compile/index.js"
|
|
37
45
|
}
|
|
38
46
|
},
|
|
39
47
|
"directories": {
|
|
@@ -73,25 +81,32 @@
|
|
|
73
81
|
"metarhia"
|
|
74
82
|
],
|
|
75
83
|
"devDependencies": {
|
|
84
|
+
"@sinclair/typebox": "^0.34.52",
|
|
76
85
|
"@standard-schema/spec": "^1.1.0",
|
|
77
86
|
"@vercel/analytics": "^2.0.1",
|
|
78
87
|
"@vercel/speed-insights": "^2.0.0",
|
|
88
|
+
"ajv": "^8.20.0",
|
|
89
|
+
"ajv-formats": "^3.0.1",
|
|
79
90
|
"c8": "^12.0.0",
|
|
80
91
|
"esbuild": "^0.28.2",
|
|
81
92
|
"oxfmt": "^0.72.0",
|
|
82
93
|
"oxlint": "^1.75.0",
|
|
83
94
|
"tsd": "^0.33.0",
|
|
84
95
|
"typescript": "^7.0.2",
|
|
85
|
-
"
|
|
96
|
+
"valibot": "^1.5.0",
|
|
97
|
+
"vitepress": "^1.6.4",
|
|
98
|
+
"zod": "^4.6.5"
|
|
86
99
|
},
|
|
87
100
|
"scripts": {
|
|
88
101
|
"test": "node --test tests/unit/*.test.js",
|
|
102
|
+
"test:jit": "node --require ./tests/helpers/jit.js --test tests/unit/*.test.js",
|
|
103
|
+
"test:nojit": "node --disallow-code-generation-from-strings --require ./tests/helpers/jit.js --test tests/unit/*.test.js",
|
|
89
104
|
"test:coverage": "c8 --all --include 'src/**' --check-coverage --lines 98 --statements 98 --branches 90 --functions 100 --reporter text --reporter lcov node --test tests/unit/*.test.js",
|
|
90
105
|
"test:types": "tsd",
|
|
91
|
-
"check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts",
|
|
92
|
-
"lint": "oxlint src tests scripts bench",
|
|
93
|
-
"format": "oxfmt src tests scripts bench",
|
|
94
|
-
"format:check": "oxfmt --check src tests scripts bench",
|
|
106
|
+
"check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts",
|
|
107
|
+
"lint": "oxlint index.js browser.js src tests scripts bench",
|
|
108
|
+
"format": "oxfmt index.js browser.js src tests scripts bench",
|
|
109
|
+
"format:check": "oxfmt --check index.js browser.js src tests scripts bench",
|
|
95
110
|
"size": "node scripts/size.js",
|
|
96
111
|
"bench": "node bench/bench.js",
|
|
97
112
|
"docs:dev": "vitepress dev docs",
|
package/src/codec.js
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
// What parse and serialize do beyond the check: the defaults, the decoders,
|
|
2
|
+
// the serializers and the stripping of unknown keys, as passes over the built
|
|
3
|
+
// types. `parse` is the check of the schema (whichever backend installed it)
|
|
4
|
+
// between two passes, defaults before and decoders after; `serialize` is one
|
|
5
|
+
// pass the other way. The passes read the same plan the closures walk and
|
|
6
|
+
// validate nothing themselves, so the JIT needs no second generator. A node
|
|
7
|
+
// whose subtree carries nothing for a phase is returned as it is, and a
|
|
8
|
+
// container is copied only when one of its parts changed: the value given is
|
|
9
|
+
// never written to.
|
|
10
|
+
const { hasBrand, define } = require('./util.js');
|
|
11
|
+
const { EMPTY, NONE, issues, isThenable, abandon, pathOf, toDotPath } = require('./issues.js');
|
|
12
|
+
const { createContext } = require('./context.js');
|
|
13
|
+
const { STRUCT, isStruct } = require('./struct.js');
|
|
14
|
+
const { asyncReturn } = require('./errors.js');
|
|
15
|
+
const collections = require('./prototypes/collections.js');
|
|
16
|
+
const { schema: struct } = require('./prototypes/schema.js');
|
|
17
|
+
const { tuple } = require('./prototypes/tuple.js');
|
|
18
|
+
const { union, tableOf } = require('./prototypes/union.js');
|
|
19
|
+
const { reference, embeds } = require('./prototypes/reference.js');
|
|
20
|
+
|
|
21
|
+
// What a subtree carries, as bits; a phase is the bit it applies.
|
|
22
|
+
const DEFAULTS = 1;
|
|
23
|
+
const DECODERS = 2;
|
|
24
|
+
const ENCODERS = 4;
|
|
25
|
+
const STRUCTS = 8;
|
|
26
|
+
const ASYNC = 16;
|
|
27
|
+
|
|
28
|
+
// The shape of a node: a Schema, a struct (the dictionary of its fields), or
|
|
29
|
+
// a field by the identity of its prototype's compile, as the JIT tells them
|
|
30
|
+
// apart; anything else (a scalar, a custom type) is a leaf.
|
|
31
|
+
const LEAF = 0;
|
|
32
|
+
const SCHEMA = 1;
|
|
33
|
+
const FIELDS = 2;
|
|
34
|
+
const NESTED = 3;
|
|
35
|
+
const LIST = 4;
|
|
36
|
+
const KEYED = 5;
|
|
37
|
+
const TUPLE = 6;
|
|
38
|
+
const UNION = 7;
|
|
39
|
+
const REFERENCE = 8;
|
|
40
|
+
|
|
41
|
+
const SHAPES = new Map([
|
|
42
|
+
[struct.compile, NESTED],
|
|
43
|
+
[collections.array.compile, LIST],
|
|
44
|
+
[collections.object.compile, KEYED],
|
|
45
|
+
[collections.map.compile, KEYED],
|
|
46
|
+
[tuple.compile, TUPLE],
|
|
47
|
+
[union.compile, UNION],
|
|
48
|
+
[reference.compile, REFERENCE],
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
const shapeOf = (node) => {
|
|
52
|
+
if (hasBrand(node, 'Schema')) return SCHEMA;
|
|
53
|
+
if (isStruct(node)) return FIELDS;
|
|
54
|
+
const shape = SHAPES.get(node.compile);
|
|
55
|
+
return shape === undefined ? LEAF : shape;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const isAsyncFunction = (fn) => typeof fn === 'function' && fn.constructor.name === 'AsyncFunction';
|
|
59
|
+
|
|
60
|
+
// What the passes know about a node, computed on first use and kept apart
|
|
61
|
+
// from the node: its shape, the bits of its subtree, its own decoder and
|
|
62
|
+
// serializer, its children with their infos, the fields of a struct a phase
|
|
63
|
+
// has to visit (`parts`, by phase bit; every field under `strip`), and the
|
|
64
|
+
// reference fields beneath it (their targets are resolved at parse time, so a
|
|
65
|
+
// reference counts as carrying everything).
|
|
66
|
+
const INFO = new WeakMap();
|
|
67
|
+
|
|
68
|
+
const infoOf = (node) => {
|
|
69
|
+
let info = INFO.get(node);
|
|
70
|
+
if (info !== undefined) return info;
|
|
71
|
+
const shape = shapeOf(node);
|
|
72
|
+
// A struct's own functions belong to the node that holds it.
|
|
73
|
+
const own = shape === SCHEMA ? node.options : shape === FIELDS ? EMPTY : node;
|
|
74
|
+
const decode = own.parse || undefined;
|
|
75
|
+
const encode = own.serialize || undefined;
|
|
76
|
+
let bits = decode === undefined ? 0 : DECODERS;
|
|
77
|
+
if (encode !== undefined) bits |= ENCODERS;
|
|
78
|
+
if (isAsyncFunction(own.validate) || isAsyncFunction(decode) || isAsyncFunction(own.checkType)) {
|
|
79
|
+
bits |= ASYNC;
|
|
80
|
+
}
|
|
81
|
+
const children = [];
|
|
82
|
+
const infos = [];
|
|
83
|
+
const refs = [];
|
|
84
|
+
let plan = null;
|
|
85
|
+
let extra = null;
|
|
86
|
+
let table = null;
|
|
87
|
+
let parts = null;
|
|
88
|
+
if (shape === SCHEMA) children.push(node.fields);
|
|
89
|
+
else if (shape === FIELDS) {
|
|
90
|
+
const compiled = node[STRUCT];
|
|
91
|
+
plan = compiled.plan;
|
|
92
|
+
extra = compiled.calculated;
|
|
93
|
+
bits |= STRUCTS;
|
|
94
|
+
} else if (shape === NESTED) children.push(node.schema);
|
|
95
|
+
else if (shape === LIST || shape === KEYED) children.push(node.value);
|
|
96
|
+
else if (shape === TUPLE) {
|
|
97
|
+
for (let index = 0; index < node.value.length; index += 1) children.push(node.value[index]);
|
|
98
|
+
} else if (shape === UNION) {
|
|
99
|
+
const branches = node.union;
|
|
100
|
+
if (node.discriminator !== undefined) table = tableOf(node);
|
|
101
|
+
for (let index = 0; index < branches.length; index += 1) children.push(branches[index]);
|
|
102
|
+
} else if (shape === REFERENCE) {
|
|
103
|
+
bits |= DEFAULTS | DECODERS | ENCODERS | STRUCTS;
|
|
104
|
+
refs.push(node);
|
|
105
|
+
}
|
|
106
|
+
if (plan === null) {
|
|
107
|
+
for (let index = 0; index < children.length; index += 1) {
|
|
108
|
+
const sub = infoOf(children[index]);
|
|
109
|
+
infos.push(sub);
|
|
110
|
+
bits |= sub.bits;
|
|
111
|
+
for (let at = 0; at < sub.refs.length; at += 1) refs.push(sub.refs[at]);
|
|
112
|
+
}
|
|
113
|
+
} else {
|
|
114
|
+
// One pass over the plan: the child and its info, and the fields each
|
|
115
|
+
// phase has to visit (every field under strip).
|
|
116
|
+
parts = { [DEFAULTS]: [], [DECODERS]: [], [ENCODERS]: [], [STRUCTS]: [] };
|
|
117
|
+
for (let index = 0; index < plan.length; index += 1) {
|
|
118
|
+
const { type } = plan[index];
|
|
119
|
+
const sub = infoOf(type);
|
|
120
|
+
children.push(type);
|
|
121
|
+
infos.push(sub);
|
|
122
|
+
bits |= sub.bits;
|
|
123
|
+
for (let at = 0; at < sub.refs.length; at += 1) refs.push(sub.refs[at]);
|
|
124
|
+
const defaulted = type.default !== undefined;
|
|
125
|
+
if (defaulted) bits |= DEFAULTS;
|
|
126
|
+
if (defaulted || (sub.bits & DEFAULTS) !== 0) parts[DEFAULTS].push(index);
|
|
127
|
+
if ((sub.bits & DECODERS) !== 0) parts[DECODERS].push(index);
|
|
128
|
+
if ((sub.bits & ENCODERS) !== 0) parts[ENCODERS].push(index);
|
|
129
|
+
parts[STRUCTS].push(index);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
info = { shape, bits, decode, encode, children, infos, plan, parts, extra, table, refs };
|
|
133
|
+
INFO.set(node, info);
|
|
134
|
+
return info;
|
|
135
|
+
};
|
|
136
|
+
// Whether a schema has an async function among its validators, decoders and
|
|
137
|
+
// custom checkTypes, the entities it references included: `~standard` then
|
|
138
|
+
// validates through parseAsync.
|
|
139
|
+
const hasAsync = (schema, visited = new Set()) => {
|
|
140
|
+
const info = infoOf(schema);
|
|
141
|
+
if ((info.bits & ASYNC) !== 0) return true;
|
|
142
|
+
visited.add(schema);
|
|
143
|
+
for (const ref of info.refs) {
|
|
144
|
+
const target = ref.root.findReference(ref.one || ref.many);
|
|
145
|
+
if (target !== null && !visited.has(target) && hasAsync(target, visited)) return true;
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// Writes into an object of the output: a key of the plan or of the value is
|
|
151
|
+
// data, so `__proto__` lands as an own property.
|
|
152
|
+
const putKey = (out, key, value) => {
|
|
153
|
+
if (key === '__proto__') define(out, key, value);
|
|
154
|
+
else out[key] = value;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const putIndex = (out, index, value) => {
|
|
158
|
+
out[index] = value;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const putEntry = (out, key, value) => {
|
|
162
|
+
out.set(key, value);
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const copy = (value) => ({ ...value });
|
|
166
|
+
|
|
167
|
+
const toMap = (value) => new Map(value);
|
|
168
|
+
|
|
169
|
+
const toSet = (list) => new Set(list);
|
|
170
|
+
|
|
171
|
+
// The output of a container under construction: the container is copied at
|
|
172
|
+
// the first part that changed (`clone`), a part is written with `put`, and
|
|
173
|
+
// the parts that decoded asynchronously are written in once they settle (a
|
|
174
|
+
// decoder that failed resolved to nothing and recorded its issue). A
|
|
175
|
+
// container pushes its key on the path for its parts.
|
|
176
|
+
const enter = (context, key, value, clone, put) => {
|
|
177
|
+
if (key !== undefined) context.path.push(key);
|
|
178
|
+
return { context, key, value, clone, put, out: null, pending: null };
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// A part that is still decoding: only a decoder makes a promise (a thenable
|
|
182
|
+
// it returns is adopted as one, below), and only in an async parse; a value
|
|
183
|
+
// of the data with a `then` of its own is data, never awaited.
|
|
184
|
+
const isPending = (context, value) => context.async !== null && value instanceof Promise;
|
|
185
|
+
|
|
186
|
+
const take = (state, key, result, phase) => {
|
|
187
|
+
if (state.out === null) state.out = state.clone(state.value);
|
|
188
|
+
state.put(state.out, key, result);
|
|
189
|
+
if (phase === DECODERS && isPending(state.context, result)) {
|
|
190
|
+
if (state.pending === null) state.pending = [];
|
|
191
|
+
state.pending.push(key, result);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// What a promise of the passes resolves to: a box around the value, never
|
|
196
|
+
// the value itself, because a promise adopts a value with a `then` of its
|
|
197
|
+
// own and the value of a program may well have one.
|
|
198
|
+
const boxed = (value) => ({ value });
|
|
199
|
+
|
|
200
|
+
const leave = (state, wrap) => {
|
|
201
|
+
const { context, key, out, pending, put } = state;
|
|
202
|
+
if (key !== undefined) context.path.pop();
|
|
203
|
+
if (out === null) return state.value;
|
|
204
|
+
if (pending === null) return wrap === undefined ? out : wrap(out);
|
|
205
|
+
const promises = [];
|
|
206
|
+
for (let index = 1; index < pending.length; index += 2) promises.push(pending[index]);
|
|
207
|
+
return Promise.all(promises).then((boxes) => {
|
|
208
|
+
for (let index = 0; index < boxes.length; index += 1) {
|
|
209
|
+
put(out, pending[index * 2], boxes[index].value);
|
|
210
|
+
}
|
|
211
|
+
return boxed(wrap === undefined ? out : wrap(out));
|
|
212
|
+
});
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// Runs `fn` with the path of the context set to where a value was met: a
|
|
216
|
+
// promise settles after the walk has unwound.
|
|
217
|
+
const at = (context, path, fn) => {
|
|
218
|
+
const saved = context.path;
|
|
219
|
+
context.path = path;
|
|
220
|
+
try {
|
|
221
|
+
return fn();
|
|
222
|
+
} finally {
|
|
223
|
+
context.path = saved;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
// The decoder of a node over a value whose parts decoded: its exception is an
|
|
228
|
+
// issue at the field, and the result is gone; a promise is awaited where
|
|
229
|
+
// parseAsync allows it and an error in a synchronous parse. Once a decoder
|
|
230
|
+
// failed, none runs: the result is invalid already.
|
|
231
|
+
const decode = (info, node, value, context, key) => {
|
|
232
|
+
const fn = info.decode;
|
|
233
|
+
if (fn === undefined || context.count > 0) return value;
|
|
234
|
+
if (isPending(context, value)) {
|
|
235
|
+
const where = pathOf(context, key);
|
|
236
|
+
return value.then((box) => {
|
|
237
|
+
const out = at(context, where, () => decode(info, node, box.value, context));
|
|
238
|
+
return out instanceof Promise ? out : boxed(out);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
let out;
|
|
242
|
+
try {
|
|
243
|
+
out = fn.call(node, value);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
issues.exception(context, error, key);
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
if (!isThenable(out)) return out;
|
|
249
|
+
const where = pathOf(context, key);
|
|
250
|
+
if (context.async === null) {
|
|
251
|
+
abandon(out);
|
|
252
|
+
throw asyncReturn('decoder', toDotPath(where, context.root), 'parseAsync');
|
|
253
|
+
}
|
|
254
|
+
// A real Promise of a box from here on, whatever the decoder returned; a
|
|
255
|
+
// decoder that failed resolves to nothing and records its issue.
|
|
256
|
+
return Promise.resolve(out).then(boxed, (error) => {
|
|
257
|
+
if (context.count < context.limit) at(context, where, () => issues.exception(context, error));
|
|
258
|
+
return boxed(undefined);
|
|
259
|
+
});
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
const walkLeaf = (info, node, value) => value;
|
|
263
|
+
|
|
264
|
+
const walkInner = (info, node, value, context, key, phase) =>
|
|
265
|
+
apply(info.infos[0], info.children[0], value, context, key, phase);
|
|
266
|
+
|
|
267
|
+
// Before the check (the defaults, a serialization) a graph may loop through
|
|
268
|
+
// its references; the records on the way down are kept in `seen`, which the
|
|
269
|
+
// caller clears before the check. A loop is marked there: the copies the
|
|
270
|
+
// defaults make cannot close it, so parse checks such a value as it was
|
|
271
|
+
// given, and the check reports the loop. After the check a loop cannot be
|
|
272
|
+
// there.
|
|
273
|
+
const LOOP = Symbol('loop');
|
|
274
|
+
|
|
275
|
+
const looped = (context) => context.seen !== null && context.seen.has(LOOP);
|
|
276
|
+
|
|
277
|
+
const walkSchema = (info, node, value, context, key, phase) => {
|
|
278
|
+
if (phase === DECODERS || info.refs.length === 0 || typeof value !== 'object') {
|
|
279
|
+
return walkInner(info, node, value, context, key, phase);
|
|
280
|
+
}
|
|
281
|
+
if (context.seen === null) context.seen = new Set();
|
|
282
|
+
const { seen } = context;
|
|
283
|
+
if (seen.has(value)) {
|
|
284
|
+
seen.add(LOOP);
|
|
285
|
+
return value;
|
|
286
|
+
}
|
|
287
|
+
seen.add(value);
|
|
288
|
+
const out = walkInner(info, node, value, context, key, phase);
|
|
289
|
+
seen.delete(value);
|
|
290
|
+
return out;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// The fields of a struct: a default fills a missing key before the check, a
|
|
294
|
+
// decoder replaces the value after it. Stripping rebuilds the object from
|
|
295
|
+
// the known keys; otherwise the object is copied when a field changed.
|
|
296
|
+
const walkFields = (info, fields, value, context, key, phase, want) => {
|
|
297
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
298
|
+
const { plan, infos, extra } = info;
|
|
299
|
+
const strip = (want & STRUCTS) !== 0;
|
|
300
|
+
const parts = info.parts[strip ? STRUCTS : phase];
|
|
301
|
+
const state = enter(context, key, value, copy, putKey);
|
|
302
|
+
if (strip) state.out = {};
|
|
303
|
+
for (let position = 0; position < parts.length; position += 1) {
|
|
304
|
+
const index = parts[position];
|
|
305
|
+
const entry = plan[index];
|
|
306
|
+
const name = entry.key;
|
|
307
|
+
let item = entry.own && !Object.hasOwn(value, name) ? undefined : value[name];
|
|
308
|
+
if (item === undefined && phase === DEFAULTS) {
|
|
309
|
+
const fallback = entry.type.default;
|
|
310
|
+
if (fallback === undefined) continue;
|
|
311
|
+
item = typeof fallback === 'function' ? fallback() : fallback;
|
|
312
|
+
take(state, name, item, phase);
|
|
313
|
+
}
|
|
314
|
+
const result = apply(infos[index], entry.type, item, context, name, phase);
|
|
315
|
+
if (strip ? result !== undefined : result !== item) take(state, name, result, phase);
|
|
316
|
+
}
|
|
317
|
+
if (strip) {
|
|
318
|
+
for (let index = 0; index < extra.length; index += 1) {
|
|
319
|
+
const name = extra[index];
|
|
320
|
+
if (Object.hasOwn(value, name)) putKey(state.out, name, value[name]);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return leave(state);
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
// The elements of an array, a Set or a tuple, by position; a Set comes back
|
|
327
|
+
// as a Set.
|
|
328
|
+
const walkItems = (children, infos, fixed, value, context, key, phase) => {
|
|
329
|
+
const set = !Array.isArray(value);
|
|
330
|
+
if (set && (fixed || value.constructor?.name !== 'Set')) return value;
|
|
331
|
+
const state = enter(context, key, value, Array.from, putIndex);
|
|
332
|
+
let index = 0;
|
|
333
|
+
for (const item of value) {
|
|
334
|
+
const slot = fixed ? index : 0;
|
|
335
|
+
if (slot >= children.length) break;
|
|
336
|
+
const result = apply(infos[slot], children[slot], item, context, index, phase);
|
|
337
|
+
if (result !== item) take(state, index, result, phase);
|
|
338
|
+
index += 1;
|
|
339
|
+
}
|
|
340
|
+
return leave(state, set ? toSet : undefined);
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const walkList = (info, node, value, context, key, phase) =>
|
|
344
|
+
walkItems(info.children, info.infos, info.shape === TUPLE, value, context, key, phase);
|
|
345
|
+
|
|
346
|
+
// The values of an object or a Map, by key.
|
|
347
|
+
const walkKeyed = (info, node, value, context, key, phase) => {
|
|
348
|
+
const map = value.constructor?.name === 'Map';
|
|
349
|
+
if (!map && (typeof value !== 'object' || Array.isArray(value))) return value;
|
|
350
|
+
const child = info.children[0];
|
|
351
|
+
const sub = info.infos[0];
|
|
352
|
+
const state = enter(context, key, value, map ? toMap : copy, map ? putEntry : putKey);
|
|
353
|
+
if (map) {
|
|
354
|
+
for (const pair of value) {
|
|
355
|
+
const name = pair[0];
|
|
356
|
+
const item = pair[1];
|
|
357
|
+
const result = apply(sub, child, item, context, name, phase);
|
|
358
|
+
if (result !== item) take(state, name, result, phase);
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
// The own keys of the object, in order, as the check iterates them.
|
|
362
|
+
for (const name in value) {
|
|
363
|
+
if (!Object.hasOwn(value, name)) continue;
|
|
364
|
+
const item = value[name];
|
|
365
|
+
const result = apply(sub, child, item, context, name, phase);
|
|
366
|
+
if (result !== item) take(state, name, result, phase);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return leave(state);
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
// The context for trying the branches of a plain union, one per parse, made
|
|
373
|
+
// at the first plain union met: the policies and the root of the parse, one
|
|
374
|
+
// issue at most, and a list for the promises so that a validator is set aside
|
|
375
|
+
// as the check sets it aside instead of failing the trial.
|
|
376
|
+
const scratchOf = (context) => {
|
|
377
|
+
let scratch = context.scratch;
|
|
378
|
+
if (scratch === null) {
|
|
379
|
+
scratch = createContext(undefined, context.root, context.unknown);
|
|
380
|
+
scratch.references = context.references;
|
|
381
|
+
scratch.limit = 1;
|
|
382
|
+
scratch.async = [];
|
|
383
|
+
context.scratch = scratch;
|
|
384
|
+
}
|
|
385
|
+
return scratch;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
// Whether a branch accepts the value, as the check decides it: under the
|
|
389
|
+
// path of the parse (the branch pushes the key as the union's check does).
|
|
390
|
+
// The validators the trial set aside are not run: the check of the value
|
|
391
|
+
// picks the branch and runs them for real.
|
|
392
|
+
const accepts = (branch, value, scratch, path, key) => {
|
|
393
|
+
scratch.issues = NONE;
|
|
394
|
+
scratch.count = 0;
|
|
395
|
+
scratch.path = path;
|
|
396
|
+
const list = scratch.async;
|
|
397
|
+
list.length = 0;
|
|
398
|
+
branch.check(value, scratch, key);
|
|
399
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
400
|
+
if (list[index].promise !== null) abandon(list[index].promise);
|
|
401
|
+
}
|
|
402
|
+
return scratch.count === 0;
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
// The branch of a union a value belongs to: by the discriminator, or the
|
|
406
|
+
// first branch whose check records nothing, as the check picks it. Before
|
|
407
|
+
// the check a branch is tried with its own defaults in place, and the value
|
|
408
|
+
// with those defaults is what parse goes on with.
|
|
409
|
+
const walkUnion = (info, node, value, context, key, phase) => {
|
|
410
|
+
const { children, infos, table } = info;
|
|
411
|
+
if (table !== null) {
|
|
412
|
+
if (typeof value !== 'object') return value;
|
|
413
|
+
const index = table.get(value[node.discriminator]);
|
|
414
|
+
if (index === undefined) return value;
|
|
415
|
+
return apply(infos[index], children[index], value, context, key, phase);
|
|
416
|
+
}
|
|
417
|
+
const scratch = scratchOf(context);
|
|
418
|
+
for (let index = 0; index < children.length; index += 1) {
|
|
419
|
+
const branch = children[index];
|
|
420
|
+
const sub = infos[index];
|
|
421
|
+
const prepared = phase === DEFAULTS ? apply(sub, branch, value, context, key, phase) : value;
|
|
422
|
+
if (!accepts(branch, prepared, scratch, context.path, key)) continue;
|
|
423
|
+
return phase === DEFAULTS ? prepared : apply(sub, branch, value, context, key, phase);
|
|
424
|
+
}
|
|
425
|
+
return value;
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// A reference resolved at parse time, as the check resolves it: an id stays
|
|
429
|
+
// an id, a record goes through its entity, and a record deeper than the
|
|
430
|
+
// check allows is left as it is for the check to report.
|
|
431
|
+
const walkReference = (info, node, value, context, key, phase) => {
|
|
432
|
+
const { one, many, root, embed } = node;
|
|
433
|
+
const target = root.findReference(one || many);
|
|
434
|
+
if (target === null || !embeds(target, embed, context.references)) return value;
|
|
435
|
+
if (context.depth >= context.maxDepth) return value;
|
|
436
|
+
const sub = infoOf(target);
|
|
437
|
+
context.depth += 1;
|
|
438
|
+
let out = value;
|
|
439
|
+
if (one) out = apply(sub, target, value, context, key, phase);
|
|
440
|
+
else if (Array.isArray(value)) {
|
|
441
|
+
// The target as the one child of the list, kept on the info from one
|
|
442
|
+
// visit to the next (it changes only when the namespaces do).
|
|
443
|
+
if (info.children[0] !== target) {
|
|
444
|
+
info.children[0] = target;
|
|
445
|
+
info.infos[0] = sub;
|
|
446
|
+
}
|
|
447
|
+
out = walkItems(info.children, info.infos, false, value, context, key, phase);
|
|
448
|
+
}
|
|
449
|
+
context.depth -= 1;
|
|
450
|
+
return out;
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
const WALKERS = [
|
|
454
|
+
walkLeaf,
|
|
455
|
+
walkSchema,
|
|
456
|
+
walkFields,
|
|
457
|
+
walkInner,
|
|
458
|
+
walkList,
|
|
459
|
+
walkKeyed,
|
|
460
|
+
walkList,
|
|
461
|
+
walkUnion,
|
|
462
|
+
walkReference,
|
|
463
|
+
];
|
|
464
|
+
|
|
465
|
+
// One pass over a value from a node whose info is known, by the shape of
|
|
466
|
+
// each node. A serializer runs before the parts of its value, a decoder
|
|
467
|
+
// after them; stripping concerns every struct, so under `strip` the pass
|
|
468
|
+
// enters any subtree with one.
|
|
469
|
+
const apply = (info, node, value, context, key, phase) => {
|
|
470
|
+
if (value == null) return value;
|
|
471
|
+
const want = phase === DECODERS && context.unknown === 'strip' ? DECODERS | STRUCTS : phase;
|
|
472
|
+
if ((info.bits & want) === 0) return value;
|
|
473
|
+
let input = value;
|
|
474
|
+
if (phase === ENCODERS && info.encode !== undefined) {
|
|
475
|
+
input = info.encode.call(node, value);
|
|
476
|
+
if (input == null) return input;
|
|
477
|
+
}
|
|
478
|
+
const out = WALKERS[info.shape](info, node, input, context, key, phase, want);
|
|
479
|
+
return phase === DECODERS ? decode(info, node, out, context, key) : out;
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
module.exports = {
|
|
483
|
+
PREPARE: DEFAULTS,
|
|
484
|
+
FINISH: DECODERS,
|
|
485
|
+
SERIALIZE: ENCODERS,
|
|
486
|
+
infoOf,
|
|
487
|
+
apply,
|
|
488
|
+
looped,
|
|
489
|
+
hasAsync,
|
|
490
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// The builder of the generated source. Generated code holds identifiers,
|
|
2
|
+
// numbers, booleans and JSON strings only: a regular expression, a Set, a
|
|
3
|
+
// function, a nested check or a dictionary of known keys goes into the scope
|
|
4
|
+
// and is reached by name (the ajv and schemasafe rule, ROADMAP P9), so
|
|
5
|
+
// nothing taken from a schema is ever part of the source text.
|
|
6
|
+
const { IDENTIFIER } = require('../util.js');
|
|
7
|
+
|
|
8
|
+
// JSON.stringify leaves U+2028 and U+2029 in place (legal in a string literal
|
|
9
|
+
// since ES2019); they are escaped anyway, so the source holds no line
|
|
10
|
+
// terminator a tool that reads it could trip on.
|
|
11
|
+
const TERMINATORS = new RegExp(`[${String.fromCharCode(0x2028, 0x2029)}]`, 'g');
|
|
12
|
+
|
|
13
|
+
const escape = (char) => `\\u${char.charCodeAt(0).toString(16)}`;
|
|
14
|
+
|
|
15
|
+
const quote = (text) => JSON.stringify(text).replace(TERMINATORS, escape);
|
|
16
|
+
|
|
17
|
+
// `object.key` for an identifier, `object["key"]` for any other string, and
|
|
18
|
+
// `object[0]` for an index.
|
|
19
|
+
const prop = (object, key) => {
|
|
20
|
+
if (typeof key === 'number') return `${object}[${key}]`;
|
|
21
|
+
return IDENTIFIER.test(key) ? `${object}.${key}` : `${object}[${quote(key)}]`;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// The source text of a primitive that has an exact one; anything else is
|
|
25
|
+
// undefined and goes through the scope. A finite number round-trips through
|
|
26
|
+
// String, except -0, which prints as 0.
|
|
27
|
+
const literal = (value) => {
|
|
28
|
+
switch (typeof value) {
|
|
29
|
+
case 'string':
|
|
30
|
+
return quote(value);
|
|
31
|
+
case 'boolean':
|
|
32
|
+
return String(value);
|
|
33
|
+
case 'bigint':
|
|
34
|
+
return `${value}n`;
|
|
35
|
+
case 'undefined':
|
|
36
|
+
return 'void 0';
|
|
37
|
+
case 'number':
|
|
38
|
+
return Number.isFinite(value) && !Object.is(value, -0) ? String(value) : undefined;
|
|
39
|
+
default:
|
|
40
|
+
return value === null ? 'null' : undefined;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
class Code {
|
|
45
|
+
#names = 0;
|
|
46
|
+
#scope = new Map();
|
|
47
|
+
values = [];
|
|
48
|
+
lines = [];
|
|
49
|
+
|
|
50
|
+
// A fresh identifier.
|
|
51
|
+
name(prefix) {
|
|
52
|
+
this.#names += 1;
|
|
53
|
+
return `${prefix}${this.#names}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The name of a real value in the scope; the same value is added once.
|
|
57
|
+
ref(value) {
|
|
58
|
+
let name = this.#scope.get(value);
|
|
59
|
+
if (name === undefined) {
|
|
60
|
+
name = `s${this.values.length}`;
|
|
61
|
+
this.#scope.set(value, name);
|
|
62
|
+
this.values.push(value);
|
|
63
|
+
}
|
|
64
|
+
return name;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A primitive as its literal, anything else by name.
|
|
68
|
+
value(value) {
|
|
69
|
+
const text = literal(value);
|
|
70
|
+
return text === undefined ? this.ref(value) : text;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
push(line) {
|
|
74
|
+
this.lines.push(line);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The source of a factory over the scope that returns the check: strict
|
|
78
|
+
// code, named after the schema in a stack trace (`name` has no line
|
|
79
|
+
// terminator once encoded).
|
|
80
|
+
source(name = '') {
|
|
81
|
+
let names = '';
|
|
82
|
+
for (let index = 0; index < this.values.length; index += 1) {
|
|
83
|
+
names += `${index === 0 ? '' : ', '}s${index} = scope[${index}]`;
|
|
84
|
+
}
|
|
85
|
+
const preamble = names === '' ? '' : `const ${names};\n`;
|
|
86
|
+
const url = `alexify-metaschema-jit/${encodeURIComponent(name) || 'anonymous'}`;
|
|
87
|
+
const body = this.lines.join('\n');
|
|
88
|
+
return `"use strict";\n${preamble}return function jit(v, c, k) {\n${body}\n};\n//# sourceURL=${url}`;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
module.exports = { IDENTIFIER, quote, prop, literal, Code };
|