@alexify/metaschema 3.3.0 → 3.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +251 -1
- package/README.md +31 -20
- package/SECURITY.md +24 -1
- package/index.d.ts +280 -48
- package/package.json +13 -3
- package/src/checks.js +789 -0
- package/src/codec.js +37 -13
- package/src/coerce/index.js +34 -1
- package/src/compile/emit.js +87 -28
- package/src/compile/index.js +9 -4
- package/src/definition/index.d.ts +19 -0
- package/src/definition/index.js +27 -0
- package/src/derive/index.js +23 -13
- package/src/errors.js +23 -0
- package/src/generators/fromjsonschema.js +14 -0
- package/src/generators/index.js +1 -1
- package/src/generators/jsonschema.js +44 -7
- package/src/generators/typescript.js +11 -0
- package/src/index.js +3 -2
- package/src/issues.js +9 -7
- package/src/kinds.js +24 -2
- package/src/lint.js +64 -2
- package/src/locales/en.js +6 -0
- package/src/locales/uk.js +6 -0
- package/src/metadata.js +2 -24
- package/src/model/data.js +68 -11
- package/src/model/diff.js +7 -4
- package/src/model/index.js +1 -1
- package/src/model/infer.js +13 -6
- package/src/model/merge.js +7 -3
- package/src/model/restore.js +60 -8
- package/src/model/sample.js +26 -1
- package/src/model.js +25 -53
- package/src/mongodb/bson.js +15 -3
- package/src/mongodb/document.js +10 -2
- package/src/preprocessor.js +14 -5
- package/src/prototypes/abstract.js +32 -64
- 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 +5 -31
- package/src/prototypes/union.js +12 -82
- package/src/rules.js +33 -157
- package/src/schema.js +108 -233
- package/src/snapshot.js +216 -41
- package/src/stream/index.js +1 -1
- package/src/struct.js +6 -91
- package/src/types.js +31 -10
- package/src/util.js +48 -0
- package/src/validation.js +313 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// The validation half of the core: what checks a value against a schema
|
|
2
|
+
// and builds the value of the program from it (the checks of the types, the
|
|
3
|
+
// passes of parse and serialize, the issues and the result), installed into
|
|
4
|
+
// the classes the definition half builds, when the core entry loads it.
|
|
5
|
+
// `./definition` is the other half alone: a schema it builds validates as
|
|
6
|
+
// soon as the program loads the core, since both halves share these
|
|
7
|
+
// classes. Installed once, on the first require of this module.
|
|
8
|
+
const { isFirstUpper } = require('./metautil.js');
|
|
9
|
+
const { RUN, TRACKED, COERCES, CODEC, STANDARD, CYCLES, safeString } = require('./util.js');
|
|
10
|
+
const { Schema } = require('./schema.js');
|
|
11
|
+
const { usesOf } = require('./snapshot.js');
|
|
12
|
+
const { Model } = require('./model.js');
|
|
13
|
+
const { warning, lintSchema } = require('./lint.js');
|
|
14
|
+
const { AbstractType, BUILD } = require('./prototypes/abstract.js');
|
|
15
|
+
const { PROTOTYPES } = require('./types.js');
|
|
16
|
+
const { COMPILE, custom, compileField, checkOf } = require('./checks.js');
|
|
17
|
+
const { isStruct } = require('./struct.js');
|
|
18
|
+
const { createContext } = require('./context.js');
|
|
19
|
+
const { ValidationResult } = require('./result.js');
|
|
20
|
+
const { finalize, runValidate, settle, release, isThenable } = require('./issues.js');
|
|
21
|
+
const { asyncReturn, VALIDATION } = require('./errors.js');
|
|
22
|
+
const {
|
|
23
|
+
PREPARE,
|
|
24
|
+
FINISH,
|
|
25
|
+
SERIALIZE,
|
|
26
|
+
COERCE,
|
|
27
|
+
infoOf,
|
|
28
|
+
apply,
|
|
29
|
+
looped,
|
|
30
|
+
hasAsync,
|
|
31
|
+
wantOf,
|
|
32
|
+
} = require('./codec.js');
|
|
33
|
+
|
|
34
|
+
// The validation of a schema inside an existing context: `check` starts one,
|
|
35
|
+
// and a reference field checks its target entity within the context of the
|
|
36
|
+
// outer check, so the error limit and the cycle detection span the whole
|
|
37
|
+
// value. The schema-level validate runs last, and only on a value whose
|
|
38
|
+
// fields all passed, so it can rely on their shape. Built once per schema,
|
|
39
|
+
// on its first use, as Schema[RUN].
|
|
40
|
+
const compileSchema = (schema) => {
|
|
41
|
+
const { fields, options } = schema;
|
|
42
|
+
const run = isStruct(fields) ? checkOf(fields) : fields.check;
|
|
43
|
+
return (value, context, key) => {
|
|
44
|
+
const before = context.count;
|
|
45
|
+
run(value, context, key);
|
|
46
|
+
const { validate } = options;
|
|
47
|
+
if (validate && context.count === before) {
|
|
48
|
+
const nested = key !== undefined;
|
|
49
|
+
if (nested) context.path.push(key);
|
|
50
|
+
runValidate(schema, validate, value, context);
|
|
51
|
+
if (nested) context.path.pop();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const resultOf = (context) => {
|
|
57
|
+
finalize(context.issues, context.messages);
|
|
58
|
+
return new ValidationResult(context);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// What parse returns: the output only for a valid value, the issues always.
|
|
62
|
+
const parsed = (context, output) => {
|
|
63
|
+
finalize(context.issues, context.messages);
|
|
64
|
+
const valid = context.count === 0;
|
|
65
|
+
return { valid, value: valid ? output : undefined, issues: context.issues };
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// The result of parse read as Standard Schema does.
|
|
69
|
+
const standardize = (result) =>
|
|
70
|
+
result.valid ? { value: result.value } : { issues: result.issues };
|
|
71
|
+
|
|
72
|
+
// The walk of an async check: a throw out of it (a getter of the value that
|
|
73
|
+
// throws, the engine's limit on a pattern) leaves the promises the walk
|
|
74
|
+
// queued observed, so that none of them rejects unhandled.
|
|
75
|
+
const walkAsync = (schema, value, context) => {
|
|
76
|
+
try {
|
|
77
|
+
schema[RUN](value, context);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
release(context.async, 0);
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// One pass of codec.js over a value, from the info of the schema, kept on
|
|
85
|
+
// the schema on first use.
|
|
86
|
+
const pass = (schema, phase, source, context, extra) => {
|
|
87
|
+
let info = schema[CODEC];
|
|
88
|
+
if (info === null) {
|
|
89
|
+
info = infoOf(schema);
|
|
90
|
+
schema[CODEC] = info;
|
|
91
|
+
}
|
|
92
|
+
const want = wantOf(phase, context) | extra;
|
|
93
|
+
return apply(info, schema, source, context, undefined, phase, want);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// The warnings of a schema and of a model, computed on first use: a schema
|
|
97
|
+
// built in a hot path never pays for the lint.
|
|
98
|
+
const LINTED = new WeakMap();
|
|
99
|
+
|
|
100
|
+
const linted = (target, lint) => {
|
|
101
|
+
let warnings = LINTED.get(target);
|
|
102
|
+
if (warnings === undefined) {
|
|
103
|
+
warnings = lint(target);
|
|
104
|
+
LINTED.set(target, warnings);
|
|
105
|
+
}
|
|
106
|
+
return warnings;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// The lint warnings of every entity of a model, the references and types
|
|
110
|
+
// they cannot resolve, and the recursive dependencies met while ordering.
|
|
111
|
+
const lintModel = (model) => {
|
|
112
|
+
const warnings = [];
|
|
113
|
+
const add = (list) => {
|
|
114
|
+
for (let index = 0; index < list.length; index += 1) warnings.push(list[index]);
|
|
115
|
+
};
|
|
116
|
+
for (const pair of model.entities) {
|
|
117
|
+
if (pair[0].startsWith('.')) continue;
|
|
118
|
+
add(pair[1].warnings);
|
|
119
|
+
add(pair[1].checkConsistency());
|
|
120
|
+
}
|
|
121
|
+
for (const pair of model[CYCLES]) {
|
|
122
|
+
warnings.push(
|
|
123
|
+
warning('recursive-reference', `"${pair[0]}" depends on "${pair[1]}" recursively`),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
return warnings;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const members = {
|
|
130
|
+
// What is not wrong enough to throw: `Warning [code]: text` strings.
|
|
131
|
+
get warnings() {
|
|
132
|
+
return linted(this, lintSchema);
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
// The warnings that need the namespaces: references and types that do
|
|
136
|
+
// not resolve, each through the schema whose fields use it (a schema
|
|
137
|
+
// reused as a field resolves its own), once per name.
|
|
138
|
+
checkConsistency() {
|
|
139
|
+
const warn = [];
|
|
140
|
+
const { name } = this;
|
|
141
|
+
const missing = new Set();
|
|
142
|
+
const uses = usesOf(this);
|
|
143
|
+
for (let index = 0; index < uses.length; index += 1) {
|
|
144
|
+
const ref = uses[index][0];
|
|
145
|
+
const root = uses[index][1];
|
|
146
|
+
if (missing.has(ref)) continue;
|
|
147
|
+
const upper = isFirstUpper(ref);
|
|
148
|
+
if (upper ? root.findReference(ref) !== null : root.types[ref] !== undefined) continue;
|
|
149
|
+
missing.add(ref);
|
|
150
|
+
if (upper) {
|
|
151
|
+
warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
|
|
152
|
+
} else warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
|
|
153
|
+
}
|
|
154
|
+
return warn;
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
// Validates a value: every problem is collected as an issue, and the
|
|
158
|
+
// result never throws because of the value. `options`: root (the label of
|
|
159
|
+
// the error lines, the schema name by default), maxErrors, unknown
|
|
160
|
+
// ('reject' or 'ignore' keys the schema does not have), references,
|
|
161
|
+
// messages (a locale). A validator that returns a promise is an error
|
|
162
|
+
// here. `createContext` is called directly in every method here, never
|
|
163
|
+
// through a helper: V8 inlines the allocation into `check` that way (the
|
|
164
|
+
// context is the one allocation of a valid check), and a method in
|
|
165
|
+
// between cost 7%.
|
|
166
|
+
check(source, options) {
|
|
167
|
+
const context = createContext(options, this.name, this.unknown);
|
|
168
|
+
if (this[TRACKED]) context.source = source;
|
|
169
|
+
this[RUN](source, context);
|
|
170
|
+
return resultOf(context);
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
// The same check, with the validators that return a promise in flight
|
|
174
|
+
// together and settled after the walk, in field order.
|
|
175
|
+
async checkAsync(source, options) {
|
|
176
|
+
const context = createContext(options, this.name, this.unknown);
|
|
177
|
+
context.async = [];
|
|
178
|
+
if (this[TRACKED]) context.source = source;
|
|
179
|
+
walkAsync(this, source, context);
|
|
180
|
+
if (context.async.length > 0) await settle(context);
|
|
181
|
+
return resultOf(context);
|
|
182
|
+
},
|
|
183
|
+
|
|
184
|
+
// Validates a value and builds the value of the program from it: the
|
|
185
|
+
// input coerced (when the call, else the schema, asks for it) and the
|
|
186
|
+
// defaults filled in, the check, and on a valid value `unknown: 'strip'`,
|
|
187
|
+
// the decoders of its fields (the parts of a value before the value) and
|
|
188
|
+
// the schema's own `parse`. `{ valid, value, issues }`: the value is
|
|
189
|
+
// undefined when invalid, and the value given when there was nothing to
|
|
190
|
+
// apply; the value given is never written to. The objects met before the
|
|
191
|
+
// check are not the check's, and a value that loops through its
|
|
192
|
+
// references is checked as it was given. The pass before the check is
|
|
193
|
+
// written out here and in parseAsync, not in a function of its own: with
|
|
194
|
+
// coercion such a method no longer fit the bytecode V8 inlines into
|
|
195
|
+
// parse, and the call cost the JIT backend 13%.
|
|
196
|
+
parse(source, options) {
|
|
197
|
+
const context = createContext(options, this.name, this.unknown, true);
|
|
198
|
+
const own = options === undefined ? undefined : options.coerce;
|
|
199
|
+
const coerce = own === undefined ? this[COERCES] : own;
|
|
200
|
+
const prepared = pass(this, PREPARE, source, context, coerce === true ? COERCE : 0);
|
|
201
|
+
const value = looped(context) ? source : prepared;
|
|
202
|
+
context.seen = null;
|
|
203
|
+
if (this[TRACKED]) context.source = value;
|
|
204
|
+
this[RUN](value, context);
|
|
205
|
+
const output = context.count === 0 ? pass(this, FINISH, value, context, 0) : undefined;
|
|
206
|
+
return parsed(context, output);
|
|
207
|
+
},
|
|
208
|
+
|
|
209
|
+
async parseAsync(source, options) {
|
|
210
|
+
const context = createContext(options, this.name, this.unknown, true);
|
|
211
|
+
context.async = [];
|
|
212
|
+
const own = options === undefined ? undefined : options.coerce;
|
|
213
|
+
const coerce = own === undefined ? this[COERCES] : own;
|
|
214
|
+
const prepared = pass(this, PREPARE, source, context, coerce === true ? COERCE : 0);
|
|
215
|
+
const value = looped(context) ? source : prepared;
|
|
216
|
+
context.seen = null;
|
|
217
|
+
if (this[TRACKED]) context.source = value;
|
|
218
|
+
walkAsync(this, value, context);
|
|
219
|
+
if (context.async.length > 0) await settle(context);
|
|
220
|
+
let output;
|
|
221
|
+
if (context.count === 0) {
|
|
222
|
+
// Only a promise of the pass is awaited: a thenable in the value is data.
|
|
223
|
+
output = pass(this, FINISH, value, context, 0);
|
|
224
|
+
if (output instanceof Promise) output = (await output).value;
|
|
225
|
+
}
|
|
226
|
+
return parsed(context, output);
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
// The other direction: the schema's own `serialize`, then the serializers
|
|
230
|
+
// of the fields, from the value down to its parts. `{ value }`, or with
|
|
231
|
+
// `options.check` the verdict of `check` over the result as well.
|
|
232
|
+
serialize(source, options) {
|
|
233
|
+
const context = createContext(options, this.name, this.unknown);
|
|
234
|
+
const value = pass(this, SERIALIZE, source, context, 0);
|
|
235
|
+
if (options === undefined || options.check !== true) return { value };
|
|
236
|
+
context.seen = null;
|
|
237
|
+
if (this[TRACKED]) context.source = value;
|
|
238
|
+
this[RUN](value, context);
|
|
239
|
+
finalize(context.issues, context.messages);
|
|
240
|
+
return { valid: context.count === 0, value, issues: context.issues };
|
|
241
|
+
},
|
|
242
|
+
|
|
243
|
+
// Runs only the schema-level validate function, as a result of its own; a
|
|
244
|
+
// function that returns a promise is an error here, as in check.
|
|
245
|
+
validate(value, path = '') {
|
|
246
|
+
if (!this.options.validate) return null;
|
|
247
|
+
const result = new ValidationResult();
|
|
248
|
+
try {
|
|
249
|
+
const output = this.options.validate.call(this, value, path);
|
|
250
|
+
if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
|
|
251
|
+
return result.add(output);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
|
|
254
|
+
return result.add({
|
|
255
|
+
code: 'exception',
|
|
256
|
+
message: `validation failed ${safeString(error)}`,
|
|
257
|
+
params: { error },
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
|
|
262
|
+
// Standard Schema v1 (https://standardschema.dev): the interface tRPC,
|
|
263
|
+
// TanStack Form, Hono and the other consumers of the specification
|
|
264
|
+
// validate through. `validate` is `parse` with the policies of the schema:
|
|
265
|
+
// the value that comes back has the defaults and the decoders applied (the
|
|
266
|
+
// value itself when there was nothing to apply), and the issues of an
|
|
267
|
+
// invalid one are the result's own (a message and a path of keys each). A
|
|
268
|
+
// schema with an async validator or decoder validates through parseAsync,
|
|
269
|
+
// as the specification allows. The vendor-specific `libraryOptions` of a
|
|
270
|
+
// call are the options of `parse`. An accessor of the prototype stays out
|
|
271
|
+
// of toJSON, inspect and Object.keys, and `validate` closes over the
|
|
272
|
+
// schema because a consumer calls it unbound. The `./generators` subpath
|
|
273
|
+
// adds the `jsonSchema` converter of Standard JSON Schema to the props.
|
|
274
|
+
get '~standard'() {
|
|
275
|
+
if (this[STANDARD] === null) {
|
|
276
|
+
const async = hasAsync(this);
|
|
277
|
+
const validate = (value, options) => {
|
|
278
|
+
const libraryOptions = options == null ? undefined : options.libraryOptions;
|
|
279
|
+
if (async) return this.parseAsync(value, libraryOptions).then(standardize);
|
|
280
|
+
return standardize(this.parse(value, libraryOptions));
|
|
281
|
+
};
|
|
282
|
+
this[STANDARD] = { version: 1, vendor: 'alexify.metaschema', validate };
|
|
283
|
+
}
|
|
284
|
+
return this[STANDARD];
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
// Installed like class members: not enumerable. A copy per subpath rather
|
|
289
|
+
// than a helper of the core: the halves are measured apart.
|
|
290
|
+
const install = (target, entries) => {
|
|
291
|
+
const descriptors = Object.getOwnPropertyDescriptors(entries);
|
|
292
|
+
for (const name in descriptors) {
|
|
293
|
+
descriptors[name].enumerable = false;
|
|
294
|
+
Object.defineProperty(target, name, descriptors[name]);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
for (const name of Object.keys(COMPILE)) PROTOTYPES[name].compile = COMPILE[name];
|
|
299
|
+
install(AbstractType.prototype, { compile: custom.compile });
|
|
300
|
+
BUILD.field = compileField;
|
|
301
|
+
BUILD.schema = compileSchema;
|
|
302
|
+
install(Schema.prototype, members);
|
|
303
|
+
install(Model.prototype, {
|
|
304
|
+
// The warnings of every entity, the references and types they cannot
|
|
305
|
+
// resolve, and the recursive dependencies, as `Warning [code]: text`.
|
|
306
|
+
get warnings() {
|
|
307
|
+
return linted(this, lintModel);
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
// A schema of another copy of the package says so (`noValidation`).
|
|
311
|
+
globalThis[VALIDATION] = true;
|
|
312
|
+
|
|
313
|
+
module.exports = { Schema, ValidationResult };
|