@alexify/metaschema 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +551 -1
  2. package/README.md +235 -34
  3. package/SECURITY.md +32 -11
  4. package/index.d.ts +798 -23
  5. package/package.json +30 -6
  6. package/src/codec.js +490 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +512 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +141 -0
  12. package/src/errors.js +10 -1
  13. package/src/generators/index.d.ts +29 -0
  14. package/src/generators/index.js +90 -0
  15. package/src/generators/jsonschema.js +535 -0
  16. package/src/generators/typescript.js +237 -0
  17. package/src/index.js +1 -3
  18. package/src/issues.js +291 -0
  19. package/src/kinds.js +9 -12
  20. package/src/lint.js +98 -0
  21. package/src/locales/en.d.ts +5 -0
  22. package/src/locales/en.js +66 -0
  23. package/src/locales/uk.d.ts +5 -0
  24. package/src/locales/uk.js +62 -0
  25. package/src/metadata.js +65 -119
  26. package/src/metautil.js +8 -1
  27. package/src/model.js +31 -20
  28. package/src/preprocessor.js +45 -27
  29. package/src/prototypes/abstract.js +101 -51
  30. package/src/prototypes/collections.js +106 -41
  31. package/src/prototypes/json.js +9 -5
  32. package/src/prototypes/reference.js +91 -20
  33. package/src/prototypes/scalars.js +124 -16
  34. package/src/prototypes/schema.js +31 -6
  35. package/src/prototypes/tuple.js +57 -29
  36. package/src/prototypes/union.js +139 -0
  37. package/src/result.js +115 -0
  38. package/src/rules.js +185 -0
  39. package/src/runtime/browser.js +2 -2
  40. package/src/runtime/node.js +4 -2
  41. package/src/schema.js +181 -68
  42. package/src/struct.js +101 -33
  43. package/src/types.js +14 -14
  44. package/src/util.js +41 -50
