@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.
Files changed (53) hide show
  1. package/CHANGELOG.md +251 -1
  2. package/README.md +31 -20
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +280 -48
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +23 -13
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +24 -2
  22. package/src/lint.js +64 -2
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +68 -11
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +13 -6
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +60 -8
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +14 -5
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +5 -31
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +108 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +31 -10
  52. package/src/util.js +48 -0
  53. package/src/validation.js +313 -0
package/src/rules.js CHANGED
@@ -1,12 +1,11 @@
1
- // The rule checks a field may carry besides its type. A type lists the rules
2
- // it accepts (`rules: ['length']` on a prototype); a rule in a definition of a
1
+ // The rules a field may carry besides its type. A type lists the rules it
2
+ // accepts (`rules: ['length']` on a prototype); a rule in a definition of a
3
3
  // type that does not accept it is a definition error, not a silent no-op. A
4
- // rule's value is checked and normalized when the field is built (`format`),
5
- // and its check is compiled into a closure over the field's bounds, run after
6
- // the type check.
7
- const { issues } = require('./issues.js');
4
+ // rule's value is checked and normalized when the field is built (`format`);
5
+ // its check is the validation half's (`compileRules` of `checks.js`),
6
+ // compiled into a closure over the field's bounds and run after the type
7
+ // check.
8
8
  const { SchemaDefinitionError } = require('./errors.js');
9
- const { isMap, isSet } = require('./util.js');
10
9
 
11
10
  const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
12
11
 
