@alexify/metaschema 2.0.0 → 3.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
@@ -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 };
@@ -0,0 +1,540 @@
1
+ // The emitters: one per built-in prototype, each rendering as straight-line
2
+ // code the check its `compile()` closes over, so a compiled schema records
3
+ // exactly the issues of the closure backend, in the same order, with the
4
+ // same paths and params. What is not inlined (a reference, a custom type, a
5
+ // validate function, the unknown-keys scan) is the closure backend's own
6
+ // function, called through the scope.
7
+ //
8
+ // Generated code names three things: `v` the value, `c` the context and `k`
9
+ // the key the root was called with. Every other identifier is fresh.
10
+ const { ENUM_SET_SIZE } = require('../util.js');
11
+ const { issues, runValidate } = require('../issues.js');
12
+ const { codePoints, lengthOf, ruleNames } = require('../rules.js');
13
+ const { STRUCT, isStruct } = require('../struct.js');
14
+ const scalars = require('../prototypes/scalars.js');
15
+ const collections = require('../prototypes/collections.js');
16
+ const { schema } = require('../prototypes/schema.js');
17
+ const { tuple } = require('../prototypes/tuple.js');
18
+ const { union, nameOf, tableOf } = require('../prototypes/union.js');
19
+ const { json } = require('../prototypes/json.js');
20
+ const { prop, quote, literal } = require('./code.js');
21
+
22
+ // The key of the field under check, as source: a quoted name, an index, a
23
+ // loop variable, or nothing at the root (`undefined` here, `void 0` there).
24
+ const keyOf = (key) => (key === undefined ? 'void 0' : key);
25
+
26
+ // The path of an issue is the stack of container keys plus the key of the
27
+ // field. The closure backend pushes a container's key before its children;
28
+ // here the keys since the last real push are known at generation time
29
+ // (`prefix`) and pushed only around a statement that records or calls out,
30
+ // so a valid value never touches the path.
31
+ const located = (keys, statement) => {
32
+ const { length } = keys;
33
+ if (length === 0) return statement;
34
+ const pop = length === 1 ? 'c.path.pop();' : `c.path.length -= ${length};`;
35
+ return `c.path.push(${keys.join(', ')}); ${statement} ${pop}`;
36
+ };
37
+
38
+ // A statement that may record, with its path, then the error limit: past it
39
+ // everything stops, up to the nearest union branch or the root.
40
+ const record = (state, statement, extra = []) => {
41
+ const keys = extra.length === 0 ? state.prefix : state.prefix.concat(extra);
42
+ state.code.push(`${located(keys, statement)} if (c.count >= c.limit) break ${state.label};`);
43
+ };
44
+
45
+ // The state under a container: its key joins the prefix of its children.
46
+ const inside = (state, key) =>
47
+ key === undefined ? state : { ...state, prefix: [...state.prefix, key] };
48
+
49
+ const issue = (state, name, args) => `${state.code.ref(issues)}.${name}(c, ${args});`;
50
+
51
+ const typeIssue = (state, expected, x, key) =>
52
+ issue(state, 'type', `${quote(expected)}, ${x}, ${keyOf(key)}`);
53
+
54
+ const notObject = (x) => `${x} === null || typeof ${x} !== "object" || Array.isArray(${x})`;
55
+
56
+ // The conditions of the bounds a field has.
57
+ const outside = (state, x, min, max) => {
58
+ const parts = [];
59
+ if (min !== undefined) parts.push(`${x} < ${state.code.value(min)}`);
60
+ if (max !== undefined) parts.push(`${x} > ${state.code.value(max)}`);
61
+ return parts.join(' || ');
62
+ };
63
+
64
+ const emitLength = (type, x, key, state) => {
65
+ const { code } = state;
66
+ const { min, max } = type.length;
67
+ if (min === undefined && max === undefined) return;
68
+ const n = code.name('n');
69
+ let measure = `${code.ref(lengthOf)}(${x})`;
70
+ if (type.scalar === 'string') {
71
+ measure = type.unicode === true ? `${code.ref(codePoints)}(${x})` : `${x}.length`;
72
+ }
73
+ code.push(`const ${n} = ${measure};`);
74
+ code.push(`if (${outside(state, n, min, max)}) {`);
75
+ const bounds = `${code.value(min)}, ${code.value(max)}, ${n}, ${keyOf(key)}`;
76
+ record(state, issue(state, 'length', bounds));
77
+ code.push('}');
78
+ };
79
+
80
+ const emitPattern = (type, x, key, state) => {
81
+ const { code } = state;
82
+ const { pattern } = type;
83
+ code.push(`if (!${code.ref(pattern)}.test(${x})) {`);
84
+ record(state, issue(state, 'pattern', `${quote(pattern.source)}, ${keyOf(key)}`));
85
+ code.push('}');
86
+ };
87
+
88
+ const emitRange = (type, x, key, state) => {
89
+ const { code } = state;
90
+ const { min, max } = type;
91
+ code.push(`if (${outside(state, x, min, max)}) {`);
92
+ const bounds = `${code.value(min)}, ${code.value(max)}, ${x}, ${keyOf(key)}`;
93
+ record(state, issue(state, 'range', bounds));
94
+ code.push('}');
95
+ };
96
+
97
+ const RULES = Object.assign(Object.create(null), {
98
+ length: emitLength,
99
+ pattern: emitPattern,
100
+ range: emitRange,
101
+ });
102
+
103
+ // The rules of a field in the order the closure backend runs them.
104
+ const rulesOf = (type) => {
105
+ const names = ruleNames(type);
106
+ const list = [];
107
+ for (let index = 0; index < names.length; index += 1) list.push(RULES[names[index]]);
108
+ return list;
109
+ };
110
+
111
+ // The rules, then the validate function on a value that passed them.
112
+ const emitTail = (type, x, key, state, rules) => {
113
+ const { code } = state;
114
+ const { validate } = type;
115
+ const guarded = validate && rules.length > 0;
116
+ const before = guarded ? code.name('b') : '';
117
+ if (guarded) code.push(`const ${before} = c.count;`);
118
+ for (const rule of rules) rule(type, x, key, state);
119
+ if (!validate) return;
120
+ if (guarded) code.push(`if (c.count === ${before}) {`);
121
+ const call = `${code.ref(runValidate)}(${code.ref(type)}, ${code.ref(validate)}, ${x}, c);`;
122
+ record(state, call, key === undefined ? [] : [key]);
123
+ if (guarded) code.push('}');
124
+ };
125
+
126
+ // A type check as `if (fails) { issue } else { body; rules; validate }`: the
127
+ // rules and the validate function run only on a value of the type, and
128
+ // after a body (the elements, the fields) only when it recorded nothing.
129
+ const typed = (type, x, key, state, fails, failure, body) => {
130
+ const { code } = state;
131
+ code.push(`if (${fails}) {`);
132
+ record(state, failure);
133
+ const rules = type === null ? [] : rulesOf(type);
134
+ const tail = type !== null && (rules.length > 0 || type.validate);
135
+ if (body === undefined && !tail) {
136
+ code.push('}');
137
+ return;
138
+ }
139
+ code.push('} else {');
140
+ const before = body !== undefined && tail ? code.name('b') : '';
141
+ if (before) code.push(`const ${before} = c.count;`);
142
+ if (body !== undefined) body();
143
+ if (before) code.push(`if (c.count === ${before}) {`);
144
+ if (tail) emitTail(type, x, key, state, rules);
145
+ if (before) code.push('}');
146
+ code.push('}');
147
+ };
148
+
149
+ const emitScalar = (type, x, key, state) => {
150
+ const { scalar } = type;
151
+ typed(type, x, key, state, `typeof ${x} !== ${quote(scalar)}`, typeIssue(state, scalar, x, key));
152
+ };
153
+
154
+ const emitInteger = (type, x, key, state) =>
155
+ typed(type, x, key, state, `!Number.isInteger(${x})`, typeIssue(state, 'integer', x, key));
156
+
157
+ const emitDate = (type, x, key, state) => {
158
+ const fails = `!(${x}?.constructor?.name === "Date" && !Number.isNaN(${x}.getTime()))`;
159
+ typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
160
+ };
161
+
162
+ const emitNull = (type, x, key, state) =>
163
+ typed(type, x, key, state, `${x} !== null`, typeIssue(state, 'null', x, key));
164
+
165
+ const emitJson = (type, x, key, state) => {
166
+ const fails = `${x} === null || typeof ${x} !== "object"`;
167
+ typed(type, x, key, state, fails, typeIssue(state, 'object', x, key));
168
+ };
169
+
170
+ // Any value at all; only a validate function can say otherwise.
171
+ const emitAny = (type, x, key, state) => emitTail(type, x, key, state, []);
172
+
173
+ const emitEnum = (type, x, key, state) => {
174
+ const { code } = state;
175
+ const values = type.enum;
176
+ const { length } = values;
177
+ let fails;
178
+ if (length > ENUM_SET_SIZE) {
179
+ fails = `!${code.ref(new Set(values))}.has(${x})`;
180
+ } else {
181
+ // A chain of comparisons with the literals, unless a value has none
182
+ // (NaN, an object): then the list itself, as the closure backend scans it.
183
+ let chain = '';
184
+ for (let index = 0; index < length; index += 1) {
185
+ const text = literal(values[index]);
186
+ if (text === undefined) {
187
+ chain = null;
188
+ break;
189
+ }
190
+ chain += `${index === 0 ? '' : ' && '}${x} !== ${text}`;
191
+ }
192
+ fails = chain === null ? `!${code.ref(values)}.includes(${x})` : chain;
193
+ }
194
+ const failure = issue(state, 'enum', `${code.ref(values)}, ${keyOf(key)}`);
195
+ typed(type, x, key, state, fails, failure);
196
+ };
197
+
198
+ const emitObject = (type, x, key, state) => {
199
+ const { code } = state;
200
+ const failure = typeIssue(state, type.type, x, key);
201
+ typed(type, x, key, state, notObject(x), failure, () => {
202
+ const children = inside(state, key);
203
+ const count = code.name('t');
204
+ const name = code.name('n');
205
+ const label = code.name('o');
206
+ code.push(`let ${count} = 0;`);
207
+ code.push(`${label}: for (const ${name} in ${x}) {`);
208
+ code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
209
+ code.push(`${count} += 1;`);
210
+ if (type.key === 'string') {
211
+ const item = code.name('x');
212
+ code.push(`const ${item} = ${x}[${name}];`);
213
+ emitField(type.value, item, name, children);
214
+ } else {
215
+ // A key of an object is a string, so any other key type fails on the
216
+ // first key, as it does in the closure backend.
217
+ record(children, issue(state, 'key', `${quote(type.key)}, ${name}`));
218
+ code.push(`break ${label};`);
219
+ }
220
+ code.push('}');
221
+ if (!type.required) return;
222
+ code.push(`if (${count} === 0) {`);
223
+ record(state, issue(state, 'required', keyOf(key)));
224
+ code.push('}');
225
+ });
226
+ };
227
+
228
+ const emitMap = (type, x, key, state) => {
229
+ const { code } = state;
230
+ const failure = typeIssue(state, type.type, x, key);
231
+ typed(type, x, key, state, `${x}?.constructor?.name !== "Map"`, failure, () => {
232
+ if (type.required) {
233
+ code.push(`if (${x}.size === 0) {`);
234
+ record(state, issue(state, 'required', keyOf(key)));
235
+ code.push('} else {');
236
+ } else {
237
+ code.push(`if (${x}.size !== 0) {`);
238
+ }
239
+ const children = inside(state, key);
240
+ const label = code.name('m');
241
+ const pair = code.name('p');
242
+ const name = code.name('n');
243
+ const item = code.name('x');
244
+ code.push(`${label}: for (const ${pair} of ${x}) {`);
245
+ code.push(`const ${name} = ${pair}[0];`);
246
+ code.push(`if (typeof ${name} !== ${quote(type.key)}) {`);
247
+ record(children, issue(state, 'key', `${quote(type.key)}, ${name}`));
248
+ code.push(`break ${label};`);
249
+ code.push('}');
250
+ code.push(`const ${item} = ${pair}[1];`);
251
+ emitField(type.value, item, name, children);
252
+ code.push('}');
253
+ code.push('}');
254
+ });
255
+ };
256
+
257
+ // An array by index, a Set through its iterator; only the type test differs.
258
+ const emitList = (type, x, key, state) => {
259
+ const { code } = state;
260
+ const set = type.isInstance === collections.set.isInstance;
261
+ const fails = set ? `${x}?.constructor?.name !== "Set"` : `!Array.isArray(${x})`;
262
+ typed(type, x, key, state, fails, typeIssue(state, type.type, x, key), () => {
263
+ const children = inside(state, key);
264
+ const index = code.name('i');
265
+ const item = code.name('x');
266
+ if (set) {
267
+ code.push(`let ${index} = 0;`);
268
+ code.push(`for (const ${item} of ${x}) {`);
269
+ emitField(type.value, item, index, children);
270
+ code.push(`${index} += 1;`);
271
+ } else {
272
+ code.push(`for (let ${index} = 0; ${index} < ${x}.length; ${index} += 1) {`);
273
+ code.push(`const ${item} = ${x}[${index}];`);
274
+ emitField(type.value, item, index, children);
275
+ }
276
+ code.push('}');
277
+ });
278
+ };
279
+
280
+ const emitTuple = (type, x, key, state) => {
281
+ const { code } = state;
282
+ const elements = type.value;
283
+ const { length } = elements;
284
+ typed(type, x, key, state, `!Array.isArray(${x})`, typeIssue(state, type.type, x, key), () => {
285
+ code.push(`if (${x}.length > ${length}) {`);
286
+ record(state, issue(state, 'length', `void 0, ${length}, ${x}.length, ${keyOf(key)}`));
287
+ code.push('} else {');
288
+ const children = inside(state, key);
289
+ for (let index = 0; index < length; index += 1) {
290
+ const item = code.name('x');
291
+ code.push(`const ${item} = ${x}[${index}];`);
292
+ emitField(elements[index], item, String(index), children);
293
+ }
294
+ code.push('}');
295
+ });
296
+ };
297
+
298
+ // The fields of a struct over `x`: a keyed load per field, `Object.hasOwn`
299
+ // only to tell a missing required key from one set to undefined (first for a
300
+ // field named after a member of Object.prototype), and the unknown-keys scan
301
+ // only when the value has more keys than the plan found.
302
+ const emitStruct = (fields, x, key, state) => {
303
+ const { code } = state;
304
+ const { plan, known } = fields[STRUCT];
305
+ const children = inside(state, key);
306
+ const found = code.name('f');
307
+ code.push(`let ${found} = 0;`);
308
+ for (const entry of plan) {
309
+ const { required, own } = entry;
310
+ const name = quote(entry.key);
311
+ const item = code.name('x');
312
+ if (entry.aliases.length > 0) {
313
+ // A field with aliases, when the value has nothing under its own key:
314
+ // the first alias the value carries, and the key the check reports
315
+ // under, as `aliasOf` in struct.js finds them.
316
+ const alias = code.name('k');
317
+ const inherited = own ? ` || !Object.hasOwn(${x}, ${name})` : '';
318
+ code.push(`let ${item} = ${prop(x, entry.key)}, ${alias} = ${name};`);
319
+ code.push(`if (${item} === undefined${inherited}) { ${item} = undefined;`);
320
+ // The first alias the value carries: once one is taken the rest are
321
+ // skipped, as the chain of the closure backend stops at it, and the
322
+ // context learns that a field was read from an alias, as there.
323
+ for (const other of entry.aliases) {
324
+ const taken = `${alias} = ${quote(other)}; ${item} = ${prop(x, other)}; c.renamed = true;`;
325
+ code.push(`if (${alias} === ${name} && Object.hasOwn(${x}, ${quote(other)})) { ${taken} }`);
326
+ }
327
+ code.push('}');
328
+ if (required) {
329
+ code.push(`if (${item} === undefined && !Object.hasOwn(${x}, ${alias})) {`);
330
+ record(children, issue(state, 'required', name));
331
+ code.push('} else {');
332
+ } else {
333
+ code.push(`if (${item} !== undefined) {`);
334
+ }
335
+ code.push(`${found} += 1;`);
336
+ emitField(entry.type, item, alias, children);
337
+ code.push('}');
338
+ continue;
339
+ }
340
+ code.push(`const ${item} = ${prop(x, entry.key)};`);
341
+ if (required) {
342
+ const missing = own ? '' : `${item} === undefined && `;
343
+ code.push(`if (${missing}!Object.hasOwn(${x}, ${name})) {`);
344
+ record(children, issue(state, 'required', name));
345
+ code.push('} else {');
346
+ } else {
347
+ const present = own ? ` && Object.hasOwn(${x}, ${name})` : '';
348
+ code.push(`if (${item} !== undefined${present}) {`);
349
+ }
350
+ code.push(`${found} += 1;`);
351
+ emitField(entry.type, item, name, children);
352
+ code.push('}');
353
+ }
354
+ const total = code.name('t');
355
+ const name = code.name('n');
356
+ const unexpected = code.name('u');
357
+ code.push('if (c.unknown === "reject") {');
358
+ code.push(`let ${total} = 0;`);
359
+ code.push(`for (const ${name} in ${x}) ${total} += 1;`);
360
+ code.push(`if (${total} !== ${found}) {`);
361
+ // The scan of struct.js with the known keys as cases: a key for...in
362
+ // yields is an internalized string, so a case is a pointer comparison
363
+ // where a dictionary lookup would hash it.
364
+ let cases = '';
365
+ for (const field in known) cases += `case ${quote(field)}: `;
366
+ code.push(`let ${unexpected} = null;`);
367
+ code.push(`for (const ${name} in ${x}) {`);
368
+ if (cases !== '') code.push(`switch (${name}) { ${cases}continue; }`);
369
+ code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
370
+ code.push(`if (${unexpected} === null) ${unexpected} = [];`);
371
+ code.push(`${unexpected}.push(${name});`);
372
+ code.push('}');
373
+ code.push(`if (${unexpected} !== null) {`);
374
+ record(children, issue(state, 'unexpected', unexpected));
375
+ code.push('}');
376
+ code.push('}');
377
+ code.push('}');
378
+ };
379
+
380
+ // A nested struct: its fields, then the validate function it carries. A
381
+ // Schema instance of one type used as a field is that type (its validate, if
382
+ // any, is the field's own: a schema of one type has no schema-level one).
383
+ const emitSchema = (type, x, key, state) => {
384
+ const fields = type.schema;
385
+ if (!isStruct(fields)) {
386
+ emitField(fields, x, key, state);
387
+ return;
388
+ }
389
+ const body = () => emitStruct(fields, x, key, state);
390
+ typed(type, x, key, state, notObject(x), typeIssue(state, 'object', x, key), body);
391
+ };
392
+
393
+ // Without a discriminator the branches are tried in order and what a failed
394
+ // branch recorded is dropped, so the error limit inside a branch stops that
395
+ // branch only. With one, the branch is picked by the value of that field.
396
+ const emitUnion = (type, x, key, state) => {
397
+ const { code } = state;
398
+ const { discriminator } = type;
399
+ const branches = type.union;
400
+ if (discriminator === undefined) {
401
+ const before = code.name('b');
402
+ const pending = code.name('a');
403
+ const label = code.name('u');
404
+ code.push(`const ${before} = c.count;`);
405
+ // The validators a failed branch set aside in an async check go with its
406
+ // issues, as in the closure backend.
407
+ code.push(`const ${pending} = c.async === null ? 0 : c.async.length;`);
408
+ code.push(`${label}: {`);
409
+ for (const branch of branches) {
410
+ const own = code.name('u');
411
+ code.push(`${own}: {`);
412
+ emitField(branch, x, key, { ...state, label: own });
413
+ code.push('}');
414
+ code.push(`if (c.count === ${before}) break ${label};`);
415
+ code.push(`c.issues.length = ${before}; c.count = ${before};`);
416
+ code.push(`if (c.async !== null) c.async.length = ${pending};`);
417
+ }
418
+ const names = [];
419
+ for (let index = 0; index < branches.length; index += 1) names.push(nameOf(branches[index]));
420
+ record(state, issue(state, 'union', `${code.ref(names)}, void 0, ${keyOf(key)}`));
421
+ code.push('}');
422
+ if (!type.validate) return;
423
+ code.push(`if (c.count === ${before}) {`);
424
+ emitTail(type, x, key, state, []);
425
+ code.push('}');
426
+ return;
427
+ }
428
+ const fails = `${x} === null || typeof ${x} !== "object"`;
429
+ typed(type, x, key, state, fails, typeIssue(state, 'object', x, key), () => {
430
+ // The literals of the discriminator values, by branch; a value with no
431
+ // literal (NaN, an object) selects its branch through the table of value
432
+ // to branch index the closure backend uses.
433
+ const expected = [];
434
+ const cases = [];
435
+ let direct = true;
436
+ for (let index = 0; index < branches.length; index += 1) {
437
+ const values = branches[index].schema[discriminator].enum;
438
+ const texts = [];
439
+ for (let at = 0; at < values.length; at += 1) {
440
+ const text = literal(values[at]);
441
+ if (text === undefined) direct = false;
442
+ expected.push(values[at]);
443
+ texts.push(text);
444
+ }
445
+ cases.push(texts);
446
+ }
447
+ const subject = prop(x, discriminator);
448
+ code.push(`switch (${direct ? subject : `${code.ref(tableOf(type))}.get(${subject})`}) {`);
449
+ for (let index = 0; index < branches.length; index += 1) {
450
+ if (direct) {
451
+ const texts = cases[index];
452
+ for (let at = 0; at < texts.length; at += 1) code.push(`case ${texts[at]}:`);
453
+ } else {
454
+ code.push(`case ${index}:`);
455
+ }
456
+ code.push('{');
457
+ emitField(branches[index], x, key, state);
458
+ code.push('break;');
459
+ code.push('}');
460
+ }
461
+ code.push('default: {');
462
+ const name = quote(discriminator);
463
+ record(inside(state, key), issue(state, 'union', `${code.ref(expected)}, ${name}, ${name}`));
464
+ code.push('}');
465
+ code.push('}');
466
+ });
467
+ };
468
+
469
+ const EMITTERS = new Map([
470
+ [scalars.string.compile, emitScalar],
471
+ [scalars.integer.compile, emitInteger],
472
+ [scalars.date.compile, emitDate],
473
+ [scalars.null.compile, emitNull],
474
+ [scalars.any.compile, emitAny],
475
+ [scalars.enum.compile, emitEnum],
476
+ [json.compile, emitJson],
477
+ [collections.object.compile, emitObject],
478
+ [collections.map.compile, emitMap],
479
+ [collections.array.compile, emitList],
480
+ [tuple.compile, emitTuple],
481
+ [union.compile, emitUnion],
482
+ [schema.compile, emitSchema],
483
+ ]);
484
+
485
+ // The check of one field over the local `x`. A built-in prototype is
486
+ // inlined by the emitter of its `compile`; a reference, a custom type or a
487
+ // prototype with a compile of its own is its closure, which does everything
488
+ // (rules, validate and nullable included). An optional field skips null and
489
+ // undefined, a nullable one null, before anything else.
490
+ const emitField = (type, x, key, state) => {
491
+ const emitter = EMITTERS.get(type.compile);
492
+ if (emitter === undefined) {
493
+ record(state, `${state.code.ref(type.check)}(${x}, c, ${keyOf(key)});`);
494
+ return;
495
+ }
496
+ const { code } = state;
497
+ const { required } = type;
498
+ let guard = null;
499
+ if (!required) guard = `${x} != null`;
500
+ else if (type.nullable === true) guard = `${x} !== null`;
501
+ if (guard !== null) code.push(`if (${guard}) {`);
502
+ emitter(type, x, key, state);
503
+ if (guard !== null) code.push('}');
504
+ };
505
+
506
+ // The body of a schema's check, `(v, c, k)`: the key the root was called
507
+ // with (through a reference) is pushed on the path at entry, so the root
508
+ // records with no key of its own and everything under it carries `k`; the
509
+ // schema-level validate runs last, on a value whose fields all passed.
510
+ const emitRoot = (target, code) => {
511
+ const { fields, options } = target;
512
+ const { validate } = options;
513
+ const state = { code, label: 'r', prefix: [] };
514
+ const before = validate ? code.name('b') : '';
515
+ if (validate) code.push(`const ${before} = c.count;`);
516
+ code.push('if (k !== undefined) c.path.push(k);');
517
+ code.push('r: {');
518
+ if (isStruct(fields)) {
519
+ const body = () => emitStruct(fields, 'v', undefined, state);
520
+ typed(
521
+ null,
522
+ 'v',
523
+ undefined,
524
+ state,
525
+ notObject('v'),
526
+ typeIssue(state, 'object', 'v', undefined),
527
+ body,
528
+ );
529
+ } else {
530
+ emitField(fields, 'v', undefined, state);
531
+ }
532
+ code.push('}');
533
+ if (validate) {
534
+ const call = `${code.ref(runValidate)}(${code.ref(target)}, ${code.ref(validate)}, v, c);`;
535
+ code.push(`if (c.count === ${before}) ${call}`);
536
+ }
537
+ code.push('if (k !== undefined) c.path.pop();');
538
+ };
539
+
540
+ module.exports = { emitRoot };
@@ -0,0 +1,38 @@
1
+ import type { Model, Schema, SchemaDefinitionError } from '../../index.js';
2
+
3
+ export interface CompileOptions {
4
+ // 'auto' (the default) generates the check where the environment allows
5
+ // code generation from strings and keeps the closure backend silently where
6
+ // it does not; true throws `SchemaDefinitionError` with the code
7
+ // `ERR_NO_EVAL` instead of falling back; false never generates code.
8
+ jit?: 'auto' | boolean;
9
+ // Told of every schema the default mode could not compile, with the
10
+ // `ERR_JIT_BUILD` error (the error of the generator as its `cause`); the
11
+ // schema keeps its closures.
12
+ onFallback?: (schema: Schema, error: SchemaDefinitionError) => void;
13
+ }
14
+
15
+ export interface Compiled {
16
+ // Whether the check runs generated code now; false in the fallback, where
17
+ // the closure backend is left as it is.
18
+ accelerated: boolean;
19
+ // What stopped the first check that could not be generated (`ERR_JIT_BUILD`,
20
+ // the generator's error as its `cause`); absent where the environment allows
21
+ // no code generation at all, and after `{ jit: false }`.
22
+ error?: SchemaDefinitionError;
23
+ }
24
+
25
+ // Replaces the check of a schema, or of every entity of a model, with the
26
+ // generated one. The issues are the ones the closure backend records, in the
27
+ // same order. A target that is neither is a `TypeError`. With `jit: true` a
28
+ // check that cannot be generated throws `ERR_JIT_BUILD` and nothing is
29
+ // installed; `{ jit: false }` puts the closures back.
30
+ export function compile(target: Schema | Model, options?: CompileOptions): Compiled;
31
+
32
+ // Compiles every schema built from now on with these options; a later call
33
+ // replaces them, `{ jit: false }` stops it. A schema built before the call is
34
+ // not touched: pass it to `compile`.
35
+ export function register(options?: CompileOptions): void;
36
+
37
+ // Whether this environment allows code generation from strings; probed once.
38
+ export function canEval(): boolean;