package/src/rules.js ADDED
@@ -0,0 +1,185 @@
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
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');
8
+ const { SchemaDefinitionError } = require('./errors.js');
9
+
10
+ const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
11
+
12
+ const invalidLength = (reason = 'needs a number, [min, max] or { min, max }') =>
13
+ new SchemaDefinitionError('ERR_INVALID_LENGTH', `Rule "length" ${reason}`);
14
+
15
+ const isBound = (value) => value === undefined || typeof value === 'number';
16
+
17
+ const isLimit = (value) => typeof value === 'number' || typeof value === 'bigint';
18
+
19
+ const formatLength = (length) => {
20
+ if (typeof length === 'number') return { max: length };
21
+ if (length === null || typeof length !== 'object') throw invalidLength();
22
+ const min = Array.isArray(length) ? length[0] : length.min;
23
+ const max = Array.isArray(length) ? length[1] : length.max;
24
+ if (!isBound(min) || !isBound(max)) throw invalidLength();
25
+ if (min !== undefined && max !== undefined && min > max) throw invalidLength('has min above max');
26
+ return { min, max };
27
+ };
28
+
29
+ // A number or a bigint, kept as it is: a bigint bound compared with a number
30
+ // value (and the other way round) is exact in JavaScript, Number(bigint) is not.
31
+ const formatLimit = (name) => (value) => {
32
+ if (!isLimit(value)) throw invalidRule(`Rule "${name}" needs a number or a bigint`);
33
+ return value;
34
+ };
35
+
36
+ // A pattern is compiled once, here, with the `u` flag (so `\p{L}` and
37
+ // astral characters mean what they say), and without `g` and `y`, whose
38
+ // lastIndex would make the same test give different answers in a row.
39
+ const formatPattern = (value) => {
40
+ const isRegExp = value instanceof RegExp;
41
+ if (!isRegExp && typeof value !== 'string') {
42
+ throw invalidRule('Rule "pattern" needs a string or a RegExp');
43
+ }
44
+ const source = isRegExp ? value.source : value;
45
+ const given = isRegExp ? value.flags.replace(/[guy]/g, '') : '';
46
+ try {
47
+ return new RegExp(source, `${given}u`);
48
+ } catch (error) {
49
+ throw invalidRule(`Rule "pattern" is not a valid regular expression: ${error.message}`);
50
+ }
51
+ };
52
+
53
+ // The formatter of each rule, by name; the names are the rules that exist. A
54
+ // null-prototype dictionary: a definition key may be called `constructor`.
55
+ const FORMAT = Object.assign(Object.create(null), {
56
+ length: formatLength,
57
+ min: formatLimit('min'),
58
+ max: formatLimit('max'),
59
+ pattern: formatPattern,
60
+ });
61
+
62
+ const notApplicable = (rule, type, rules) => {
63
+ const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
64
+ return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
65
+ };
66
+
67
+ // Code points of a string: a surrogate pair counts once, a lone surrogate
68
+ // once too.
69
+ const codePoints = (text) => {
70
+ const { length } = text;
71
+ let count = 0;
72
+ for (let index = 0; index < length; index += 1) {
73
+ const unit = text.charCodeAt(index);
74
+ if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < length) {
75
+ const next = text.charCodeAt(index + 1);
76
+ if (next >= 0xdc00 && next <= 0xdfff) index += 1;
77
+ }
78
+ count += 1;
79
+ }
80
+ return count;
81
+ };
82
+
83
+ // The own keys of an object, counted without a list of them.
84
+ const keyCount = (value) => {
85
+ let count = 0;
86
+ for (const name in value) if (Object.hasOwn(value, name)) count += 1;
87
+ return count;
88
+ };
89
+
90
+ // The length of a value, by what the value is rather than by what it carries
91
+ // (an object with a `size` key is an object): the units of a string, the
92
+ // length of an array, the size of a Set or a Map, the own keys of an object.
93
+ const lengthOf = (value) => {
94
+ if (typeof value === 'string' || Array.isArray(value)) return value.length;
95
+ const name = value.constructor?.name;
96
+ return name === 'Set' || name === 'Map' ? value.size : keyCount(value);
97
+ };
98
+
99
+ // A string field measures its units, or its code points when it asks for
100
+ // them; anything else is measured by what it is. One closure per case, each
101
+ // calling its measure directly: a measure held in a variable is a call site
102
+ // shared by every length rule of the process, which V8 then cannot inline.
103
+ const compileLength = (type) => {
104
+ const { min, max } = type.length;
105
+ if (type.scalar === 'string') {
106
+ if (type.unicode === true) {
107
+ return (value, context, key) => {
108
+ const actual = codePoints(value);
109
+ const short = min !== undefined && actual < min;
110
+ const long = max !== undefined && actual > max;
111
+ if (short || long) issues.length(context, min, max, actual, key);
112
+ };
113
+ }
114
+ return (value, context, key) => {
115
+ const actual = value.length;
116
+ const short = min !== undefined && actual < min;
117
+ const long = max !== undefined && actual > max;
118
+ if (short || long) issues.length(context, min, max, actual, key);
119
+ };
120
+ }
121
+ return (value, context, key) => {
122
+ const actual = lengthOf(value);
123
+ const short = min !== undefined && actual < min;
124
+ const long = max !== undefined && actual > max;
125
+ if (short || long) issues.length(context, min, max, actual, key);
126
+ };
127
+ };
128
+
129
+ // One closure for both bounds when a field has both.
130
+ const compileRange = (type) => {
131
+ const { min, max } = type;
132
+ if (min === undefined) {
133
+ return (value, context, key) => {
134
+ if (value > max) issues.range(context, min, max, value, key);
135
+ };
136
+ }
137
+ if (max === undefined) {
138
+ return (value, context, key) => {
139
+ if (value < min) issues.range(context, min, max, value, key);
140
+ };
141
+ }
142
+ if (min > max) throw invalidRule('Rule "max" is below "min"');
143
+ return (value, context, key) => {
144
+ if (value < min || value > max) issues.range(context, min, max, value, key);
145
+ };
146
+ };
147
+
148
+ const compilePattern = (type) => {
149
+ const { pattern } = type;
150
+ const { source } = pattern;
151
+ return (value, context, key) => {
152
+ if (!pattern.test(value)) issues.pattern(context, source, key);
153
+ };
154
+ };
155
+
156
+ // The rules a field carries, by name, in the order its type lists them, min
157
+ // and max as the one `range`: the order the closures run them in and the JIT
158
+ // emits them in.
159
+ const ruleNames = (type) => {
160
+ const names = [];
161
+ let range = false;
162
+ for (const name of type.constructor.rules) {
163
+ if (type[name] === undefined) continue;
164
+ if (name === 'min' || name === 'max') range = true;
165
+ else names.push(name);
166
+ }
167
+ if (range) names.push('range');
168
+ return names;
169
+ };
170
+
171
+ const COMPILERS = Object.assign(Object.create(null), {
172
+ length: compileLength,
173
+ pattern: compilePattern,
174
+ range: compileRange,
175
+ });
176
+
177
+ // The checks of the rules a field carries.
178
+ const compileRules = (type) => {
179
+ const names = ruleNames(type);
180
+ const checks = [];
181
+ for (let index = 0; index < names.length; index += 1) checks.push(COMPILERS[names[index]](type));
182
+ return checks;
183
+ };
184
+
185
+ module.exports = { FORMAT, notApplicable, ruleNames, compileRules, codePoints, lengthOf };
@@ -1,6 +1,6 @@
1
1
  // Browser twin of ./node.js: the same interface, mapped in by the package.json
