@alexify/metaschema 3.2.0 → 3.4.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 +307 -1
- package/README.md +173 -89
- package/SECURITY.md +24 -1
- package/index.d.ts +601 -29
- package/package.json +28 -3
- package/src/checks.js +789 -0
- package/src/codec.js +201 -46
- package/src/coerce/index.d.ts +34 -0
- package/src/coerce/index.js +385 -0
- package/src/compile/emit.js +87 -28
- package/src/compile/index.js +9 -4
- package/src/context.js +6 -1
- package/src/definition/index.d.ts +19 -0
- package/src/definition/index.js +27 -0
- package/src/derive/index.d.ts +86 -0
- package/src/derive/index.js +273 -0
- package/src/errors.js +46 -4
- package/src/formats/index.d.ts +20 -8
- package/src/formats/index.js +450 -39
- package/src/generators/fromjsonschema.js +21 -2
- package/src/generators/index.js +1 -1
- package/src/generators/jsonschema.js +90 -21
- package/src/generators/typescript.js +11 -0
- package/src/index.js +3 -2
- package/src/issues.js +9 -7
- package/src/kinds.js +15 -3
- package/src/lint.js +38 -0
- package/src/locales/en.js +6 -0
- package/src/locales/uk.js +6 -0
- package/src/metadata.js +6 -24
- package/src/model/data.js +67 -10
- package/src/model/diff.js +7 -4
- package/src/model/index.js +1 -1
- package/src/model/infer.js +10 -3
- package/src/model/merge.js +16 -9
- package/src/model/restore.js +52 -7
- package/src/model/sample.js +28 -4
- package/src/model.js +54 -56
- package/src/mongodb/bson.js +130 -0
- package/src/mongodb/document.js +217 -0
- package/src/mongodb/index.d.ts +133 -0
- package/src/mongodb/index.js +24 -0
- package/src/mongodb/indexes.js +79 -0
- package/src/mongodb/update.js +258 -0
- package/src/preprocessor.js +1 -2
- package/src/prototypes/abstract.js +41 -67
- package/src/prototypes/collections.js +3 -90
- package/src/prototypes/flags.js +34 -0
- package/src/prototypes/json.js +0 -11
- package/src/prototypes/reference.js +0 -76
- package/src/prototypes/scalars.js +17 -96
- package/src/prototypes/schema.js +1 -10
- package/src/prototypes/tuple.js +0 -26
- package/src/prototypes/union.js +12 -82
- package/src/rules.js +33 -157
- package/src/schema.js +105 -220
- package/src/snapshot.js +216 -41
- package/src/stream/index.js +1 -1
- package/src/struct.js +6 -91
- package/src/types.js +43 -6
- package/src/util.js +43 -0
- package/src/validation.js +313 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// The `./coerce` subpath: the converters of coercion, by type name. The core
|
|
2
|
+
// has the policy (`coerce` of a parse call, of the kind metadata, of a field)
|
|
3
|
+
// and the step in the pass before the check; it converts nothing until
|
|
4
|
+
// register() installed the table here. The converters are strict: a string
|
|
5
|
+
// is a number only when it is written as one, a boolean only as `true`,
|
|
6
|
+
// `false`, `1` or `0`, a date only with its zone, and the empty string is
|
|
7
|
+
// never converted. A value a converter cannot read comes back as it was, so
|
|
8
|
+
// the check reports it as given.
|
|
9
|
+
const { hasBrand, isSet, isMap } = require('../util.js');
|
|
10
|
+
const { isFirstLower } = require('../metautil.js');
|
|
11
|
+
const { Schema } = require('../validation.js');
|
|
12
|
+
const { createContext } = require('../context.js');
|
|
13
|
+
const { COERCE, COERCION, PREPARE, infoOf, apply, wantOf, looped } = require('../codec.js');
|
|
14
|
+
const { SchemaDefinitionError, invalidTarget, invalidOption } = require('../errors.js');
|
|
15
|
+
|
|
16
|
+
// The integer digits and the fraction are told apart by the dot alone:
|
|
17
|
+
// `\d+\.?\d*` reads a run of digits two ways and is quadratic on a run
|
|
18
|
+
// that ends in something else.
|
|
19
|
+
const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
20
|
+
const INTEGER = /^[+-]?\d+$/;
|
|
21
|
+
const ISO =
|
|
22
|
+
/^(\d{4})-(\d{2})-(\d{2})(?:[Tt ]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d))?$/;
|
|
23
|
+
const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
24
|
+
|
|
25
|
+
const toNumber = (value) => {
|
|
26
|
+
if (typeof value === 'string') {
|
|
27
|
+
if (!DECIMAL.test(value)) return value;
|
|
28
|
+
const number = Number(value);
|
|
29
|
+
return Number.isFinite(number) ? number : value;
|
|
30
|
+
}
|
|
31
|
+
if (typeof value === 'bigint' && value >= -SAFE && value <= SAFE) return Number(value);
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const toInteger = (value) => {
|
|
36
|
+
const number = toNumber(value);
|
|
37
|
+
return Number.isSafeInteger(number) ? number : value;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const toBigint = (value) => {
|
|
41
|
+
if (typeof value === 'string') return INTEGER.test(value) ? BigInt(value) : value;
|
|
42
|
+
return Number.isSafeInteger(value) ? BigInt(value) : value;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const toBoolean = (value) => {
|
|
46
|
+
if (value === 'true' || value === '1' || value === 1) return true;
|
|
47
|
+
if (value === 'false' || value === '0' || value === 0) return false;
|
|
48
|
+
return value;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const isLeap = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
52
|
+
|
|
53
|
+
const daysIn = (year, month) => {
|
|
54
|
+
if (month === 2) return isLeap(year) ? 29 : 28;
|
|
55
|
+
return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// A calendar date (midnight UTC) or a date-time with its zone: a local time
|
|
59
|
+
// would depend on the zone of the server. The engine rolls `2026-02-31`
|
|
60
|
+
// over to March, so the day is checked here.
|
|
61
|
+
const toDate = (value) => {
|
|
62
|
+
if (typeof value === 'number') {
|
|
63
|
+
const date = new Date(value);
|
|
64
|
+
return Number.isNaN(date.getTime()) ? value : date;
|
|
65
|
+
}
|
|
66
|
+
if (typeof value !== 'string') return value;
|
|
67
|
+
const match = ISO.exec(value);
|
|
68
|
+
if (match === null) return value;
|
|
69
|
+
const month = Number(match[2]);
|
|
70
|
+
const day = Number(match[3]);
|
|
71
|
+
if (month < 1 || month > 12 || day < 1 || day > daysIn(Number(match[1]), month)) return value;
|
|
72
|
+
const text = match[4] === undefined ? value : `${value.slice(0, 10)}T${value.slice(11)}`;
|
|
73
|
+
const date = new Date(text.toUpperCase());
|
|
74
|
+
return Number.isNaN(date.getTime()) ? value : date;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const toText = (value) => {
|
|
78
|
+
const type = typeof value;
|
|
79
|
+
if (type === 'number') return Number.isFinite(value) ? String(value) : value;
|
|
80
|
+
return type === 'bigint' || type === 'boolean' ? String(value) : value;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// Canonical base64 (RFC 4648 §4): padded, and with the bits the padding
|
|
84
|
+
// leaves unused at zero, so that one text is one value; what a decoder
|
|
85
|
+
// would forgive (whitespace, a missing `=`, the URL alphabet) is left to
|
|
86
|
+
// the check. A charset, a length and the last quantum rather than one
|
|
87
|
+
// expression of quanta, whose repetition grows the stack of the engine by a
|
|
88
|
+
// frame each and overflowed it on a valid text of a few megabytes (the
|
|
89
|
+
// formats subpath reads base64 the same way). `''` is the text of no bytes.
|
|
90
|
+
const ALPHABET = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
91
|
+
|
|
92
|
+
const isBase64 = (text) => {
|
|
93
|
+
const { length } = text;
|
|
94
|
+
if (length % 4 !== 0 || !ALPHABET.test(text)) return false;
|
|
95
|
+
if (text[length - 1] !== '=') return true;
|
|
96
|
+
if (text[length - 2] === '=') return 'AQgw'.includes(text[length - 3]);
|
|
97
|
+
return 'AEIMQUYcgkosw048'.includes(text[length - 2]);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// A text whose bytes would be over `length.max` is not decoded: the check
|
|
101
|
+
// rejects it, and a converter runs before the check, so this is what bounds
|
|
102
|
+
// what it allocates.
|
|
103
|
+
const toBytes = (value, field) => {
|
|
104
|
+
if (typeof value !== 'string' || !isBase64(value)) return value;
|
|
105
|
+
const max = field.length?.max;
|
|
106
|
+
const pad = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
|
|
107
|
+
if (max !== undefined && (value.length / 4) * 3 - pad > max) return value;
|
|
108
|
+
if (Uint8Array.fromBase64 !== undefined) return Uint8Array.fromBase64(value);
|
|
109
|
+
const text = atob(value);
|
|
110
|
+
const bytes = new Uint8Array(text.length);
|
|
111
|
+
for (let index = 0; index < text.length; index += 1) bytes[index] = text.charCodeAt(index);
|
|
112
|
+
return bytes;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const isPrimitive = (value) => {
|
|
116
|
+
const type = typeof value;
|
|
117
|
+
return type === 'number' || type === 'boolean' || type === 'bigint';
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// The member a value is written as: a string for a number, a boolean or a
|
|
121
|
+
// bigint member, or one of those for a string member.
|
|
122
|
+
const toEnum = (value, field) => {
|
|
123
|
+
const members = field.enum;
|
|
124
|
+
if (members.includes(value)) return value;
|
|
125
|
+
const text = typeof value === 'string';
|
|
126
|
+
if (!text && !isPrimitive(value)) return value;
|
|
127
|
+
for (const member of members) {
|
|
128
|
+
if (text ? isPrimitive(member) && String(member) === value : member === String(value)) {
|
|
129
|
+
return member;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return value;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
// The same, with the members and their written forms indexed once for the
|
|
136
|
+
// field: a visit of a large enum is a lookup, not a scan.
|
|
137
|
+
const enumConverterOf = (field) => {
|
|
138
|
+
const members = new Set(field.enum);
|
|
139
|
+
const written = new Map();
|
|
140
|
+
const strings = new Set();
|
|
141
|
+
for (const member of field.enum) {
|
|
142
|
+
if (typeof member === 'string') strings.add(member);
|
|
143
|
+
else if (isPrimitive(member)) {
|
|
144
|
+
const text = String(member);
|
|
145
|
+
if (!written.has(text)) written.set(text, member);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return (value) => {
|
|
149
|
+
if (members.has(value)) return value;
|
|
150
|
+
if (typeof value === 'string') return written.has(value) ? written.get(value) : value;
|
|
151
|
+
if (!isPrimitive(value)) return value;
|
|
152
|
+
const text = String(value);
|
|
153
|
+
return strings.has(text) ? text : value;
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// A single value where a list is expected (`?tag=a` against `?tag=a&tag=b`).
|
|
158
|
+
const isItem = (value) => (typeof value === 'string' ? value !== '' : isPrimitive(value));
|
|
159
|
+
|
|
160
|
+
const toArray = (value) => {
|
|
161
|
+
if (isSet(value)) return Array.from(value);
|
|
162
|
+
return isItem(value) ? [value] : value;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const toSet = (value) => {
|
|
166
|
+
if (Array.isArray(value)) return new Set(value);
|
|
167
|
+
return isItem(value) ? new Set([value]) : value;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const isPairs = (value) => {
|
|
171
|
+
for (const pair of value) if (!Array.isArray(pair) || pair.length !== 2) return false;
|
|
172
|
+
return true;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// A plain object of any realm: a Set, a Date or a typed array has a
|
|
176
|
+
// prototype in between, and its entries are not the entries of a map.
|
|
177
|
+
const isPlain = (value) => {
|
|
178
|
+
const prototype = Object.getPrototypeOf(value);
|
|
179
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// A plain object or a list of pairs; the keys of a map of numbers that are
|
|
183
|
+
// written as numbers become numbers.
|
|
184
|
+
const toMap = (value, field) => {
|
|
185
|
+
if (value === null || typeof value !== 'object') return value;
|
|
186
|
+
const list = Array.isArray(value);
|
|
187
|
+
if (list ? !isPairs(value) : !isPlain(value)) return value;
|
|
188
|
+
const map = new Map();
|
|
189
|
+
for (const pair of list ? value : Object.entries(value)) {
|
|
190
|
+
const key = field.key === 'number' && typeof pair[0] === 'string' ? toNumber(pair[0]) : pair[0];
|
|
191
|
+
map.set(key, pair[1]);
|
|
192
|
+
}
|
|
193
|
+
return map;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const BUILT_IN = {
|
|
197
|
+
string: toText,
|
|
198
|
+
number: toNumber,
|
|
199
|
+
integer: toInteger,
|
|
200
|
+
bigint: toBigint,
|
|
201
|
+
boolean: toBoolean,
|
|
202
|
+
date: toDate,
|
|
203
|
+
bytes: toBytes,
|
|
204
|
+
enum: toEnum,
|
|
205
|
+
array: toArray,
|
|
206
|
+
set: toSet,
|
|
207
|
+
map: toMap,
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
// The table: a converter by type name, `(value, field) => value`.
|
|
211
|
+
const COERCIONS = Object.create(null);
|
|
212
|
+
|
|
213
|
+
const invalidCoercion = (reason) => new SchemaDefinitionError('ERR_INVALID_COERCION', reason);
|
|
214
|
+
|
|
215
|
+
// The converter of a field: its type's, or the one of the type it is an
|
|
216
|
+
// alias of (`{ money: { js: 'number' } }` converts as a number); an alias
|
|
217
|
+
// names a type registered before it, so the chain ends. The core keeps what
|
|
218
|
+
// is resolved on the info of the node, under the version of the table.
|
|
219
|
+
// The converter a model of the field's own gave for a type name
|
|
220
|
+
// (`new Model(types, entities, database, { coercions })`), before the
|
|
221
|
+
// process-wide one: the models among the namespaces of the schema.
|
|
222
|
+
const ownConverterOf = (root, name) => {
|
|
223
|
+
for (const namespace of root.namespaces) {
|
|
224
|
+
const own = namespace.coercions;
|
|
225
|
+
if (own != null && own[name] !== undefined) return own[name];
|
|
226
|
+
}
|
|
227
|
+
return undefined;
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const converterOf = (field) => {
|
|
231
|
+
let Type = field.constructor;
|
|
232
|
+
let name = field.type;
|
|
233
|
+
for (;;) {
|
|
234
|
+
const converter = ownConverterOf(field.root, name) ?? COERCIONS[name];
|
|
235
|
+
if (converter !== undefined) return converter;
|
|
236
|
+
const js = Type?.source?.js;
|
|
237
|
+
if (typeof js !== 'string') return null;
|
|
238
|
+
name = js;
|
|
239
|
+
Type = field.root.types[js];
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// The hook `register({ onError })` gives: told of a converter that threw,
|
|
244
|
+
// with the field, since the value is left to the check as if the converter
|
|
245
|
+
// could not read it, and a bug in a converter of the program would look the
|
|
246
|
+
// same.
|
|
247
|
+
let onError = null;
|
|
248
|
+
|
|
249
|
+
// What the core asks once per node of a coercing pass (and again after a
|
|
250
|
+
// register()): the converter of the node, closed over it, or null for a
|
|
251
|
+
// node that is not a field (a schema, a struct) or whose type has none. A
|
|
252
|
+
// converter that throws leaves the value to the check.
|
|
253
|
+
const resolve = (node) => {
|
|
254
|
+
const converter = hasBrand(node, 'Type') ? converterOf(node) : null;
|
|
255
|
+
if (converter === null) return null;
|
|
256
|
+
const run = converter === toEnum ? enumConverterOf(node) : converter;
|
|
257
|
+
return (value) => {
|
|
258
|
+
try {
|
|
259
|
+
return run(value, node);
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (onError !== null) onError(error, node);
|
|
262
|
+
return value;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
// An entry of the program: the name of a type, a function, and not another
|
|
268
|
+
// function under a name the table has (a built-in name included).
|
|
269
|
+
const check = (name, converter) => {
|
|
270
|
+
if (!isFirstLower(name)) throw invalidCoercion(`Converter "${name}" needs the name of a type`);
|
|
271
|
+
if (typeof converter !== 'function') {
|
|
272
|
+
throw invalidCoercion(`Converter "${name}" must be a function`);
|
|
273
|
+
}
|
|
274
|
+
const known = COERCIONS[name] ?? BUILT_IN[name];
|
|
275
|
+
if (known !== undefined && known !== converter) {
|
|
276
|
+
const reason = `Converter "${name}" is registered already with another function`;
|
|
277
|
+
throw new SchemaDefinitionError('ERR_COERCION_REGISTERED', reason);
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// The paths of the keys the pass changed (a value converted, a default
|
|
282
|
+
// filled in), read off the output beside the input: a container is copied
|
|
283
|
+
// only where a part of it changed, and a part given back as it is is the
|
|
284
|
+
// same reference, so what differs is what changed. The paths are those of
|
|
285
|
+
// an issue (`PropertyKey[]`, the root `[]`).
|
|
286
|
+
const report = (input, output, path, paths) => {
|
|
287
|
+
if (output === input) return;
|
|
288
|
+
const container = output !== null && typeof output === 'object';
|
|
289
|
+
const given = input !== null && typeof input === 'object';
|
|
290
|
+
if (!container || !given) {
|
|
291
|
+
paths.push(path);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (Array.isArray(output)) {
|
|
295
|
+
if (!Array.isArray(input)) {
|
|
296
|
+
paths.push(path);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
for (let index = 0; index < output.length; index += 1) {
|
|
300
|
+
report(input[index], output[index], [...path, index], paths);
|
|
301
|
+
}
|
|
302
|
+
} else if (isMap(output)) {
|
|
303
|
+
if (!isMap(input)) {
|
|
304
|
+
paths.push(path);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
for (const pair of output) report(input.get(pair[0]), pair[1], [...path, pair[0]], paths);
|
|
308
|
+
} else if (!isPlain(output) || !isPlain(input)) {
|
|
309
|
+
paths.push(path);
|
|
310
|
+
} else {
|
|
311
|
+
for (const key of Object.keys(output)) {
|
|
312
|
+
const before = Object.hasOwn(input, key) ? input[key] : undefined;
|
|
313
|
+
report(before, output[key], [...path, key], paths);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
// The value with the conversions of the schema applied, and its defaults:
|
|
319
|
+
// the pass parse runs before its check, with coercion on and nothing
|
|
320
|
+
// checked. The value given is never written to; it comes back itself when
|
|
321
|
+
// nothing changed, and as it was when it loops through its references.
|
|
322
|
+
// `options.report`, an array, is given the path of every key the pass
|
|
323
|
+
// changed.
|
|
324
|
+
const coerce = (schema, value, options) => {
|
|
325
|
+
if (!hasBrand(schema, 'Schema')) throw invalidTarget('A Schema is expected');
|
|
326
|
+
const context = createContext(options, schema.name, schema.unknown, true);
|
|
327
|
+
const paths = options === undefined ? undefined : options.report;
|
|
328
|
+
if (paths !== undefined && !Array.isArray(paths)) {
|
|
329
|
+
throw invalidOption('report', 'an array', paths);
|
|
330
|
+
}
|
|
331
|
+
const want = wantOf(PREPARE, context) | COERCE;
|
|
332
|
+
const out = apply(infoOf(schema), schema, value, context, undefined, PREPARE, want);
|
|
333
|
+
const result = looped(context) ? value : out;
|
|
334
|
+
if (paths !== undefined) report(value, result, [], paths);
|
|
335
|
+
return result;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// Installed like class members: not enumerable. A copy per subpath rather
|
|
339
|
+
// than a helper of the core: the core is measured on its own, the subpaths
|
|
340
|
+
// on top of it.
|
|
341
|
+
const install = (target, members) => {
|
|
342
|
+
const descriptors = Object.getOwnPropertyDescriptors(members);
|
|
343
|
+
for (const name in descriptors) {
|
|
344
|
+
descriptors[name].enumerable = false;
|
|
345
|
+
Object.defineProperty(target, name, descriptors[name]);
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
let installed = false;
|
|
350
|
+
|
|
351
|
+
// Fills the table with the built-in converters and the program's own, once
|
|
352
|
+
// per name, process-wide (another function under a registered name is
|
|
353
|
+
// ERR_COERCION_REGISTERED; a converter of an alias type is the way to read a
|
|
354
|
+
// type differently), and adds `schema.coerce(value, options)`. Every entry
|
|
355
|
+
// is checked before any is written, so a call that throws leaves the table
|
|
356
|
+
// as it was. `options.onError` is told of a converter that threw.
|
|
357
|
+
const register = (custom = {}, settings = {}) => {
|
|
358
|
+
if (custom === null || typeof custom !== 'object' || Array.isArray(custom)) {
|
|
359
|
+
throw invalidCoercion('The converters must be an object of functions by type name');
|
|
360
|
+
}
|
|
361
|
+
if (settings === null || typeof settings !== 'object') {
|
|
362
|
+
throw invalidCoercion('The options of register must be an object');
|
|
363
|
+
}
|
|
364
|
+
const hook = settings.onError;
|
|
365
|
+
if (hook !== undefined && typeof hook !== 'function') {
|
|
366
|
+
throw invalidCoercion('Option "onError" must be a function');
|
|
367
|
+
}
|
|
368
|
+
const names = Object.keys(custom);
|
|
369
|
+
for (const name of names) check(name, custom[name]);
|
|
370
|
+
for (const name of Object.keys(BUILT_IN)) COERCIONS[name] = BUILT_IN[name];
|
|
371
|
+
for (const name of names) COERCIONS[name] = custom[name];
|
|
372
|
+
if (hook !== undefined) onError = hook;
|
|
373
|
+
COERCION.resolve = resolve;
|
|
374
|
+
COERCION.installed = true;
|
|
375
|
+
COERCION.version += 1;
|
|
376
|
+
if (installed) return;
|
|
377
|
+
installed = true;
|
|
378
|
+
install(Schema.prototype, {
|
|
379
|
+
coerce(value, options) {
|
|
380
|
+
return coerce(this, value, options);
|
|
381
|
+
},
|
|
382
|
+
});
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
module.exports = { COERCIONS, coerce, register };
|
package/src/compile/emit.js
CHANGED
|
@@ -7,16 +7,21 @@
|
|
|
7
7
|
//
|
|
8
8
|
// Generated code names three things: `v` the value, `c` the context and `k`
|
|
9
9
|
// the key the root was called with. Every other identifier is fresh.
|
|
10
|
-
const { ENUM_SET_SIZE } = require('../util.js');
|
|
10
|
+
const { ENUM_SET_SIZE, isBytes } = require('../util.js');
|
|
11
11
|
const { issues, runValidate, release } = require('../issues.js');
|
|
12
|
-
const {
|
|
12
|
+
const { formatOf } = require('../rules.js');
|
|
13
13
|
const { STRUCT, isStruct } = require('../struct.js');
|
|
14
|
-
const scalars = require('../prototypes/scalars.js');
|
|
15
14
|
const collections = require('../prototypes/collections.js');
|
|
16
|
-
const {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
const {
|
|
16
|
+
COMPILE,
|
|
17
|
+
decimalsOff,
|
|
18
|
+
codePoints,
|
|
19
|
+
lengthOf,
|
|
20
|
+
ruleNames,
|
|
21
|
+
patternLimit,
|
|
22
|
+
nameOf,
|
|
23
|
+
tableOf,
|
|
24
|
+
} = require('../checks.js');
|
|
20
25
|
const { prop, quote, literal } = require('./code.js');
|
|
21
26
|
|
|
22
27
|
// The key of the field under check, as source: a quoted name, an index, a
|
|
@@ -75,9 +80,8 @@ const emitLength = (type, x, key, state) => {
|
|
|
75
80
|
if (min === undefined && max === undefined) return;
|
|
76
81
|
const n = code.name('n');
|
|
77
82
|
let measure = `${code.ref(lengthOf)}(${x})`;
|
|
78
|
-
if (type.scalar === 'string') {
|
|
79
|
-
|
|
80
|
-
}
|
|
83
|
+
if (type.scalar === 'string' && type.unicode === true) measure = `${code.ref(codePoints)}(${x})`;
|
|
84
|
+
else if (type.scalar === 'string' || type.scalar === 'bytes') measure = `${x}.length`;
|
|
81
85
|
code.push(`const ${n} = ${measure};`);
|
|
82
86
|
code.push(`if (${outside(state, n, min, max)}) {`);
|
|
83
87
|
const bounds = `${code.value(min)}, ${code.value(max)}, ${n}, ${keyOf(key)}`;
|
|
@@ -103,12 +107,23 @@ const emitPattern = (type, x, key, state) => {
|
|
|
103
107
|
const emitFormat = (type, x, key, state) => {
|
|
104
108
|
const { code } = state;
|
|
105
109
|
const { format } = type;
|
|
106
|
-
const { test } =
|
|
110
|
+
const { test } = formatOf(type);
|
|
107
111
|
code.push(`if (${withinLength(type, x, code)}!${code.ref(test)}(${x})) {`);
|
|
108
112
|
record(state, issue(state, 'format', `${quote(format)}, ${keyOf(key)}`));
|
|
109
113
|
code.push('}');
|
|
110
114
|
};
|
|
111
115
|
|
|
116
|
+
// The decimals of a number, by the test of checks.js (`decimalsOff`); the
|
|
117
|
+
// numbers of the rule reach the source as literals of `code.value`, never as
|
|
118
|
+
// the text of the field.
|
|
119
|
+
const emitDecimals = (type, x, key, state) => {
|
|
120
|
+
const { code } = state;
|
|
121
|
+
const { decimals } = type;
|
|
122
|
+
code.push(`if (${code.ref(decimalsOff)}(${x}, ${code.value(10 ** decimals)})) {`);
|
|
123
|
+
record(state, issue(state, 'decimals', `${code.value(decimals)}, ${x}, ${keyOf(key)}`));
|
|
124
|
+
code.push('}');
|
|
125
|
+
};
|
|
126
|
+
|
|
112
127
|
const emitRange = (type, x, key, state) => {
|
|
113
128
|
const { code } = state;
|
|
114
129
|
const { min, max } = type;
|
|
@@ -122,6 +137,7 @@ const RULES = Object.assign(Object.create(null), {
|
|
|
122
137
|
length: emitLength,
|
|
123
138
|
pattern: emitPattern,
|
|
124
139
|
format: emitFormat,
|
|
140
|
+
decimals: emitDecimals,
|
|
125
141
|
range: emitRange,
|
|
126
142
|
});
|
|
127
143
|
|
|
@@ -184,6 +200,16 @@ const emitDate = (type, x, key, state) => {
|
|
|
184
200
|
typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
|
|
185
201
|
};
|
|
186
202
|
|
|
203
|
+
const emitBytes = (type, x, key, state) =>
|
|
204
|
+
typed(
|
|
205
|
+
type,
|
|
206
|
+
x,
|
|
207
|
+
key,
|
|
208
|
+
state,
|
|
209
|
+
`!${state.code.ref(isBytes)}(${x})`,
|
|
210
|
+
typeIssue(state, 'bytes', x, key),
|
|
211
|
+
);
|
|
212
|
+
|
|
187
213
|
const emitNull = (type, x, key, state) =>
|
|
188
214
|
typed(type, x, key, state, `${x} !== null`, typeIssue(state, 'null', x, key));
|
|
189
215
|
|
|
@@ -250,6 +276,37 @@ const emitObject = (type, x, key, state) => {
|
|
|
250
276
|
});
|
|
251
277
|
};
|
|
252
278
|
|
|
279
|
+
// The own keys of a flags value: a name of the list holds a boolean, any
|
|
280
|
+
// other key is unexpected under the reject policy, as in the closure.
|
|
281
|
+
const emitFlags = (type, x, key, state) => {
|
|
282
|
+
const { code } = state;
|
|
283
|
+
const failure = typeIssue(state, type.type, x, key);
|
|
284
|
+
typed(type, x, key, state, notObject(x), failure, () => {
|
|
285
|
+
const children = inside(state, key);
|
|
286
|
+
const name = code.name('n');
|
|
287
|
+
const item = code.name('x');
|
|
288
|
+
const unexpected = code.name('u');
|
|
289
|
+
let cases = '';
|
|
290
|
+
for (const flag of type.flags) cases += `case ${quote(flag)}: `;
|
|
291
|
+
code.push(`let ${unexpected} = null;`);
|
|
292
|
+
code.push(`for (const ${name} in ${x}) {`);
|
|
293
|
+
code.push(`if (!Object.hasOwn(${x}, ${name})) continue;`);
|
|
294
|
+
code.push(`switch (${name}) { ${cases}{`);
|
|
295
|
+
code.push(`const ${item} = ${x}[${name}];`);
|
|
296
|
+
code.push(`if (typeof ${item} !== "boolean") {`);
|
|
297
|
+
record(children, typeIssue(state, 'boolean', item, name));
|
|
298
|
+
code.push('}');
|
|
299
|
+
code.push('continue; } }');
|
|
300
|
+
code.push(
|
|
301
|
+
`if (c.unknown === "reject") (${unexpected} === null ? (${unexpected} = []) : ${unexpected}).push(${name});`,
|
|
302
|
+
);
|
|
303
|
+
code.push('}');
|
|
304
|
+
code.push(`if (${unexpected} !== null) {`);
|
|
305
|
+
record(children, issue(state, 'unexpected', unexpected));
|
|
306
|
+
code.push('}');
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
|
|
253
310
|
const emitMap = (type, x, key, state) => {
|
|
254
311
|
const { code } = state;
|
|
255
312
|
const failure = typeIssue(state, type.type, x, key);
|
|
@@ -337,7 +394,7 @@ const emitStruct = (fields, x, key, state) => {
|
|
|
337
394
|
if (entry.aliases.length > 0) {
|
|
338
395
|
// A field with aliases, when the value has nothing under its own key:
|
|
339
396
|
// the first alias the value carries, and the key the check reports
|
|
340
|
-
// under, as `aliasOf`
|
|
397
|
+
// under, as `aliasOf` of checks.js finds them.
|
|
341
398
|
const alias = code.name('k');
|
|
342
399
|
const inherited = own ? ` || !Object.hasOwn(${x}, ${name})` : '';
|
|
343
400
|
code.push(`let ${item} = ${prop(x, entry.key)}, ${alias} = ${name};`);
|
|
@@ -383,9 +440,9 @@ const emitStruct = (fields, x, key, state) => {
|
|
|
383
440
|
code.push(`let ${total} = 0;`);
|
|
384
441
|
code.push(`for (const ${name} in ${x}) ${total} += 1;`);
|
|
385
442
|
code.push(`if (${total} !== ${found}) {`);
|
|
386
|
-
// The scan of
|
|
387
|
-
// yields is an internalized string, so a case is a pointer
|
|
388
|
-
// where a dictionary lookup would hash it.
|
|
443
|
+
// The scan of `checkOf` (checks.js) with the known keys as cases: a key
|
|
444
|
+
// for...in yields is an internalized string, so a case is a pointer
|
|
445
|
+
// comparison where a dictionary lookup would hash it.
|
|
389
446
|
let cases = '';
|
|
390
447
|
for (const field in known) cases += `case ${quote(field)}: `;
|
|
391
448
|
code.push(`let ${unexpected} = null;`);
|
|
@@ -492,19 +549,21 @@ const emitUnion = (type, x, key, state) => {
|
|
|
492
549
|
};
|
|
493
550
|
|
|
494
551
|
const EMITTERS = new Map([
|
|
495
|
-
[
|
|
496
|
-
[
|
|
497
|
-
[
|
|
498
|
-
[
|
|
499
|
-
[
|
|
500
|
-
[
|
|
501
|
-
[
|
|
502
|
-
[
|
|
503
|
-
[
|
|
504
|
-
[
|
|
505
|
-
[
|
|
506
|
-
[
|
|
507
|
-
[
|
|
552
|
+
[COMPILE.string, emitScalar],
|
|
553
|
+
[COMPILE.integer, emitInteger],
|
|
554
|
+
[COMPILE.date, emitDate],
|
|
555
|
+
[COMPILE.bytes, emitBytes],
|
|
556
|
+
[COMPILE.flags, emitFlags],
|
|
557
|
+
[COMPILE.null, emitNull],
|
|
558
|
+
[COMPILE.any, emitAny],
|
|
559
|
+
[COMPILE.enum, emitEnum],
|
|
560
|
+
[COMPILE.json, emitJson],
|
|
561
|
+
[COMPILE.object, emitObject],
|
|
562
|
+
[COMPILE.map, emitMap],
|
|
563
|
+
[COMPILE.array, emitList],
|
|
564
|
+
[COMPILE.tuple, emitTuple],
|
|
565
|
+
[COMPILE.union, emitUnion],
|
|
566
|
+
[COMPILE.schema, emitSchema],
|
|
508
567
|
]);
|
|
509
568
|
|
|
510
569
|
// The check of one field over the local `x`. A built-in prototype is
|
package/src/compile/index.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// `node --disallow-code-generation-from-strings`) the closures stay, silently
|
|
8
8
|
// in the default mode. Nothing happens on import.
|
|
9
9
|
const { hasBrand, RUN, HOOK } = require('../util.js');
|
|
10
|
-
const { Schema } = require('../
|
|
10
|
+
const { Schema } = require('../validation.js');
|
|
11
11
|
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
12
12
|
const { Code } = require('./code.js');
|
|
13
13
|
const { emitRoot } = require('./emit.js');
|
|
@@ -71,12 +71,18 @@ const failure = (target, error) => {
|
|
|
71
71
|
return wrapped;
|
|
72
72
|
};
|
|
73
73
|
|
|
74
|
+
// The checks the subpath generated: the closures a schema runs instead may
|
|
75
|
+
// be the ones it was built with or ones compiled later, on first use.
|
|
76
|
+
const GENERATED = new WeakSet();
|
|
77
|
+
|
|
74
78
|
const build = (target) => {
|
|
75
79
|
const code = new Code();
|
|
76
80
|
emitRoot(target, code);
|
|
77
81
|
// oxlint-disable-next-line no-new-func
|
|
78
82
|
const factory = new Function('scope', code.source(target.name));
|
|
79
|
-
|
|
83
|
+
const run = factory(code.values);
|
|
84
|
+
GENERATED.add(run);
|
|
85
|
+
return run;
|
|
80
86
|
};
|
|
81
87
|
|
|
82
88
|
// The generated check, or ERR_JIT_BUILD: the JIT was demanded.
|
|
@@ -158,8 +164,7 @@ const compile = (target, options = {}) => {
|
|
|
158
164
|
const compiled = (target) => {
|
|
159
165
|
const schemas = schemasOf(target);
|
|
160
166
|
for (let index = 0; index < schemas.length; index += 1) {
|
|
161
|
-
|
|
162
|
-
if (!ORIGINAL.has(schema) || schema[RUN] === ORIGINAL.get(schema)) return false;
|
|
167
|
+
if (!GENERATED.has(schemas[index][RUN])) return false;
|
|
163
168
|
}
|
|
164
169
|
return true;
|
|
165
170
|
};
|
package/src/context.js
CHANGED
|
@@ -92,6 +92,11 @@ const configure = (context, options, parsing) => {
|
|
|
92
92
|
if (options.unknown !== undefined) context.unknown = unknownOf(options.unknown, parsing);
|
|
93
93
|
if (options.references !== undefined) context.references = referencesOf(options.references);
|
|
94
94
|
if (options.root !== undefined) context.root = rootOf(options.root);
|
|
95
|
+
// Read by parse and parseAsync themselves, checked here with the rest.
|
|
96
|
+
const { coerce } = options;
|
|
97
|
+
if (parsing && coerce !== undefined && typeof coerce !== 'boolean') {
|
|
98
|
+
throw invalid('coerce', 'a boolean', coerce);
|
|
99
|
+
}
|
|
95
100
|
};
|
|
96
101
|
|
|
97
102
|
// One object shape for every context: the keys are always present, in this
|
|
@@ -137,4 +142,4 @@ const createContext = (options, name = '', unknown = 'reject', parsing = false)
|
|
|
137
142
|
return context;
|
|
138
143
|
};
|
|
139
144
|
|
|
140
|
-
module.exports = { createContext, UNLIMITED, MAX_DEPTH };
|
|
145
|
+
module.exports = { createContext, referencesOf, UNLIMITED, MAX_DEPTH };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The `@alexify/metaschema/definition` subpath: the core's own Schema and
|
|
2
|
+
// Model, built and read without the half that validates. Until the core
|
|
3
|
+
// entry is loaded as well, `check`, `checkAsync`, `parse`, `parseAsync`,
|
|
4
|
+
// `serialize`, `validate`, `checkConsistency`, `warnings`, the `check` of a
|
|
5
|
+
// field and `model.warnings` throw a `TypeError` with the code
|
|
6
|
+
// `ERR_NOT_REGISTERED`, and a schema has no `~standard`; the typings are the
|
|
7
|
+
// core's, since loading the core installs all of them into these classes.
|
|
8
|
+
export {
|
|
9
|
+
KIND,
|
|
10
|
+
KIND_STORED,
|
|
11
|
+
KIND_MEMORY,
|
|
12
|
+
SCOPE,
|
|
13
|
+
STORE,
|
|
14
|
+
ALLOW,
|
|
15
|
+
getKindMetadata,
|
|
16
|
+
Schema,
|
|
17
|
+
Model,
|
|
18
|
+
SchemaDefinitionError,
|
|
19
|
+
} from '../../index.js';
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The `./definition` subpath: the half of the core that builds schemas and
|
|
2
|
+
// models and reads them (their fields and metadata, the warnings of their
|
|
3
|
+
// definitions, `toJSON` and `toSnapshot`), without the half that validates.
|
|
4
|
+
// For a program that needs the definitions and their snapshots alone (the
|
|
5
|
+
// browser client of a codec built from them): `check`, `parse` and their
|
|
6
|
+
// kin say that the core entry is missing. The classes are the core's own,
|
|
7
|
+
// so a program that loads the core entry as well validates with these very
|
|
8
|
+
// schemas, and a bundle of both carries each module once.
|
|
9
|
+
const { constants, getKindMetadata } = require('../kinds.js');
|
|
10
|
+
const { Schema } = require('../schema.js');
|
|
11
|
+
const { Model } = require('../model.js');
|
|
12
|
+
const { SchemaDefinitionError } = require('../errors.js');
|
|
13
|
+
|
|
14
|
+
const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
|
|
15
|
+
|
|
16
|
+
module.exports = {
|
|
17
|
+
KIND,
|
|
18
|
+
KIND_STORED,
|
|
19
|
+
KIND_MEMORY,
|
|
20
|
+
SCOPE,
|
|
21
|
+
STORE,
|
|
22
|
+
ALLOW,
|
|
23
|
+
getKindMetadata,
|
|
24
|
+
Schema,
|
|
25
|
+
Model,
|
|
26
|
+
SchemaDefinitionError,
|
|
27
|
+
};
|