@alexify/metaschema 3.2.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.
package/src/codec.js CHANGED
@@ -1,7 +1,8 @@
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
@@ -20,7 +21,7 @@ const {
20
21
  } = require('./issues.js');
21
22
  const { createContext } = require('./context.js');
22
23
  const { STRUCT, isStruct, aliasOf } = require('./struct.js');
23
- const { asyncReturn } = require('./errors.js');
24
+ const { asyncReturn, notRegistered } = require('./errors.js');
24
25
  const collections = require('./prototypes/collections.js');
25
26
  const { schema: struct } = require('./prototypes/schema.js');
26
27
  const { tuple } = require('./prototypes/tuple.js');
@@ -36,6 +37,27 @@ const ASYNC = 16;
36
37
  // A field with aliases below: the pass after the check visits it only when
37
38
  // the check read a field from an alias (`context.renamed`).
38
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
+ };
39
61
 
40
62
  // The shape of a node: a Schema, a struct (the dictionary of its fields), or
41
63
  // a field by the identity of its prototype's compile, as the JIT tells them
@@ -71,7 +93,9 @@ const isAsyncFunction = (fn) => typeof fn === 'function' && fn.constructor.name
71
93
 
72
94
  // What the passes know about a node, computed on first use and kept apart
73
95
  // from the node: its shape, the bits of its subtree, its own decoder and
74
- // 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
75
99
  // has to visit (`parts`, by phase bit; every field under `strip`), and the
76
100
  // reference fields beneath it (their targets are resolved at parse time, so a
77
101
  // reference counts as carrying everything).
@@ -85,8 +109,14 @@ const infoOf = (node) => {
85
109
  const own = shape === SCHEMA ? node.options : shape === FIELDS ? EMPTY : node;
86
110
  const decode = own.parse || undefined;
87
111
  const encode = own.serialize || undefined;
88
- 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;
89
118
  if (encode !== undefined) bits |= ENCODERS;
119
+ if (coerce === true) bits |= DEFAULTS | POLICY;
90
120
  if (isAsyncFunction(own.validate) || isAsyncFunction(decode) || isAsyncFunction(own.checkType)) {
91
121
  bits |= ASYNC;
92
122
  }
@@ -146,7 +176,26 @@ const infoOf = (node) => {
146
176
  parts[STRUCTS].push(index);
147
177
  }
148
178
  }
149
- 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
+ };
150
199
  INFO.set(node, info);
151
200
  return info;
152
201
  };
@@ -274,7 +323,22 @@ const decode = (info, node, value, context, key) => {
274
323
  });
275
324
  };
276
325
 
277
- 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);
278
342
 
279
343
  const walkInner = (info, node, value, context, key, phase, want) =>
280
344
  apply(info.infos[0], info.children[0], value, context, key, phase, want);
@@ -290,6 +354,11 @@ const LOOP = Symbol('loop');
290
354
  const looped = (context) => context.seen !== null && context.seen.has(LOOP);
291
355
 
292
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
+ }
293
362
  if (phase === DECODERS || info.refs.length === 0 || typeof value !== 'object') {
294
363
  return walkInner(info, node, value, context, key, phase, want);
295
364
  }
@@ -318,8 +387,9 @@ const renameKeys = (out, renames) => {
318
387
  return result;
319
388
  };
320
389
 
321
- // The fields of a struct: a default fills a missing key before the check, a
322
- // 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
323
393
  // the known keys; otherwise the object is copied when a field changed. A
324
394
  // value under an alias of a field is read from there (no default fills the
325
395
  // field, and the check sees it there), and the pass after the check writes
@@ -329,7 +399,8 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
329
399
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
330
400
  const { plan, infos, extra } = info;
331
401
  const strip = (want & STRUCTS) !== 0;
332
- const parts = info.parts[strip ? STRUCTS : phase];
402
+ // Every field under strip, and under coercion: any of them may convert.
403
+ const parts = info.parts[(want & (STRUCTS | COERCE)) !== 0 ? STRUCTS : phase];
333
404
  const nested = key !== undefined;
334
405
  if (nested) context.path.push(key);
335
406
  let out = strip ? {} : null;
@@ -346,14 +417,17 @@ const walkFields = (info, fields, value, context, key, phase, want) => {
346
417
  if (from !== name) item = value[from];
347
418
  }
348
419
  if (phase === DEFAULTS) {
349
- if (item === undefined) {
350
- const fallback = entry.type.default;
351
- if (fallback === undefined) continue;
352
- item = typeof fallback === 'function' ? fallback() : fallback;
353
- out = written(out, value, copy, putKey, from, item);
420
+ let result = item;
421
+ if (item !== undefined) {
422
+ result = apply(infos[index], entry.type, item, context, from, phase, want);
354
423
  }
355
- const result = apply(infos[index], entry.type, item, context, from, phase, want);
356
- if (result !== item) out = written(out, value, copy, putKey, from, result);
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);
357
431
  continue;
358
432
  }
359
433
  const result = apply(infos[index], entry.type, item, context, from, phase, want);
@@ -403,11 +477,25 @@ const walkItems = (children, infos, fixed, value, context, key, phase, want) =>
403
477
  return settled(value, out, pending, putIndex, set ? toSet : undefined);
404
478
  };
405
479
 
406
- const walkList = (info, node, value, context, key, phase, want) =>
407
- 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
+ };
408
494
 
409
495
  // The values of an object or a Map, by key.