2
2
  // `browser` field. There is no file system to write to, so it rejects.
3
3
 
4
- const saveTypes = () => Promise.reject(new Error('saveTypes is not available in the browser'));
4
+ const writeFile = () => Promise.reject(new Error('saveTypes is not available in the browser'));
5
5
 
6
- module.exports = { saveTypes };
6
+ module.exports = { writeFile };
@@ -1,5 +1,7 @@
1
1
  const fsp = require('node:fs').promises;
2
2
 
3
- const saveTypes = (outputFile, model) => fsp.writeFile(outputFile, model.dts);
3
+ // The one file-system call of the package, behind `saveTypes` of the
4
+ // `./generators` subpath.
5
+ const writeFile = (outputFile, text) => fsp.writeFile(outputFile, text);
4
6
 
5
- module.exports = { saveTypes };
7
+ module.exports = { writeFile };
package/src/schema.js CHANGED
@@ -1,58 +1,74 @@
1
1
  const { isFirstUpper } = require('./metautil.js');
2
2
 
3
- const { BRAND, INSPECT, hasBrand, ancestors, limits } = require('./util.js');
3
+ const { BRAND, INSPECT, RUN, HOOK, hasBrand } = require('./util.js');
4
+ const { createContext } = require('./context.js');
4
5
  const { TYPES } = require('./types.js');
5
6
  const { Preprocessor } = require('./preprocessor.js');
6
- const { SchemaMetadata, ValidationResult } = require('./metadata.js');
7
+ const { SchemaMetadata } = require('./metadata.js');
8
+ const { ValidationResult } = require('./result.js');
9
+ const { finalize, runValidate, settle } = require('./issues.js');
7
10
  const { SchemaDefinitionError } = require('./errors.js');
8
- const { createStruct, checkStruct } = require('./struct.js');
11
+ const { createStruct, isStruct, checkOf } = require('./struct.js');
12
+ const { warning, lintSchema } = require('./lint.js');
13
+ const { PREPARE, FINISH, SERIALIZE, infoOf, apply, looped, hasAsync } = require('./codec.js');
9
14
 
