@alexify/metaschema 3.1.0 → 3.3.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 (56) hide show
  1. package/CHANGELOG.md +314 -1
  2. package/README.md +535 -20
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +496 -2
  5. package/package.json +53 -5
  6. package/src/codec.js +239 -74
  7. package/src/coerce/index.d.ts +34 -0
  8. package/src/coerce/index.js +352 -0
  9. package/src/compile/code.js +1 -1
  10. package/src/compile/emit.js +32 -7
  11. package/src/compile/index.d.ts +6 -0
  12. package/src/compile/index.js +12 -1
  13. package/src/context.js +11 -10
  14. package/src/derive/index.d.ts +86 -0
  15. package/src/derive/index.js +266 -0
  16. package/src/errors.js +28 -1
  17. package/src/formats/index.d.ts +31 -0
  18. package/src/formats/index.js +557 -0
  19. package/src/generators/fromjsonschema.js +16 -14
  20. package/src/generators/index.js +2 -1
  21. package/src/generators/jsonschema.js +47 -13
  22. package/src/issues.js +37 -20
  23. package/src/kinds.js +11 -2
  24. package/src/lint.js +24 -0
  25. package/src/locales/en.js +11 -2
  26. package/src/locales/uk.js +10 -2
  27. package/src/metadata.js +7 -2
  28. package/src/model/data.js +17 -0
  29. package/src/model/diff.js +1 -0
  30. package/src/model/index.d.ts +14 -2
  31. package/src/model/index.js +13 -10
  32. package/src/model/infer.js +483 -0
  33. package/src/model/merge.js +10 -6
  34. package/src/model/restore.js +3 -3
  35. package/src/model/sample.js +8 -5
  36. package/src/model.js +34 -4
  37. package/src/mongodb/bson.js +118 -0
  38. package/src/mongodb/document.js +209 -0
  39. package/src/mongodb/index.d.ts +133 -0
  40. package/src/mongodb/index.js +24 -0
  41. package/src/mongodb/indexes.js +79 -0
  42. package/src/mongodb/update.js +258 -0
  43. package/src/preprocessor.js +1 -0
  44. package/src/prototypes/abstract.js +9 -3
  45. package/src/prototypes/collections.js +4 -3
  46. package/src/prototypes/scalars.js +4 -4
  47. package/src/prototypes/union.js +2 -2
  48. package/src/result.js +6 -0
  49. package/src/rules.js +53 -4
  50. package/src/schema.js +53 -28
  51. package/src/snapshot.js +1 -1
  52. package/src/stream/index.d.ts +68 -0
  53. package/src/stream/index.js +247 -0
  54. package/src/struct.js +1 -1
  55. package/src/types.js +33 -1
  56. package/src/util.js +18 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alexify/metaschema",
3
- "version": "3.1.0",
4
- "description": "Zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — data validation, domain models and TypeScript generation",
3
+ "version": "3.3.0",
4
+ "description": "Fast, zero-dependency metadata schema and interface definition language (IDL) for Node.js and browsers — validation and parsing with a JIT backend, domain models, TypeScript and JSON Schema",
5
5
  "license": "MIT",
6
6
  "author": "Alex Dolid <dolid.sasha@gmail.com>",
7
7
  "repository": {
@@ -46,6 +46,26 @@
46
46
  "./model": {
47
47
  "types": "./src/model/index.d.ts",
48
48
  "default": "./src/model/index.js"
49
+ },
50
+ "./stream": {
51
+ "types": "./src/stream/index.d.ts",
52
+ "default": "./src/stream/index.js"
53
+ },
54
+ "./formats": {
55
+ "types": "./src/formats/index.d.ts",
56
+ "default": "./src/formats/index.js"
57
+ },
58
+ "./derive": {
59
+ "types": "./src/derive/index.d.ts",
60
+ "default": "./src/derive/index.js"
61
+ },
62
+ "./coerce": {
63
+ "types": "./src/coerce/index.d.ts",
64
+ "default": "./src/coerce/index.js"
65
+ },
66
+ "./mongodb": {
67
+ "types": "./src/mongodb/index.d.ts",
68
+ "default": "./src/mongodb/index.js"
49
69
  }
50
70
  },