410
- const walkKeyed = (info, node, value, context, key, phase, want) => {
496
+ const walkKeyed = (info, node, given, context, key, phase, want) => {
497
+ const value = convert(want, given, node, info);
498
+ if (value == null) return value;
411
499
  const map = isMap(value);
412
500
  if (!map && (typeof value !== 'object' || Array.isArray(value))) return value;
413
501
  const child = info.children[0];
@@ -480,7 +568,9 @@ const accepts = (branch, value, scratch, path, key) => {
480
568
  // The branch of a union a value belongs to: by the discriminator, or the
481
569
  // first branch whose check records nothing, as the check picks it. Before
482
570
  // the check a branch is tried with its own defaults in place, and the value
483
- // 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.
484
574
  const walkUnion = (info, node, value, context, key, phase, want) => {
485
575
  const { children, infos, table } = info;
486
576
  if (table !== null) {
@@ -489,14 +579,43 @@ const walkUnion = (info, node, value, context, key, phase, want) => {
489
579
  if (index === undefined) return value;
490
580
  return apply(infos[index], children[index], value, context, key, phase, want);
491
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;
492
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
+ }
493
615
  for (let index = 0; index < children.length; index += 1) {
494
- const branch = children[index];
495
- const sub = infos[index];
496
- const prepared =
497
- phase === DEFAULTS ? apply(sub, branch, value, context, key, phase, want) : value;
498
- if (!accepts(branch, prepared, scratch, context.path, key)) continue;
499
- 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
+ }
500
619
  }
501
620
  return value;
502
621
  };
@@ -526,6 +645,14 @@ const walkReference = (info, node, value, context, key, phase, want) => {
526
645
  return out;
527
646
  };
528
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
+
529
656
  const WALKERS = [
530
657
  walkLeaf,
531
658
  walkSchema,
@@ -540,7 +667,8 @@ const WALKERS = [
540
667
 
541
668
  // The bits a pass wants of a subtree, decided once per pass: its own, and
542
669
  // for the pass after the check the structs (under `strip`) and the fields
543
- // 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.
544
672
  const wantOf = (phase, context) => {
545
673
  let want = phase;
546
674
  if (phase === DECODERS) {
@@ -552,8 +680,9 @@ const wantOf = (phase, context) => {
552
680
 
553
681
  // One pass over a value from a node whose info is known, by the shape of
554
682
  // each node. A serializer runs before the parts of its value, a decoder
555
- // after them; a subtree without the bits the pass wants is returned as it
556
- // 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.
557
686
  const apply = (info, node, value, context, key, phase, want) => {
558
687
  if (value == null) return value;
559
688
  if ((info.bits & want) === 0) return value;
@@ -562,7 +691,7 @@ const apply = (info, node, value, context, key, phase, want) => {
562
691
  input = info.encode.call(node, value);
563
692
  if (input == null) return input;
564
693
  }
565
- const out = WALKERS[info.shape](info, node, input, context, key, phase, want);
694
+ const out = info.walk(info, node, input, context, key, phase, want);
566
695
  return phase === DECODERS ? decode(info, node, out, context, key) : out;
567
696
  };
568
697
 
@@ -570,6 +699,8 @@ module.exports = {
570
699
  PREPARE: DEFAULTS,
571
700
  FINISH: DECODERS,
572
701
  SERIALIZE: ENCODERS,
702
+ COERCE,
703
+ COERCION,
573
704
  infoOf,
574
705
  apply,
575
706
  wantOf,
@@ -0,0 +1,34 @@
1
+ import type { CoerceOptions, Coercion, FieldType, Schema } from '../../index.js';
2
+
3
+ // A converter: the value of a field of its type read from what the input
4
+ // gave, or the value itself when it cannot be read (the check then reports
5
+ // it as given). It never throws on purpose: a throw is taken as "cannot".
6
+ // Declared with the core (`ModelOptions.coercions` takes them too).
7
+ export type { Coercion };
8
+
9
+ // The converters by type name: the built-in ones (`string`, `number`,
10
+ // `integer`, `bigint`, `boolean`, `date`, `enum`, `array`, `set`, `map`) and
11
+ // the program's own, once `register()` ran.
12
+ export const COERCIONS: { readonly [name: string]: Coercion | undefined };
13
+
14
+ // The value with the conversions of the schema applied, and its defaults:
15
+ // the pass parse runs before its check with coercion on, nothing checked.
16
+ // The value given is never written to, and comes back itself when nothing
17
+ // changed. Needs `register()`: without it a conversion is a TypeError with
18
+ // `code: 'ERR_NOT_REGISTERED'`.
19
+ export function coerce(schema: Schema, value: unknown, options?: CoerceOptions): unknown;
20
+
21
+ // The options of `register`: `onError` is told of a converter that threw
22
+ // (the value is left to the check as if the converter could not read it, so
23
+ // a bug in a converter of the program would look the same without it).
24
+ export interface RegisterOptions {
25
+ onError?: (error: unknown, field: FieldType) => void;
26
+ }
27
+
28
+ // Fills the table with the built-in converters and the program's own, by
29
+ // type name, once per name and process-wide (another function under a
30
+ // registered name is `ERR_COERCION_REGISTERED`, a name that is not one of a
31
+ // type or an entry that is not a function `ERR_INVALID_COERCION`; every
32
+ // entry is checked before any is written), and adds
33
+ // `schema.coerce(value, options)`. Importing the subpath registers nothing.
34
+ export function register(custom?: Record<string, Coercion>, options?: RegisterOptions): void;