@@ -60,12 +59,28 @@ const formatPattern = (value) => {
60
59
  // the hint, never a check that passes everything.
61
60
  const FORMATS = Object.create(null);
62
61
 
63
- const formatName = (value) => {
62
+ // The entry a field's format named when the field was built: a format the
63
+ // program registers later under that name does not change the field, whose
64
+ // check is compiled on its first use.
65
+ const NAMED = new WeakMap();
66
+
67
+ const formatName = (value, type) => {
64
68
  if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
65
69
  if (FORMATS[value] === undefined) {
66
70
  const hint = 'register() of @alexify/metaschema/formats';
67
71
  throw invalidRule(`Rule "format" names a format that is not registered: "${value}" (${hint})`);
68
72
  }
73
+ NAMED.set(type, FORMATS[value]);
74
+ return value;
75
+ };
76
+
77
+ const formatOf = (type) => NAMED.get(type);
78
+
79
+ // The decimals a number may have: what a double holds exactly in a fraction.
80
+ const formatDecimals = (value) => {
81
+ if (!Number.isInteger(value) || value < 0 || value > 15) {
82
+ throw invalidRule('Rule "decimals" needs an integer from 0 to 15');
83
+ }
69
84
  return value;
70
85
  };
71
86
 
@@ -75,160 +90,21 @@ const FORMAT = Object.assign(Object.create(null), {
75
90
  max: formatLimit('max'),
76
91
  pattern: formatPattern,
77
92
  format: formatName,
93
+ decimals: formatDecimals,
78
94
  });
79
95
 
80
- const notApplicable = (rule, type, rules) => {
81
- const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
82
- return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
83
- };
84
-
85
- // Code points of a string: a surrogate pair counts once, a lone surrogate
86
- // once too.
87
- const codePoints = (text) => {
88
- const { length } = text;
89
- let count = 0;
90
- for (let index = 0; index < length; index += 1) {
91
- const unit = text.charCodeAt(index);
92
- if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < length) {
93
- const next = text.charCodeAt(index + 1);
94
- if (next >= 0xdc00 && next <= 0xdfff) index += 1;
95
- }
96
- count += 1;
97
- }
98
- return count;
99
- };
100
-
101
- // The own keys of an object, counted without a list of them.
102
- const keyCount = (value) => {
103
- let count = 0;
104
- for (const name in value) if (Object.hasOwn(value, name)) count += 1;
105
- return count;
106
- };
107
-
108
- // The length of a value, by what the value is rather than by what it carries
109
- // (an object with a `size` key is an object): the units of a string, the
110
- // length of an array, the size of a Set or a Map, the own keys of an object.
111
- const lengthOf = (value) => {
112
- if (typeof value === 'string' || Array.isArray(value)) return value.length;
113
- return isMap(value) || isSet(value) ? value.size : keyCount(value);
114
- };
115
-
116
- // A string field measures its units, or its code points when it asks for
117
- // them; anything else is measured by what it is. One closure per case, each
118
- // calling its measure directly: a measure held in a variable is a call site
119
- // shared by every length rule of the process, which V8 then cannot inline.
120
- const compileLength = (type) => {
121
- const { min, max } = type.length;
122
- if (type.scalar === 'string') {
123
- if (type.unicode === true) {
124
- return (value, context, key) => {
125
- const actual = codePoints(value);
126
- const short = min !== undefined && actual < min;
127
- const long = max !== undefined && actual > max;
128
- if (short || long) issues.length(context, min, max, actual, key);
129
- };
130
- }
131
- return (value, context, key) => {
132
- const actual = value.length;
133
- const short = min !== undefined && actual < min;
134
- const long = max !== undefined && actual > max;
135
- if (short || long) issues.length(context, min, max, actual, key);
136
- };
137
- }
138
- return (value, context, key) => {
139
- const actual = lengthOf(value);
140
- const short = min !== undefined && actual < min;
141
- const long = max !== undefined && actual > max;
142
- if (short || long) issues.length(context, min, max, actual, key);
143
- };
144
- };
145
-
146
- // One closure for both bounds when a field has both.
147
- const compileRange = (type) => {
96
+ // The bounds of a field leave room for a value: the definition is checked
97
+ // when the field is built, its check compiled later.
98
+ const checkBounds = (type) => {
148
99
  const { min, max } = type;
149
- if (min === undefined) {
150
- return (value, context, key) => {
151
- if (value > max) issues.range(context, min, max, value, key);
152
- };
153
- }
154
- if (max === undefined) {
155
- return (value, context, key) => {
156
- if (value < min) issues.range(context, min, max, value, key);
157
- };
158
- }
159
- if (min > max) throw invalidRule('Rule "max" is below "min"');
160
- return (value, context, key) => {
161
- if (value < min || value > max) issues.range(context, min, max, value, key);
162
- };
163
- };
164
-
165
- // The units a pattern may be run over: `length.max` (twice it when the
166
- // length counts code points, each at most two units), so that a string past
167
- // the bound, reported for its length already, never reaches a pattern that
168
- // backtracks over it; no limit without the bound.
169
- const patternLimit = (type) => {
170
- const max = type.length?.max;
171
- if (max === undefined) return Infinity;
172
- return type.unicode === true ? 2 * max : max;
173
- };
174
-
175
- const compilePattern = (type) => {
176
- const { pattern } = type;
177
- const { source } = pattern;
178
- const limit = patternLimit(type);
179
- return (value, context, key) => {
180
- if (value.length <= limit && !pattern.test(value)) issues.pattern(context, source, key);
181
- };
182
- };
183
-
184
- // A format is the test the subpath registered under its name, run after the
185
- // pattern and under the same bound.
186
- const compileFormat = (type) => {
187
- const { format } = type;
188
- const { test } = FORMATS[format];
189
- const limit = patternLimit(type);
190
- return (value, context, key) => {
191
- if (value.length <= limit && !test(value)) issues.format(context, format, key);
192
- };
193
- };
194
-
195
- // The rules a field carries, by name, in the order its type lists them, min
196
- // and max as the one `range`: the order the closures run them in and the JIT
197
- // emits them in.
198
- const ruleNames = (type) => {
199
- const names = [];
200
- let range = false;
201
- for (const name of type.constructor.rules) {
202
- if (type[name] === undefined) continue;
203
- if (name === 'min' || name === 'max') range = true;
204
- else names.push(name);
100
+ if (min !== undefined && max !== undefined && min > max) {
101
+ throw invalidRule('Rule "max" is below "min"');
205
102
  }
206
- if (range) names.push('range');
207
- return names;
208
103
  };
209
104
 
210
- const COMPILERS = Object.assign(Object.create(null), {
211
- length: compileLength,
212
- pattern: compilePattern,
213
- format: compileFormat,
214
- range: compileRange,
215
- });
216
-
217
- // The checks of the rules a field carries.
218
- const compileRules = (type) => {
219
- const names = ruleNames(type);
220
- const checks = [];
221
- for (let index = 0; index < names.length; index += 1) checks.push(COMPILERS[names[index]](type));
222
- return checks;
105
+ const notApplicable = (rule, type, rules) => {
106
+ const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
107
+ return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
223
108
  };
224
109
 
225
- module.exports = {
226
- FORMAT,
227
- FORMATS,
228
- notApplicable,
229
- ruleNames,
230
- compileRules,
231
- patternLimit,
232
- codePoints,
233
- lengthOf,
234
- };
110
+ module.exports = { FORMAT, FORMATS, formatOf, checkBounds, notApplicable };
package/src/schema.js CHANGED
@@ -1,101 +1,47 @@
1
- const { isFirstUpper } = require('./metautil.js');
2
-
3
- const { BRAND, INSPECT, RUN, HOOK, hasBrand } = require('./util.js');
4
- const { createContext } = require('./context.js');
1
+ const {
2
+ BRAND,
3
+ INSPECT,
4
+ RUN,
5
+ HOOK,
6
+ TRACKED,
7
+ COERCES,
8
+ CODEC,
9
+ STANDARD,
10
+ KINDS,
11
+ hasBrand,
12
+ } = require('./util.js');
5
13
  const { TYPES } = require('./types.js');
6
14
  const { Preprocessor } = require('./preprocessor.js');
7
15
  const { SchemaMetadata } = require('./metadata.js');
8
- const { ValidationResult } = require('./result.js');
9
- const { finalize, runValidate, settle, release } = require('./issues.js');
10
- const { SchemaDefinitionError } = require('./errors.js');
11
- const { createStruct, isStruct, checkOf } = require('./struct.js');
12
- const { warning, lintSchema } = require('./lint.js');
13
- const {
14
- PREPARE,
15
- FINISH,
16
- SERIALIZE,
17
- COERCE,
18
- infoOf,
19
- apply,
20
- looped,
21
- hasAsync,
22
- wantOf,
23
- } = require('./codec.js');
24
-
25
- // The validation of a schema inside an existing context: `check` starts one,
26
- // and a reference field checks its target entity within the context of the
27
- // outer check, so the error limit and the cycle detection span the whole
28
- // value. The schema-level validate runs last, and only on a value whose
29
- // fields all passed, so it can rely on their shape. Built once per schema,
30
- // as Schema[RUN].
31
- const compileSchema = (schema) => {
32
- const { fields, options } = schema;
33
- const run = isStruct(fields) ? checkOf(fields) : fields.check;
34
- return (value, context, key) => {
35
- const before = context.count;
36
- run(value, context, key);
37
- const { validate } = options;
38
- if (validate && context.count === before) {
39
- const nested = key !== undefined;
40
- if (nested) context.path.push(key);
41
- runValidate(schema, validate, value, context);
42
- if (nested) context.path.pop();
43
- }
16
+ const { SchemaDefinitionError, noValidation } = require('./errors.js');
17
+ const { createStruct } = require('./struct.js');
18
+ const { BUILD } = require('./prototypes/abstract.js');
19
+ const { schemaSnapshotOf } = require('./snapshot.js');
20
+
21
+ // The check of a schema until it is first used: it builds the closures
22
+ // (`BUILD.schema`, the validation half's), takes their place and runs them.
23
+ // A schema built to be read (rendered, written as a snapshot) never builds
24
+ // them; one the JIT replaced before its first use (`register()` of
25
+ // `./compile`) is not touched.
26
+ const lazyRun = (schema) => {
27
+ const run = (value, context, key) => {
28
+ const check = BUILD.schema(schema);
29
+ if (schema[RUN] === run) schema[RUN] = check;
30
+ return check(value, context, key);
44
31
  };
32
+ return run;
45
33
  };
46
34
 
47
- const resultOf = (context) => {
48
- finalize(context.issues, context.messages);
49
- return new ValidationResult(context);
50
- };
51
-
52
- // What parse returns: the output only for a valid value, the issues always.
53
- const parsed = (context, output) => {
54
- finalize(context.issues, context.messages);
55
- const valid = context.count === 0;
56
- return { valid, value: valid ? output : undefined, issues: context.issues };
57
- };
58
-
59
- // The result of parse read as Standard Schema does.
60
- const standardize = (result) =>
61
- result.valid ? { value: result.value } : { issues: result.issues };
62
-
63
- // The walk of an async check: a throw out of it (a getter of the value that
64
- // throws, the engine's limit on a pattern) leaves the promises the walk
65
- // queued observed, so that none of them rejects unhandled.
66
- const walkAsync = (schema, value, context) => {
67
- try {
68
- schema[RUN](value, context);
69
- } catch (error) {
70
- release(context.async, 0);
71
- throw error;
72
- }
73
- };
74
-
35
+ // The half of the core that builds a schema and reads it: its fields and
36
+ // metadata, its JSON and its snapshot. The validation half (`validation.js`,
37
+ // which the core entry loads) installs `check`, `parse`, `serialize` and
38
+ // their kin, `~standard` and the warnings of the lint on this class; until
39
+ // then they say so (`./definition` alone).
75
40
  class Schema extends SchemaMetadata {
76
41
  // The merged type table of the attached namespaces, rebuilt only when they
77
42
  // change.
78
43
  #types = null;
79
44
 
80
- // Whether the root value joins the cycle detection (`context.source`):
81
- // only a struct with references can reach it again.
82
- #tracked = false;
83
-
84
- // The lint of the definition, run on first use: a schema built in a hot
85
- // path never pays for it.
86
- #warnings = null;
87
-
88
- // The Standard Schema props, built on first use.
89
- #standard = null;
90
-
91
- // What the passes of parse and serialize know about the schema, on first use.
92
- #codec = null;
93
-
94
- // Whether parse coerces the input unless the call says otherwise: the
95
- // `coerce` of the kind metadata, read once (an own property would shadow
96
- // the method the `./coerce` subpath installs).
97
- #coerce = false;
98
-
99
45
  static from(source, namespaces) {
100
46
  return new Schema('', source, namespaces);
101
47
  }
@@ -134,44 +80,22 @@ class Schema extends SchemaMetadata {
134
80
  const combined = { ...fields, ...extras };
135
81
  this.fields = createStruct(combined, preprocessor);
136
82
  }
137
- this.#tracked = isSchemaType && this.relations.size > 0;
138
- this.#coerce = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
139
- this[RUN] = compileSchema(this);
83
+ // What the validation half reads (util.js): whether the root value joins
84
+ // the cycle detection (only a struct with references can reach it
85
+ // again), whether parse coerces unless the call says otherwise (the
86
+ // `coerce` of the kind metadata, read once: an own property would shadow
87
+ // the method the `./coerce` subpath installs), its caches, and the kinds
88
+ // of the program's own the definition named, for the lint.
89
+ this[TRACKED] = isSchemaType && this.relations.size > 0;
90
+ this[COERCES] = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
91
+ this[CODEC] = null;
92
+ this[STANDARD] = null;
93
+ this[KINDS] = preprocessor.kinds;
94
+ this[RUN] = lazyRun(this);
140
95
  const hook = Schema[HOOK];
141
96
  if (hook !== undefined) hook(this);
142
97
  }
143
98
 
144
- // What is not wrong enough to throw: `Warning [code]: text` strings.
145
- get warnings() {
146
- if (this.#warnings === null) this.#warnings = lintSchema(this);
147
- return this.#warnings;
148
- }
149
-
150
- // Standard Schema v1 (https://standardschema.dev): the interface tRPC,
151
- // TanStack Form, Hono and the other consumers of the specification validate
152
- // through. `validate` is `parse` with the policies of the schema: the value
153
- // that comes back has the defaults and the decoders applied (the value
154
- // itself when there was nothing to apply), and the issues of an invalid one
155
- // are the result's own (a message and a path of keys each). A schema with
156
- // an async validator or decoder validates through parseAsync, as the
157
- // specification allows. The vendor-specific `libraryOptions` of a call are
158
- // the options of `parse`. An accessor of the prototype stays out of toJSON,
159
- // inspect and Object.keys, and `validate` closes over the schema because a
160
- // consumer calls it unbound. The `./generators` subpath adds the
161
- // `jsonSchema` converter of Standard JSON Schema to the props.
162
- get '~standard'() {
163
- if (this.#standard === null) {
164
- const async = hasAsync(this);
165
- const validate = (value, options) => {
166
- const libraryOptions = options == null ? undefined : options.libraryOptions;
167
- if (async) return this.parseAsync(value, libraryOptions).then(standardize);
168
- return standardize(this.parse(value, libraryOptions));
169
- };
170
- this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
171
- }
172
- return this.#standard;
173
- }
174
-
175
99
  get types() {
176
100
  if (this.namespaces.size === 0) return TYPES;
177
101
  if (this.#types === null) {
@@ -182,121 +106,16 @@ class Schema extends SchemaMetadata {
182
106
  return this.#types;
183
107
  }
184
108
 
185
- // The warnings that need the namespaces: references and types that do
186
- // not resolve.
187
- checkConsistency() {
188
- const warn = [];
189
- const { name, references } = this;
190
- for (const ref of references) {
191
- if (isFirstUpper(ref)) {
192
- const entity = this.findReference(ref);
193
- if (!entity) {
194
- warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
195
- }
196
- } else if (!this.types[ref]) {
197
- warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
198
- }
199
- }
200
- return warn;
201
- }
202
-
109
+ // An entity of the attached models, else the schema itself: a schema that
110
+ // names itself (`parent: '?Category'`) needs no model. The models come
111
+ // first, so a schema with the name of one of their entities (a schema
112
+ // derived from it keeps the name) still reaches that entity.
203
113
  findReference(name) {
204
114
  for (const ns of this.namespaces) {
205
115
  const entity = ns.entities.get(name);
206
116
  if (entity) return entity;
207
117
  }
208
- return null;
209
- }
210
-
211
- // Validates a value: every problem is collected as an issue, and the result
212
- // never throws because of the value. `options`: root (the label of the
213
- // error lines, the schema name by default), maxErrors, unknown ('reject'
214
- // or 'ignore' keys the schema does not have), references, messages (a
215
- // locale). A validator that returns a promise is an error here.
216
- // `createContext` is called directly in every method here, never through a
217
- // helper: V8 inlines the allocation into `check` that way (the context is
218
- // the one allocation of a valid check), and a method in between cost 7%.
219
- check(source, options) {
220
- const context = createContext(options, this.name, this.unknown);
221
- if (this.#tracked) context.source = source;
222
- this[RUN](source, context);
223
- return resultOf(context);
224
- }
225
-
226
- // The same check, with the validators that return a promise in flight
227
- // together and settled after the walk, in field order.
228
- async checkAsync(source, options) {
229
- const context = createContext(options, this.name, this.unknown);
230
- context.async = [];
231
- if (this.#tracked) context.source = source;
232
- walkAsync(this, source, context);
233
- if (context.async.length > 0) await settle(context);
234
- return resultOf(context);
235
- }
236
-
237
- #pass(phase, source, context, extra) {
238
- if (this.#codec === null) this.#codec = infoOf(this);
239
- const want = wantOf(phase, context) | extra;
240
- return apply(this.#codec, this, source, context, undefined, phase, want);
241
- }
242
-
243
- // Validates a value and builds the value of the program from it: the input
244
- // coerced (when the call, else the schema, asks for it) and the defaults
245
- // filled in, the check, and on a valid value `unknown: 'strip'`, the
246
- // decoders of its fields (the parts of a value before the value) and the
247
- // schema's own `parse`. `{ valid, value, issues }`: the value is undefined
248
- // when invalid, and the value given when there was nothing to apply; the
249
- // value given is never written to. The objects met before the check are
250
- // not the check's, and a value that loops through its references is
251
- // checked as it was given. The pass before the check is written out here
252
- // and in parseAsync, not in a method of its own: with coercion such a
253
- // method no longer fit the bytecode V8 inlines into parse, and the call
254
- // cost the JIT backend 13%.
255
- parse(source, options) {
256
- const context = createContext(options, this.name, this.unknown, true);
257
- const own = options === undefined ? undefined : options.coerce;
258
- const coerce = own === undefined ? this.#coerce : own;
259
- const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
260
- const value = looped(context) ? source : prepared;
261
- context.seen = null;
262
- if (this.#tracked) context.source = value;
263
- this[RUN](value, context);
264
- const output = context.count === 0 ? this.#pass(FINISH, value, context, 0) : undefined;
265
- return parsed(context, output);
266
- }
267
-
268
- async parseAsync(source, options) {
269
- const context = createContext(options, this.name, this.unknown, true);
270
- context.async = [];
271
- const own = options === undefined ? undefined : options.coerce;
272
- const coerce = own === undefined ? this.#coerce : own;
273
- const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
274
- const value = looped(context) ? source : prepared;
275
- context.seen = null;
276
- if (this.#tracked) context.source = value;
277
- walkAsync(this, value, context);
278
- if (context.async.length > 0) await settle(context);
279
- let output;
280
- if (context.count === 0) {
281
- // Only a promise of the pass is awaited: a thenable in the value is data.
282
- output = this.#pass(FINISH, value, context, 0);
283
- if (output instanceof Promise) output = (await output).value;
284
- }
285
- return parsed(context, output);
286
- }
287
-
288
- // The other direction: the schema's own `serialize`, then the serializers
289
- // of the fields, from the value down to its parts. `{ value }`, or with
290
- // `options.check` the verdict of `check` over the result as well.
291
- serialize(source, options) {
292
- const context = createContext(options, this.name, this.unknown);
293
- const value = this.#pass(SERIALIZE, source, context, 0);
294
- if (options === undefined || options.check !== true) return { value };
295
- context.seen = null;
296
- if (this.#tracked) context.source = value;
297
- this[RUN](value, context);
298
- finalize(context.issues, context.messages);
299
- return { valid: context.count === 0, value, issues: context.issues };
118
+ return name === this.name && name !== '' ? this : null;
300
119
  }
301
120
 
302
121
  // The types and the Standard Schema props depend on the namespaces (the
@@ -305,13 +124,13 @@ class Schema extends SchemaMetadata {
305
124
  attach(...namespaces) {
306
125
  for (const ns of namespaces) this.namespaces.add(ns);
307
126
  this.#types = null;
308
- this.#standard = null;
127
+ this[STANDARD] = null;
309
128
  }
310
129
 
311
130
  detach(...namespaces) {
312
131
  for (const ns of namespaces) this.namespaces.delete(ns);
313
132
  this.#types = null;
314
- this.#standard = null;
133
+ this[STANDARD] = null;
315
134
  }
316
135
 
317
136
  toString() {
@@ -323,12 +142,68 @@ class Schema extends SchemaMetadata {
323
142
  return hasBrand(fields, 'Struct') ? { ...fields } : fields.toJSON();
324
143
  }
325
144
 
145
+ // The schema as plain JSON: the snapshot of a model (format 1) holding the
146
+ // schema and every entity it reaches through its references, in
147
+ // dependency order, with the name of the schema as `root`.
148
+ toSnapshot() {
149
+ return schemaSnapshotOf(this);
150
+ }
151
+
326
152
  [INSPECT](depth, options, inspect) {
327
153
  const label = this.name ? `Schema(${this.name})` : 'Schema';
328
154
  return `${label} ${inspect(this.toJSON(), options)}`;
329
155
  }
330
156
  }
331
157
 
158
+ // Until the validation half is installed, a schema builds and reads, and a
159
+ // call that validates says what is missing. A stub looks the method up when
160
+ // it is called, so one a program took before the core was loaded (`const {
161
+ // check } = schema`, `check.bind(schema)`) calls the method installed since.
162
+ // Named as the methods are, for the stack.
163
+ const STUBS = {
164
+ checkConsistency(...args) {
165
+ return late(this, 'checkConsistency', args);
166
+ },
167
+ check(...args) {
168
+ return late(this, 'check', args);
169
+ },
170
+ async checkAsync(...args) {
171
+ return late(this, 'checkAsync', args);
172
+ },
173
+ parse(...args) {
174
+ return late(this, 'parse', args);
175
+ },
176
+ async parseAsync(...args) {
177
+ return late(this, 'parseAsync', args);
178
+ },
179
+ serialize(...args) {
180
+ return late(this, 'serialize', args);
181
+ },
182
+ validate(...args) {
183
+ return late(this, 'validate', args);
184
+ },
185
+ };
186
+
187
+ const late = (schema, name, args) => {
188
+ const method = Schema.prototype[name];
189
+ if (method === STUBS[name]) throw noValidation(name);
190
+ return method.apply(schema, args);
191
+ };
192
+
193
+ for (const name of Object.keys(STUBS)) {
194
+ Object.defineProperty(Schema.prototype, name, {
195
+ value: STUBS[name],
196
+ writable: true,
197
+ configurable: true,
198
+ });
199
+ }
200
+ Object.defineProperty(Schema.prototype, 'warnings', {
201
+ get() {
202
+ throw noValidation('warnings');
203
+ },
204
+ configurable: true,
205
+ });
206
+
332
207
  Schema.prototype[BRAND] = 'Schema';
333
208
 
334
209
  module.exports = { Schema };