51
71
  "directories": {
@@ -61,6 +81,7 @@
61
81
  "LICENSE",
62
82
  "SECURITY.md"
63
83
  ],
84
+ "sideEffects": false,
64
85
  "publishConfig": {
65
86
  "access": "public"
66
87
  },
@@ -68,6 +89,8 @@
68
89
  "directory": "tests/types"
69
90
  },
70
91
  "keywords": [
92
+ "mongodb",
93
+ "bson",
71
94
  "schema",
72
95
  "metaschema",
73
96
  "metadata",
@@ -76,6 +99,11 @@
76
99
  "dsl",
77
100
  "validation",
78
101
  "data-validation",
102
+ "fast",
103
+ "jit",
104
+ "parse",
105
+ "standard-schema",
106
+ "json-schema",
79
107
  "domain-model",
80
108
  "model",
81
109
  "typescript",
@@ -85,21 +113,36 @@
85
113
  "metarhia"
86
114
  ],
87
115
  "devDependencies": {
88
- "@sinclair/typebox": "^0.34.52",
116
+ "@braintree/sanitize-url": "^7.1.2",
89
117
  "@standard-schema/spec": "^1.1.0",
90
118
  "@vercel/analytics": "^2.0.1",
91
119
  "@vercel/speed-insights": "^2.0.0",
92
120
  "ajv": "^8.20.0",
93
121
  "ajv-formats": "^3.0.1",
122
+ "arktype": "^2.2.8",
123
+ "bson": "7.3.3",
94
124
  "c8": "^12.0.0",
125
+ "cytoscape": "^3.34.3",
126
+ "cytoscape-cose-bilkent": "^4.1.0",
127
+ "dayjs": "^1.11.23",
128
+ "debug": "^4.4.3",
129
+ "effect": "^4.0.3",
95
130
  "esbuild": "^0.28.2",
131
+ "fastdom": "1.0.12",
132
+ "joi": "^18.2.9",
133
+ "mermaid": "^11.17.2",
134
+ "metaschema": "2.2.2",
96
135
  "oxfmt": "^0.72.0",
97
136
  "oxlint": "^1.75.0",
137
+ "superstruct": "^2.0.2",
98
138
  "tsd": "^0.33.0",
139
+ "typebox": "^1.3.36",
99
140
  "typescript": "^7.0.2",
100
141
  "valibot": "^1.5.0",
101
142
  "vitepress": "^1.6.4",
102
- "zod": "^4.6.5"
143
+ "vitepress-plugin-mermaid": "^2.0.17",
144
+ "yup": "^1.7.1",
145
+ "zod": "^4.6.6"
103
146
  },
104
147
  "scripts": {
105
148
  "test": "node --test tests/unit/*.test.js",
@@ -107,15 +150,20 @@
107
150
  "test:nojit": "node --disallow-code-generation-from-strings --require ./tests/helpers/jit.js --test tests/unit/*.test.js",
108
151
  "test:coverage": "c8 --all --include 'src/**' --check-coverage --lines 98 --statements 98 --branches 90 --functions 100 --reporter text --reporter lcov node --test tests/unit/*.test.js",
109
152
  "test:types": "tsd",
110
- "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts src/model/index.d.ts",
153
+ "check:dts": "tsc --noEmit --strict --target es2022 --skipLibCheck false index.d.ts src/locales/en.d.ts src/locales/uk.d.ts src/generators/index.d.ts src/compile/index.d.ts src/model/index.d.ts src/stream/index.d.ts src/formats/index.d.ts src/derive/index.d.ts src/coerce/index.d.ts src/mongodb/index.d.ts",
111
154
  "lint": "oxlint index.js browser.js src tests scripts bench",
112
155
  "format": "oxfmt index.js browser.js src tests scripts bench",
113
156
  "format:check": "oxfmt --check index.js browser.js src tests scripts bench",
114
157
  "size": "node scripts/size.js",
115
158
  "bench": "node bench/bench.js",
159
+ "bench:compare": "node bench/compare.js",
160
+ "bench:releases": "node bench/releases.js",
161
+ "bench:report": "node bench/report.js",
162
+ "size:compare": "node scripts/size-compare.js",
116
163
  "docs:dev": "vitepress dev docs",
117
164
  "docs:build": "vitepress build docs",
118
165
  "docs:preview": "vitepress preview docs",
166
+ "docs:comparison": "node scripts/comparison.js",
119
167
  "release": "pnpm publish"
120
168
  }