10
- const TS_SCALARS = { string: 'string', number: 'number', boolean: 'boolean', bigint: 'bigint' };
11
-
12
- const maxErrorsOf = ({ maxErrors }) => {
13
- const valid = typeof maxErrors === 'number' && maxErrors >= 1;
14
- if (!valid) throw new TypeError(`maxErrors must be a number of at least 1, got ${maxErrors}`);
15
- return maxErrors;
15
+ // The validation of a schema inside an existing context: `check` starts one,
16
+ // and a reference field checks its target entity within the context of the
17
+ // outer check, so the error limit and the cycle detection span the whole
18
+ // value. The schema-level validate runs last, and only on a value whose
19
+ // fields all passed, so it can rely on their shape. Built once per schema,
20
+ // as Schema[RUN].
21
+ const compileSchema = (schema) => {
22
+ const { fields, options } = schema;
23
+ const run = isStruct(fields) ? checkOf(fields) : fields.check;
24
+ return (value, context, key) => {
25
+ const before = context.count;
26
+ run(value, context, key);
27
+ const { validate } = options;
28
+ if (validate && context.count === before) {
29
+ const nested = key !== undefined;
30
+ if (nested) context.path.push(key);
31
+ runValidate(schema, validate, value, context);
32
+ if (nested) context.path.pop();
33
+ }
34
+ };
16
35
  };
17
36
 
18
- const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
19
-
20
- // The TypeScript type of a field. A reference is stored as an id, so it
21
- // renders as a string (an array of them for `many`); a custom scalar with its
22
- // own check has no known shape and renders as a string too.
23
- const tsType = (def) => {
24
- if (isFirstUpper(def.type)) return def.many ? 'string[]' : 'string';
25
- if (def.enum) return def.enum.map((value) => JSON.stringify(value)).join(' | ');
26
- if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
27
- if (def.schema) return `{ ${tsFields(def.schema).join('; ')} }`;
28
- if (Array.isArray(def.value)) return `[${def.value.map(tsType).join(', ')}]`;
29
- if (def.key !== undefined && def.value) {
30
- const entries = `${def.key}, ${tsType(def.value)}`;
31
- return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
32
- }
33
- if (def.value) return listOf(tsType(def.value));
34
- if (def.kind === 'struct') return 'unknown';
35
- return 'string';
37
+ const resultOf = (context) => {
38
+ finalize(context.issues, context.messages);
39
+ return new ValidationResult(context);
36
40
  };
37
41
 
38
- const tsFields = (fields) => {
39
- const lines = [];
40
- for (const pair of Object.entries(fields)) {
41
- const key = pair[0];
42
- const def = pair[1];
43
- if (!hasBrand(def, 'Type')) continue;
44
- const optional = def.required ? '' : '?';
45
- const name = isFirstUpper(def.type) ? `${key}Id` : key;
46
- lines.push(`${name}${optional}: ${tsType(def)}`);
47
- }
48
- return lines;
42
+ // What parse returns: the output only for a valid value, the issues always.
43
+ const parsed = (context, output) => {
44
+ finalize(context.issues, context.messages);
45
+ const valid = context.count === 0;
46
+ return { valid, value: valid ? output : undefined, issues: context.issues };
49
47
  };
50
48
 
49
+ // The result of parse read as Standard Schema does.
50
+ const standardize = (result) =>
51
+ result.valid ? { value: result.value } : { issues: result.issues };
52
+
51
53
  class Schema extends SchemaMetadata {
52
54
  // The merged type table of the attached namespaces, rebuilt only when they
53
55
  // change.
54
56
  #types = null;
55
57
 
58
+ // Whether the root value joins the cycle detection (`context.source`):
59
+ // only a struct with references can reach it again.
60
+ #tracked = false;
61
+
62
+ // The lint of the definition, run on first use: a schema built in a hot
63
+ // path never pays for it.
64
+ #warnings = null;
65
+
66
+ // The Standard Schema props, built on first use.
67
+ #standard = null;
68
+
69
+ // What the passes of parse and serialize know about the schema, on first use.
70
+ #codec = null;
71
+
56
72
  static from(source, namespaces) {
57
73
  return new Schema('', source, namespaces);
58
74
  }
@@ -91,17 +107,55 @@ class Schema extends SchemaMetadata {
91
107
  const combined = { ...fields, ...extras };
92
108
  this.fields = createStruct(combined, preprocessor);
93
109
  }
110
+ this.#tracked = isSchemaType && this.relations.size > 0;
111
+ this[RUN] = compileSchema(this);
112
+ const hook = Schema[HOOK];
113
+ if (hook !== undefined) hook(this);
114
+ }
115
+
116
+ // What is not wrong enough to throw: `Warning [code]: text` strings.
117
+ get warnings() {
118
+ if (this.#warnings === null) this.#warnings = lintSchema(this);
119
+ return this.#warnings;
120
+ }
121
+
122
+ // Standard Schema v1 (https://standardschema.dev): the interface tRPC,
123
+ // TanStack Form, Hono and the other consumers of the specification validate
124
+ // through. `validate` is `parse` with the policies of the schema: the value
125
+ // that comes back has the defaults and the decoders applied (the value
126
+ // itself when there was nothing to apply), and the issues of an invalid one
127
+ // are the result's own (a message and a path of keys each). A schema with
128
+ // an async validator or decoder validates through parseAsync, as the
129
+ // specification allows. The vendor-specific `libraryOptions` of a call are
130
+ // the options of `parse`. An accessor of the prototype stays out of toJSON,
131
+ // inspect and Object.keys, and `validate` closes over the schema because a
132
+ // consumer calls it unbound. The `./generators` subpath adds the
133
+ // `jsonSchema` converter of Standard JSON Schema to the props.
134
+ get '~standard'() {
135
+ if (this.#standard === null) {
136
+ const async = hasAsync(this);
137
+ const validate = (value, options) => {
138
+ const libraryOptions = options == null ? undefined : options.libraryOptions;
139
+ if (async) return this.parseAsync(value, libraryOptions).then(standardize);
140
+ return standardize(this.parse(value, libraryOptions));
141
+ };
142
+ this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
143
+ }
144
+ return this.#standard;
94
145
  }
95
146
 
96
147
  get types() {
97
148
  if (this.namespaces.size === 0) return TYPES;
98
149
  if (this.#types === null) {
99
- const types = Array.from(this.namespaces).map((ns) => ns.types);
100
- this.#types = Object.assign(Object.create(null), ...types);
150
+ const types = Object.create(null);
151
+ for (const ns of this.namespaces) Object.assign(types, ns.types);
152
+ this.#types = types;
101
153
  }
102
154
  return this.#types;
103
155
  }
104
156
 
157
+ // The warnings that need the namespaces: references and types that do
158
+ // not resolve.
105
159
  checkConsistency() {
106
160
  const warn = [];
107
161
  const { name, references } = this;
@@ -109,10 +163,10 @@ class Schema extends SchemaMetadata {
109
163
  if (isFirstUpper(ref)) {
110
164
  const entity = this.findReference(ref);
111
165
  if (!entity) {
112
- warn.push(`Warning: "${ref}" referenced by "${name}" is not found`);
166
+ warn.push(warning('missing-reference', `"${ref}" referenced by "${name}" is not found`));
113
167
  }
114
168
  } else if (!this.types[ref]) {
115
- warn.push(`Warning: type "${ref}" is not found in "${name}"`);
169
+ warn.push(warning('missing-type', `type "${ref}" is not found in "${name}"`));
116
170
  }
117
171
  }
118
172
  return warn;
@@ -126,45 +180,104 @@ class Schema extends SchemaMetadata {
126
180
  return null;
127
181
  }
128
182
 
129
- check(source, path = this.name, options = {}) {
130
- const result = new ValidationResult(path);
131
- const { fields } = this;
132
- const isStruct = hasBrand(fields, 'Struct');
133
- // The root of a struct joins the path too, unless a field check already put
134
- // it there (a reference checks its target through this method). A schema
135
- // of any other type delegates to that type's check, which tracks itself.
136
- const isObject = typeof source === 'object' && source !== null;
137
- const track = isStruct && isObject && !ancestors.has(source);
138
- if (track) ancestors.add(source);
139
- const previous = limits.maxErrors;
140
- if (options.maxErrors !== undefined) limits.maxErrors = maxErrorsOf(options);
141
- try {
142
- const custom = this.validate(source, path);
143
- result.add(custom);
144
- if (result.full) return result;
145
- const nested = isStruct ? checkStruct(fields, source, path) : fields.check(source, path);
146
- return result.add(nested);
147
- } finally {
148
- limits.maxErrors = previous;
149
- if (track) ancestors.delete(source);
183
+ // Validates a value: every problem is collected as an issue, and the result
184
+ // never throws because of the value. `options`: root (the label of the
185
+ // error lines, the schema name by default), maxErrors, unknown ('reject'
186
+ // or 'ignore' keys the schema does not have), references, messages (a
187
+ // locale). A validator that returns a promise is an error here.
188
+ // `createContext` is called directly in every method here, never through a
189
+ // helper: V8 inlines the allocation into `check` that way (the context is
190
+ // the one allocation of a valid check), and a method in between cost 7%.
191
+ check(source, options) {
192
+ const context = createContext(options, this.name, this.unknown);
193
+ if (this.#tracked) context.source = source;
194
+ this[RUN](source, context);
195
+ return resultOf(context);
196
+ }
197
+
198
+ // The same check, with the validators that return a promise settled after
199
+ // the walk, in field order.
200
+ async checkAsync(source, options) {
201
+ const context = createContext(options, this.name, this.unknown);
202
+ context.async = [];
203
+ if (this.#tracked) context.source = source;
204
+ this[RUN](source, context);
205
+ if (context.async.length > 0) await settle(context);
206
+ return resultOf(context);
207
+ }
208
+
209
+ #pass(phase, source, context) {
210
+ if (this.#codec === null) this.#codec = infoOf(this);
211
+ return apply(this.#codec, this, source, context, undefined, phase);
212
+ }
213
+
214
+ // The defaults of the schema over a value, before its check; the objects
215
+ // met on the way down are not the check's, and a value that loops through
216
+ // its references is checked as it was given.
217
+ #prepare(source, context) {
218
+ const prepared = this.#pass(PREPARE, source, context);
219
+ const value = looped(context) ? source : prepared;
220
+ context.seen = null;
221
+ if (this.#tracked) context.source = value;
222
+ return value;
223
+ }
224
+
225
+ // Validates a value and builds the value of the program from it: the
226
+ // defaults fill the missing keys, the check runs, and a valid value goes
227
+ // through `unknown: 'strip'`, the decoders of its fields (the parts of a
228
+ // value before the value) and the schema's own `parse`. `{ valid, value,
229
+ // issues }`: the value is undefined when invalid, and the value given when
230
+ // there was nothing to apply; the value given is never written to.
231
+ parse(source, options) {
232
+ const context = createContext(options, this.name, this.unknown, true);
233
+ const value = this.#prepare(source, context);
234
+ this[RUN](value, context);
235
+ const output = context.count === 0 ? this.#pass(FINISH, value, context) : undefined;
236
+ return parsed(context, output);
237
+ }
238
+
239
+ async parseAsync(source, options) {
240
+ const context = createContext(options, this.name, this.unknown, true);
241
+ context.async = [];
242
+ const value = this.#prepare(source, context);
243
+ this[RUN](value, context);
244
+ if (context.async.length > 0) await settle(context);
245
+ let output;
246
+ if (context.count === 0) {
247
+ // Only a promise of the pass is awaited: a thenable in the value is data.
248
+ output = this.#pass(FINISH, value, context);
249
+ if (output instanceof Promise) output = (await output).value;
150
250
  }
251
+ return parsed(context, output);
151
252
  }
152
253
 
153
- toInterface() {
154
- const { name, fields } = this;
155
- if (!hasBrand(fields, 'Struct')) return `type ${name} = ${tsType(fields)};`;
156
- const lines = tsFields(fields).map((line) => ` ${line};`);
157
- return [`interface ${name} {`, ...lines, '}'].join('\n');
254
+ // The other direction: the schema's own `serialize`, then the serializers
255
+ // of the fields, from the value down to its parts. `{ value }`, or with
256
+ // `options.check` the verdict of `check` over the result as well.
257
+ serialize(source, options) {
258
+ const context = createContext(options, this.name, this.unknown);
259
+ const value = this.#pass(SERIALIZE, source, context);
260
+ if (options === undefined || options.check !== true) return { value };
261
+ context.seen = null;
262
+ if (this.#tracked) context.source = value;
263
+ this[RUN](value, context);
264
+ finalize(context.issues, context.messages);
265
+ return { valid: context.count === 0, value, issues: context.issues };
158
266
  }
159
267
 
268
+ // The types and the Standard Schema props depend on the namespaces (the
269
+ // latter through the entities an async validator may be in), so both are
270
+ // rebuilt on the next use.
160
271
  attach(...namespaces) {
161
272
  for (const ns of namespaces) this.namespaces.add(ns);
162
273
  this.#types = null;
274
+ this.#standard = null;
163
275
  }
164
276
 
165
277
  detach(...namespaces) {
166
278
  for (const ns of namespaces) this.namespaces.delete(ns);
167
279
  this.#types = null;
280
+ this.#standard = null;
168
281
  }
169
282
 
170
283
  toString() {