121
169
  }
package/src/codec.js CHANGED
@@ -1,17 +1,27 @@
1
- // What parse and serialize do beyond the check: the defaults, the decoders,
2
- // the serializers and the stripping of unknown keys, as passes over the built
3
- // types. `parse` is the check of the schema (whichever backend installed it)
4
- // between two passes, defaults before and decoders after; `serialize` is one
1
+ // What parse and serialize do beyond the check: the coercion of the input,
2
+ // the defaults, the decoders, the serializers and the stripping of unknown
3
+ // keys, as passes over the built types. `parse` is the check of the schema
4
+ // (whichever backend installed it) between two passes, coercion and defaults
5
+ // before and decoders after; `serialize` is one
5
6
  // pass the other way. The passes read the same plan the closures walk and
6
7
  // validate nothing themselves, so the JIT needs no second generator. A node
7
8
  // whose subtree carries nothing for a phase is returned as it is, and a
8
9
  // container is copied only when one of its parts changed: the value given is
9
10
  // never written to.
10
- const { hasBrand, define } = require('./util.js');
11
- const { EMPTY, NONE, issues, isThenable, abandon, pathOf, toDotPath } = require('./issues.js');
11
+ const { hasBrand, define, isMap, isSet } = require('./util.js');
12
+ const {
13
+ EMPTY,
14
+ NONE,
15
+ issues,
16
+ isThenable,
17
+ abandon,
18
+ release,
19
+ pathOf,
20
+ toDotPath,
21
+ } = require('./issues.js');
12
22
  const { createContext } = require('./context.js');
13
23
  const { STRUCT, isStruct, aliasOf } = require('./struct.js');
14
- const { asyncReturn } = require('./errors.js');
24
+ const { asyncReturn, notRegistered } = require('./errors.js');
15
25
  const collections = require('./prototypes/collections.js');
16
26
  const { schema: struct } = require('./prototypes/schema.js');
17
27
  const { tuple } = require('./prototypes/tuple.js');
@@ -27,6 +37,27 @@ const ASYNC = 16;
27
37
  // A field with aliases below: the pass after the check visits it only when
28
38
  // the check read a field from an alias (`context.renamed`).
29
39
  const ALIASES = 32;
40
+ // On every info: a pass before the check that coerces enters every subtree,
41
+ // since any value of the input may need a conversion.
42
+ const COERCE = 64;
43
+ // A field with `coerce: true` of its own below: the pass before the check
44
+ // converts there whatever the policy of the call.
45
+ const POLICY = 128;
46
+
47
+ // The converters of coercion, by type name, are the `./coerce` subpath's:
48
+ // its register() installs `resolve` here (the converter of a node, or null)
49
+ // and says so. The converter resolved is kept on the info of the node with
50
+ // the `version` it was resolved under, which every register() bumps, so a
51
+ // leaf pays no lookup per visit. Until the subpath is registered a pass
52
+ // that coerces is a call that cannot work, and says so as it enters the
53
+ // schema (`walkSchema`), whatever the value holds.
54
+ const COERCION = {
55
+ installed: false,
56
+ version: 0,
57
+ resolve() {
58
+ throw notRegistered('coerce', 'coerce');
59
+ },
60
+ };
30
61
 
31
62
  // The shape of a node: a Schema, a struct (the dictionary of its fields), or
32
63
  // a field by the identity of its prototype's compile, as the JIT tells them
@@ -62,7 +93,9 @@ const isAsyncFunction = (fn) => typeof fn === 'function' && fn.constructor.name
62
93
 
63
94
  // What the passes know about a node, computed on first use and kept apart
64
95
  // from the node: its shape, the bits of its subtree, its own decoder and
65
- // serializer, its children with their infos, the fields of a struct a phase
96
+ // serializer, its own coercion policy (a field's `coerce` key, which turns
97
+ // coercion on or off for its subtree), its children with their infos, the
98
+ // fields of a struct a phase
66
99
  // has to visit (`parts`, by phase bit; every field under `strip`), and the
67
100
  // reference fields beneath it (their targets are resolved at parse time, so a
68
101
  // reference counts as carrying everything).
@@ -76,8 +109,14 @@ const infoOf = (node) => {
76
109
  const own = shape === SCHEMA ? node.options : shape === FIELDS ? EMPTY : node;
77
110
  const decode = own.parse || undefined;
78
111
  const encode = own.serialize || undefined;
79
- let bits = decode === undefined ? 0 : DECODERS;
112
+ // A field that coerces makes the pass before the check enter its subtree
113
+ // whatever the policy of the call. An own key only: a `coerce` set on
114
+ // Object.prototype elsewhere must not turn every schema's on.
115
+ const policy = Object.hasOwn(own, 'coerce') ? own.coerce : undefined;
116
+ const coerce = policy === true ? true : policy === false ? false : undefined;
117
+ let bits = decode === undefined ? COERCE : COERCE | DECODERS;
80
118
  if (encode !== undefined) bits |= ENCODERS;
119
+ if (coerce === true) bits |= DEFAULTS | POLICY;
81
120
  if (isAsyncFunction(own.validate) || isAsyncFunction(decode) || isAsyncFunction(own.checkType)) {
82
121
  bits |= ASYNC;
83
122
  }
@@ -137,7 +176,26 @@ const infoOf = (node) => {
137
176
  parts[STRUCTS].push(index);
138
177
  }
139
178
  }
140
- info = { shape, bits, decode, encode, children, infos, plan, parts, extra, table, refs };
179
+ // The walker of the node: the one of its shape, or for a field with a
180
+ // coercion policy of its own the one that applies the policy first.
181
+ const walk = coerce === undefined ? WALKERS[shape] : walkPolicy;
182
+ info = {
183
+ shape,
184
+ walk,
185
+ bits,
186
+ decode,
187
+ encode,
188
+ coerce,
189
+ convert: null,
190
+ version: -1,
191
+ children,
192
+ infos,
193
+ plan,
194
+ parts,
195
+ extra,
196
+ table,
197
+ refs,
198
+ };
141
199
  INFO.set(node, info);
142
200
  return info;
143
201
  };
@@ -176,14 +234,13 @@ const toMap = (value) => new Map(value);
176
234
 
177
235
  const toSet = (list) => new Set(list);
178
236
 
179
- // The output of a container under construction: the container is copied at
180
- // the first part that changed (`clone`), a part is written with `put`, and
181
- // the parts that decoded asynchronously are written in once they settle (a
182
- // decoder that failed resolved to nothing and recorded its issue). A
183
- // container pushes its key on the path for its parts.
184
- const enter = (context, key, value, clone, put) => {
185
- if (key !== undefined) context.path.push(key);
186
- return { context, key, value, clone, put, out: null, pending: null };
237
+ // The output of a container under construction, kept in the locals of its
238
+ // walker (no state object per container): null until a part changes, then a
239
+ // copy of the container (`clone`) the parts are written into (`put`).
240
+ const written = (out, value, clone, put, key, result) => {
241
+ const target = out === null ? clone(value) : out;
242
+ put(target, key, result);
243
+ return target;
187
244
  };
188
245
 
189
246
  // A part that is still decoding: only a decoder makes a promise (a thenable
@@ -191,13 +248,11 @@ const enter = (context, key, value, clone, put) => {
191
248
  // of the data with a `then` of its own is data, never awaited.
192
249
  const isPending = (context, value) => context.async !== null && value instanceof Promise;
193
250
 
194
- const take = (state, key, result, phase) => {
195
- if (state.out === null) state.out = state.clone(state.value);
196
- state.put(state.out, key, result);
197
- if (phase === DECODERS && isPending(state.context, result)) {
198
- if (state.pending === null) state.pending = [];
199
- state.pending.push(key, result);
200
- }
251
+ // The parts of a container still decoding, as key, promise, key, promise.
252
+ const queued = (pending, key, result) => {
253
+ const list = pending === null ? [] : pending;
254
+ list.push(key, result);
255
+ return list;
201
256
  };
202
257
 
203
258
  // What a promise of the passes resolves to: a box around the value, never
@@ -205,10 +260,11 @@ const take = (state, key, result, phase) => {
205
260
  // own and the value of a program may well have one.
206
261
  const boxed = (value) => ({ value });
207
262
 
208
- const leave = (state, wrap) => {
209
- const { context, key, out, pending, put } = state;
210
- if (key !== undefined) context.path.pop();
211
- if (out === null) return state.value;
263
+ // What a container comes back as: the value when no part changed, its copy,
264
+ // or a promise of a box when parts are still decoding, written in once they
265
+ // settle (a decoder that failed resolved to nothing and recorded its issue).
266
+ const settled = (value, out, pending, put, wrap) => {
267
+ if (out === null) return value;
212
268
  if (pending === null) return wrap === undefined ? out : wrap(out);
213
269
  const promises = [];
214
270
  for (let index = 1; index < pending.length; index += 2) promises.push(pending[index]);
@@ -267,7 +323,22 @@ const decode = (info, node, value, context, key) => {
267
323
  });
268
324
  };
269
325
 
270
- const walkLeaf = (info, node, value) => value;
326
+ // Under coercion a leaf, a list, a tuple or a dictionary asks for a
327
+ // conversion of its value before anything else looks at it (a struct, a
328
+ // union or a reference has none of its own: their parts convert; a tuple
329
+ // and an `object` have no built-in converter, and get the value back). Done
330
+ // by the walkers so that apply stays as small as parse needs it to be
331
+ // inlined.
332
+ const convert = (want, value, node, info) => {
333
+ if ((want & COERCE) === 0) return value;
334
+ if (info.version !== COERCION.version) {
335
+ info.convert = COERCION.resolve(node);
336
+ info.version = COERCION.version;
337
+ }
338
+ return info.convert === null ? value : info.convert(value);
339
+ };
340
+
341
+ const walkLeaf = (info, node, value, context, key, phase, want) => convert(want, value, node, info);
271
342
 
272
343
  const walkInner = (info, node, value, context, key, phase, want) =>
273
344
  apply(info.infos[0], info.children[0], value, context, key, phase, want);
@@ -283,6 +354,11 @@ const LOOP = Symbol('loop');
283
354
  const looped = (context) => context.seen !== null && context.seen.has(LOOP);
284
355
 
285
356
  const walkSchema = (info, node, value, context, key, phase, want) => {
357
+ // A pass that converts somewhere below (the policy of the call, or a
358
+ // field's own) needs the converters, whatever the value holds.
359
+ if (phase === DEFAULTS && !COERCION.installed && ((want & COERCE) | (info.bits & POLICY)) !== 0) {
360
+ throw notRegistered('coerce', 'coerce');
361
+ }
286
362
  if (phase === DECODERS || info.refs.length === 0 || typeof value !== 'object') {
287
363
  return walkInner(info, node, value, context, key, phase, want);
288
364
  }
@@ -311,8 +387,9 @@ const renameKeys = (out, renames) => {
311
387
  return result;
312
388
  };
313
389
 
314
- // The fields of a struct: a default fills a missing key before the check, a
315
- // decoder replaces the value after it. Stripping rebuilds the object from
390
+ // The fields of a struct: before the check a present value is coerced and a
391
+ // default fills a missing key (coerced too: it is validated like any
392
+ // value), a decoder replaces the value after it. Stripping rebuilds the object from
316
393
  // the known keys; otherwise the object is copied when a field changed. A
317
394
  // value under an alias of a field is read from there (no default fills the
318
395
  // field, and the check sees it there), and the pass after the check writes
@@ -322,9 +399,12 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
322
399
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
323
400
  const { plan, infos, extra } = info;
324
401
  const strip = (want & STRUCTS) !== 0;
325
- const parts = info.parts[strip ? STRUCTS : phase];
326
- const state = enter(context, key, value, copy, putKey);
327
- if (strip) state.out = {};
402
+ // Every field under strip, and under coercion: any of them may convert.
403
+ const parts = info.parts[(want & (STRUCTS | COERCE)) !== 0 ? STRUCTS : phase];
404
+ const nested = key !== undefined;
405
+ if (nested) context.path.push(key);
406
+ let out = strip ? {} : null;
407
+ let pending = null;
328
408
  let renames = null;
329
409
  for (let position = 0; position < parts.length; position += 1) {
330
410
  const index = parts[position];
@@ -337,19 +417,25 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
337
417
  if (from !== name) item = value[from];
338
418
  }
339
419
  if (phase === DEFAULTS) {
340
- if (item === undefined) {
341
- const fallback = entry.type.default;
342
- if (fallback === undefined) continue;
343
- item = typeof fallback === 'function' ? fallback() : fallback;
344
- take(state, from, item, phase);
420
+ let result = item;
421
+ if (item !== undefined) {
422
+ result = apply(infos[index], entry.type, item, context, from, phase, want);
345
423
  }
346
- const result = apply(infos[index], entry.type, item, context, from, phase, want);
347
- if (result !== item) take(state, from, result, phase);
424
+ const fallback = entry.type.default;
425
+ if (result === undefined && fallback !== undefined) {
426
+ const filled = typeof fallback === 'function' ? fallback() : fallback;
427
+ out = written(out, value, copy, putKey, from, filled);
428
+ result = apply(infos[index], entry.type, filled, context, from, phase, want);
429
+ if (result !== filled) out = written(out, value, copy, putKey, from, result);
430
+ } else if (result !== item) out = written(out, value, copy, putKey, from, result);
348
431
  continue;
349
432
  }
350
433
  const result = apply(infos[index], entry.type, item, context, from, phase, want);
351
434
  const renamed = from !== name;
352
- if (strip ? result !== undefined : renamed || result !== item) take(state, name, result, phase);
435
+ if (strip ? result !== undefined : renamed || result !== item) {
436
+ out = written(out, value, copy, putKey, name, result);
437
+ if (phase === DECODERS && isPending(context, result)) pending = queued(pending, name, result);
438
+ }
353
439
  if (renamed && !strip) {
354
440
  if (renames === null) renames = [];
355
441
  renames.push(from, name);
@@ -358,45 +444,79 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
358
444
  if (strip) {
359
445
  for (let index = 0; index < extra.length; index += 1) {
360
446
  const name = extra[index];
361
- if (Object.hasOwn(value, name)) putKey(state.out, name, value[name]);
447
+ if (Object.hasOwn(value, name)) putKey(out, name, value[name]);
362
448
  }
363
- } else if (renames !== null) state.out = renameKeys(state.out, renames);
364
- return leave(state);
449
+ } else if (renames !== null) out = renameKeys(out, renames);
450
+ if (nested) context.path.pop();
451
+ return settled(value, out, pending, putKey, undefined);
365
452
  };
366
453
 
367
454
  // The elements of an array, a Set or a tuple, by position; a Set comes back
368
455
  // as a Set.
369
456
  const walkItems = (children, infos, fixed, value, context, key, phase, want) => {
370
457
  const set = !Array.isArray(value);
371
- if (set && (fixed || value.constructor?.name !== 'Set')) return value;
372
- const state = enter(context, key, value, Array.from, putIndex);
458
+ if (set && (fixed || !isSet(value))) return value;
459
+ const nested = key !== undefined;
460
+ if (nested) context.path.push(key);
461
+ let out = null;
462
+ let pending = null;
373
463
  let index = 0;
374
464
  for (const item of value) {
375
465
  const slot = fixed ? index : 0;
376
466
  if (slot >= children.length) break;
377
467
  const result = apply(infos[slot], children[slot], item, context, index, phase, want);
378
- if (result !== item) take(state, index, result, phase);
468
+ if (result !== item) {
469
+ out = written(out, value, Array.from, putIndex, index, result);
470
+ if (phase === DECODERS && isPending(context, result)) {
471
+ pending = queued(pending, index, result);
472
+ }
473
+ }
379
474
  index += 1;
380
475
  }
381
- return leave(state, set ? toSet : undefined);
476
+ if (nested) context.path.pop();
477
+ return settled(value, out, pending, putIndex, set ? toSet : undefined);
382
478
  };
383
479
 
384
- const walkList = (info, node, value, context, key, phase, want) =>
385
- walkItems(info.children, info.infos, info.shape === TUPLE, value, context, key, phase, want);
480
+ const walkList = (info, node, value, context, key, phase, want) => {
481
+ const input = convert(want, value, node, info);
482
+ if (input == null) return input;
483
+ return walkItems(
484
+ info.children,
485
+ info.infos,
486
+ info.shape === TUPLE,
487
+ input,
488
+ context,
489
+ key,
490
+ phase,
491
+ want,
492
+ );
493
+ };
386
494
 
387
495
  // The values of an object or a Map, by key.
388
- const walkKeyed = (info, node, value, context, key, phase, want) => {
389
- const map = value.constructor?.name === 'Map';
496
+ const walkKeyed = (info, node, given, context, key, phase, want) => {
497
+ const value = convert(want, given, node, info);
498
+ if (value == null) return value;
499
+ const map = isMap(value);
390
500
  if (!map && (typeof value !== 'object' || Array.isArray(value))) return value;
391
501
  const child = info.children[0];
392
502
  const sub = info.infos[0];
393
- const state = enter(context, key, value, map ? toMap : copy, map ? putEntry : putKey);
503
+ const clone = map ? toMap : copy;
504
+ const put = map ? putEntry : putKey;
505
+ const nested = key !== undefined;
506
+ if (nested) context.path.push(key);
507
+ let out = null;
508
+ let pending = null;
394
509
  if (map) {
395
510
  for (const pair of value) {
396
511
  const name = pair[0];
397
512
  const item = pair[1];
398
513
  const result = apply(sub, child, item, context, name, phase, want);
399
- if (result !== item) take(state, name, result, phase);
514
+ if (result !== item) {
515
+ out = written(out, value, clone, put, name, result);
516
+ if (phase === DECODERS && isPending(context, result)) {
517
+ pending = queued(pending, name, result);
518
+ }
519
+ }
400
520
  }
401
521
  } else {
402
522
  // The own keys of the object, in order, as the check iterates them.
@@ -404,10 +524,16 @@ const walkKeyed = (info, node, value, context, key, phase, want) => {
404
524
  if (!Object.hasOwn(value, name)) continue;
405
525
  const item = value[name];
406
526
  const result = apply(sub, child, item, context, name, phase, want);
407
- if (result !== item) take(state, name, result, phase);
527
+ if (result !== item) {
528
+ out = written(out, value, clone, put, name, result);
529
+ if (phase === DECODERS && isPending(context, result)) {
530
+ pending = queued(pending, name, result);
531
+ }
532
+ }
408
533
  }
409
534
  }
410
- return leave(state);
535
+ if (nested) context.path.pop();
536
+ return settled(value, out, pending, put, undefined);
411
537
  };
412
538
 
413
539
  // The context for trying the branches of a plain union, one per parse, made
@@ -434,19 +560,17 @@ const accepts = (branch, value, scratch, path, key) => {
434
560
  scratch.issues = NONE;
435
561
  scratch.count = 0;
436
562
  scratch.path = path;
437
- const list = scratch.async;
438
- list.length = 0;
439
563
  branch.check(value, scratch, key);
440
- for (let index = 0; index < list.length; index += 1) {
441
- if (list[index].promise !== null) abandon(list[index].promise);
442
- }
564
+ release(scratch.async, 0);
443
565
  return scratch.count === 0;
444
566
  };
445
567
 
446
568
  // The branch of a union a value belongs to: by the discriminator, or the
447
569
  // first branch whose check records nothing, as the check picks it. Before
448
570
  // the check a branch is tried with its own defaults in place, and the value
449
- // with those defaults is what parse goes on with.
571
+ // with those defaults is what parse goes on with. Under coercion a value
572
+ // some branch accepts as given is not converted: the branches are tried as
573
+ // given first, then converted.
450
574
  const walkUnion = (info, node, value, context, key, phase, want) => {
451
575
  const { children, infos, table } = info;
452
576
  if (table !== null) {
@@ -455,14 +579,43 @@ const walkUnion = (info, node, value, context, key, phase, want) => {
455
579
  if (index === undefined) return value;
456
580
  return apply(infos[index], children[index], value, context, key, phase, want);
457
581
  }
582
+ if (phase !== DEFAULTS) {
583
+ const scratch = scratchOf(context);
584
+ for (let index = 0; index < children.length; index += 1) {
585
+ if (!accepts(children[index], value, scratch, context.path, key)) continue;
586
+ return apply(infos[index], children[index], value, context, key, phase, want);
587
+ }
588
+ return value;
589
+ }
590
+ // Before the check, every branch is prepared first, with all the pass
591
+ // wants: when none of them changes the value (no default to fill, nothing
592
+ // to convert below) there is nothing to pick between, and the check picks
593
+ // the branch. The trial is a check of the subtree, so over a union of
594
+ // records that nest unions this is the difference between a linear and an
595
+ // exponential parse. What was prepared is what the last round picks from.
596
+ const prepared = [];
597
+ let same = true;
598
+ for (let index = 0; index < children.length; index += 1) {
599
+ const out = apply(infos[index], children[index], value, context, key, phase, want);
600
+ prepared.push(out);
601
+ if (out !== value) same = false;
602
+ }
603
+ if (same) return value;
458
604
  const scratch = scratchOf(context);
605
+ if ((want & COERCE) !== 0) {
606
+ // As given first (with the defaults): a branch that accepts the value as
607
+ // it is wins, and nothing is converted.
608
+ const given = want & ~COERCE;
609
+ for (let index = 0; index < children.length; index += 1) {
610
+ const branch = children[index];
611
+ const out = apply(infos[index], branch, value, context, key, phase, given);
612
+ if (accepts(branch, out, scratch, context.path, key)) return out;
613
+ }
614
+ }
459
615
  for (let index = 0; index < children.length; index += 1) {
460
- const branch = children[index];
461
- const sub = infos[index];
462
- const prepared =
463
- phase === DEFAULTS ? apply(sub, branch, value, context, key, phase, want) : value;
464
- if (!accepts(branch, prepared, scratch, context.path, key)) continue;
465
- return phase === DEFAULTS ? prepared : apply(sub, branch, value, context, key, phase, want);
616
+ if (accepts(children[index], prepared[index], scratch, context.path, key)) {
617
+ return prepared[index];
618
+ }
466
619
  }
467
620
  return value;
468
621
  };
@@ -492,6 +645,14 @@ const walkReference = (info, node, value, context, key, phase, want) => {
492
645
  return out;
493
646
  };
494
647
 
648
+ // A field's own `coerce` turns coercion on or off for its subtree, in the
649
+ // pass before the check.
650
+ const walkPolicy = (info, node, value, context, key, phase, want) => {
651
+ let mode = want;
652
+ if (phase === DEFAULTS) mode = info.coerce ? want | COERCE : want & ~COERCE;
653
+ return WALKERS[info.shape](info, node, value, context, key, phase, mode);
654
+ };
655
+
495
656
  const WALKERS = [
496
657
  walkLeaf,
497
658
  walkSchema,
@@ -506,7 +667,8 @@ const WALKERS = [
506
667
 
507
668
  // The bits a pass wants of a subtree, decided once per pass: its own, and
508
669
  // for the pass after the check the structs (under `strip`) and the fields
509
- // with aliases (after a check that read one).
670
+ // with aliases (after a check that read one); a parse that coerces adds
671
+ // COERCE to the pass before it.
510
672
  const wantOf = (phase, context) => {
511
673
  let want = phase;
512
674
  if (phase === DECODERS) {
@@ -518,8 +680,9 @@ const wantOf = (phase, context) => {
518
680
 
519
681
  // One pass over a value from a node whose info is known, by the shape of
520
682
  // each node. A serializer runs before the parts of its value, a decoder
521
- // after them; a subtree without the bits the pass wants is returned as it
522
- // is, which is the one test a value nothing applies to costs.
683
+ // after them, a conversion before them (in the walkers); a subtree without
684
+ // the bits the pass wants is returned as it is, which is the one test a
685
+ // value nothing applies to costs.
523
686
  const apply = (info, node, value, context, key, phase, want) => {
524
687
  if (value == null) return value;
525
688
  if ((info.bits & want) === 0) return value;
@@ -528,7 +691,7 @@ const apply = (info, node, value, context, key, phase, want) => {
528
691
  input = info.encode.call(node, value);
529
692
  if (input == null) return input;
530
693
  }
531
- const out = WALKERS[info.shape](info, node, input, context, key, phase, want);
694
+ const out = info.walk(info, node, input, context, key, phase, want);
532
695
  return phase === DECODERS ? decode(info, node, out, context, key) : out;
533
696
  };
534
697
 
@@ -536,6 +699,8 @@ module.exports = {
536
699
  PREPARE: DEFAULTS,
537
700
  FINISH: DECODERS,
538
701
  SERIALIZE: ENCODERS,
702
+ COERCE,
703
+ COERCION,
539
704
  infoOf,
540
705
  apply,
541
706
  wantOf,