@alexify/metaschema 3.4.1 → 4.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 (66) hide show
  1. package/CHANGELOG.md +162 -1
  2. package/README.md +22 -7
  3. package/SECURITY.md +5 -4
  4. package/index.d.ts +856 -460
  5. package/package.json +8 -6
  6. package/src/checks.js +72 -107
  7. package/src/codec.js +67 -58
  8. package/src/coerce/index.d.ts +31 -21
  9. package/src/coerce/index.js +64 -47
  10. package/src/compile/code.js +2 -2
  11. package/src/compile/emit.js +20 -31
  12. package/src/compile/index.d.ts +41 -25
  13. package/src/compile/index.js +45 -32
  14. package/src/context.js +10 -10
  15. package/src/definition/index.d.ts +10 -7
  16. package/src/definition/index.js +2 -1
  17. package/src/derive/index.d.ts +25 -17
  18. package/src/derive/index.js +14 -11
  19. package/src/errors.js +84 -59
  20. package/src/formats/index.d.ts +27 -21
  21. package/src/formats/index.js +15 -13
  22. package/src/generators/{fromjsonschema.js → from-json-schema.js} +170 -127
  23. package/src/generators/index.d.ts +23 -15
  24. package/src/generators/index.js +2 -2
  25. package/src/generators/{jsonschema.js → json-schema.js} +37 -43
  26. package/src/generators/typescript.js +9 -6
  27. package/src/index.js +2 -1
  28. package/src/issues.js +41 -42
  29. package/src/kinds.js +18 -16
  30. package/src/lint.js +15 -18
  31. package/src/locales/en.js +7 -7
  32. package/src/locales/uk.js +6 -6
  33. package/src/metadata.js +2 -2
  34. package/src/model/data.js +17 -20
  35. package/src/model/diff.js +29 -24
  36. package/src/model/index.d.ts +51 -35
  37. package/src/model/infer.js +69 -60
  38. package/src/model/merge.js +29 -18
  39. package/src/model/pattern.js +105 -102
  40. package/src/model/restore.js +24 -19
  41. package/src/model/sample.js +90 -100
  42. package/src/model.js +4 -2
  43. package/src/mongodb/bson.js +12 -12
  44. package/src/mongodb/document.js +7 -6
  45. package/src/mongodb/index.d.ts +54 -31
  46. package/src/mongodb/update.js +12 -9
  47. package/src/preprocessor.js +13 -13
  48. package/src/prototypes/abstract.js +8 -8
  49. package/src/prototypes/collections.js +7 -7
  50. package/src/prototypes/flags.js +1 -1
  51. package/src/prototypes/reference.js +3 -4
  52. package/src/prototypes/scalars.js +1 -1
  53. package/src/prototypes/schema.js +5 -6
  54. package/src/prototypes/tuple.js +6 -5
  55. package/src/prototypes/union.js +5 -4
  56. package/src/rules.js +23 -20
  57. package/src/runtime/browser.js +6 -1
  58. package/src/runtime/node.js +19 -2
  59. package/src/schema.js +15 -13
  60. package/src/snapshot.js +14 -12
  61. package/src/stream/index.d.ts +33 -21
  62. package/src/stream/index.js +37 -20
  63. package/src/struct.js +6 -6
  64. package/src/types.js +28 -22
  65. package/src/util.js +65 -64
  66. package/src/validation.js +10 -13
@@ -7,7 +7,7 @@
7
7
  // (witness generation as a satisfiability check).
8
8
  const { hasBrand, define } = require('../util.js');
9
9
  const { createContext } = require('../context.js');
10
- const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
10
+ const { SchemaDefinitionError, SchemaUsageError, invalidTarget } = require('../errors.js');
11
11
  const { isStruct } = require('../struct.js');
12
12
  const { baseTypeOf } = require('../types.js');
13
13
  const { embeds } = require('../prototypes/reference.js');
@@ -16,26 +16,12 @@ const en = require('../locales/en.js');
16
16
  const { int, pick, patternOf, fromPattern } = require('./pattern.js');
17
17
  const { FORMATS } = require('../rules.js');
18
18
 
19
- const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
20
-
21
- const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
22
-
23
- // mulberry32: a 32-bit generator, the same numbers for a seed everywhere.
24
- const prng = (seed) => {
25
- let state = seed | 0;
26
- return () => {
27
- state = (state + 0x6d2b79f5) | 0;
28
- let t = Math.imul(state ^ (state >>> 15), 1 | state);
29
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
30
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
31
- };
32
- };
33
-
34
19
  // The letters of a free string, by locale.
35
- const LETTERS = Object.assign(Object.create(null), {
20
+ const LETTERS = {
21
+ __proto__: null,
36
22
  en: 'abcdefghijklmnopqrstuvwxyz',
37
23
  uk: 'абвгґдеєжзиіїйклмнопрстуфхцчшщьюя',
38
- });
24
+ };
39
25
 
40
26
  // How many draws a field gets before it is given up on, and how many an
41
27
  // optional field is present in, out of four.
@@ -46,6 +32,33 @@ const PRESENT = 3;
46
32
  // reference nested too deep.
47
33
  const ABSENT = Symbol('absent');
48
34
 
35
+ // The widest span a bigint is drawn from: what a number holds exactly.
36
+ const SPAN = 2n ** 53n;
37
+
38
+ // The errors of a branch that another branch may not have: a union tries
39
+ // every branch from a random one on and fails with the last error only when
40
+ // every branch failed.
41
+ const RETRIED = new Set(['ALX_ERR_UNSATISFIABLE', 'ALX_ERR_SAMPLE_PATTERN', 'ALX_ERR_SAMPLE_TYPE']);
42
+
43
+ // How a reference may be held, as in check, and how deep embedded records
44
+ // may nest: a `many` reference fans out by up to four records a level.
45
+ const REFERENCES = new Set(['kind', 'embed', 'id']);
46
+ const MAX_DEPTH = 32;
47
+
48
+ // An option of the call that is not what it must be: the call is wrong.
49
+ const wrongOption = (reason) => new SchemaUsageError(reason, { code: 'ALX_ERR_INVALID_OPTION' });
50
+
51
+ // mulberry32: a 32-bit generator, the same numbers for a seed everywhere.
52
+ const prng = (seed) => {
53
+ let state = seed | 0;
54
+ return () => {
55
+ state = (state + 0x6d2b79f5) | 0;
56
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
57
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
58
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
59
+ };
60
+ };
61
+
49
62
  // The built-in type a field validates as: its own, or the one its alias
50
63
  // chain ends in; a custom type with a check of its own has none.
51
64
  const baseOf = (field) => {
@@ -89,6 +102,13 @@ const stringOf = (state, field, key) => {
89
102
 
90
103
  const asNumber = (value) => (typeof value === 'bigint' ? Number(value) : value);
91
104
 
105
+ // The units of one in the last decimal a number is drawn to: 1 for a whole
106
+ // number, 10ⁿ for n decimals, 0 when any number will do.
107
+ const scaleOf = (field, whole) => {
108
+ if (whole) return 1;
109
+ return field.decimals === undefined ? 0 : 10 ** field.decimals;
110
+ };
111
+
92
112
  // A number within the bounds; a whole one, or one of `decimals` decimals,
93
113
  // rounded toward the inside of the bounds.
94
114
  const numberOf = (state, field, whole) => {
@@ -97,7 +117,7 @@ const numberOf = (state, field, whole) => {
97
117
  const low = min ?? (max === undefined ? 0 : max - 100);
98
118
  const high = max ?? low + 100;
99
119
  const value = low + state.random() * (high - low);
100
- const scale = whole ? 1 : field.decimals === undefined ? 0 : 10 ** field.decimals;
120
+ const scale = scaleOf(field, whole);
101
121
  // Past 2⁵³ units of the last decimal every double is a whole number of
102
122
  // them (and the product may be no number at all): the value is one.
103
123
  if (scale === 0 || !(Math.abs(value * scale) < 2 ** 53)) return value;
@@ -105,16 +125,15 @@ const numberOf = (state, field, whole) => {
105
125
  return up > high ? Math.floor(value * scale) / scale : up;
106
126
  };
107
127
 
108
- // The widest span a bigint is drawn from: what a number holds exactly.
109
- const SPAN = 2n ** 53n;
128
+ // The lower bound of a bigint drawn: the minimum, else a hundred under the
129
+ // maximum, else zero.
130
+ const lowOf = (field) => {
131
+ if (field.min !== undefined) return BigInt(field.min);
132
+ return field.max === undefined ? 0n : BigInt(field.max) - 100n;
133
+ };
110
134
 
111
135
  const bigintOf = (state, field) => {
112
- const low =
113
- field.min === undefined
114
- ? field.max === undefined
115
- ? 0n
116
- : BigInt(field.max) - 100n
117
- : BigInt(field.min);
136
+ const low = lowOf(field);
118
137
  const high = field.max === undefined ? low + 100n : BigInt(field.max);
119
138
  const span = high - low > SPAN ? SPAN : high - low;
120
139
  return low + BigInt(int(state, Number(span)));
@@ -173,11 +192,6 @@ const tupleOf = (state, field) => {
173
192
  return list;
174
193
  };
175
194
 
176
- // The errors of a branch that another branch may not have: a union tries
177
- // every branch from a random one on and fails with the last error only when
178
- // every branch failed.
179
- const RETRIED = new Set(['ERR_UNSATISFIABLE', 'ERR_SAMPLE_PATTERN', 'ERR_SAMPLE_TYPE']);
180
-
181
195
  const unionOf = (state, field, key) => {
182
196
  const branches = field.union;
183
197
  const start = int(state, branches.length - 1);
@@ -242,10 +256,8 @@ const customOf = (state, field, key) => {
242
256
  const { sample: given } = field.constructor.metadata;
243
257
  if (given === undefined) {
244
258
  const hint = `Type "${field.type}" needs metadata.sample to be sampled`;
245
- throw invalid(
246
- 'ERR_SAMPLE_TYPE',
247
- `${hint} in "${toDotPath(pathOf(state, key), state.root.name)}"`,
248
- );
259
+ const where = toDotPath(pathOf(state, key), state.root.name);
260
+ throw new SchemaDefinitionError(`${hint} in "${where}"`, { code: 'ALX_ERR_SAMPLE_TYPE' });
249
261
  }
250
262
  return typeof given === 'function' ? given(field, state.random) : given;
251
263
  };
@@ -257,12 +269,37 @@ const pathOf = (state, key) => (key === undefined ? state.path : state.path.conc
257
269
  const unsatisfiable = (state, key, reason) => {
258
270
  const where = toDotPath(pathOf(state, key), state.root.name);
259
271
  const { seed } = state;
260
- const error = invalid(
261
- 'ERR_UNSATISFIABLE',
262
- `No value satisfies "${where}" (seed ${seed}): ${reason}`,
263
- );
264
- error.seed = seed;
265
- return error;
272
+ const message = `No value satisfies "${where}" (seed ${seed}): ${reason}`;
273
+ return new SchemaDefinitionError(message, { code: 'ALX_ERR_UNSATISFIABLE', seed });
274
+ };
275
+
276
+ // A draw by the built-in type a field validates as; a type of the program's
277
+ // own draws through its prototype (`customOf`).
278
+ const DRAWERS = {
279
+ __proto__: null,
280
+ string: stringOf,
281
+ number: (state, field) => numberOf(state, field, false),
282
+ integer: (state, field) => numberOf(state, field, true),
283
+ bigint: bigintOf,
284
+ boolean: (state) => state.random() < 0.5,
285
+ date: (state) => new Date(1_600_000_000_000 + Math.floor(state.random() * 100_000_000_000)),
286
+ bytes: bytesOf,
287
+ flags: flagsOf,
288
+ null: () => null,
289
+ any: (state) => lettersOf(state, 4),
290
+ unknown: (state) => lettersOf(state, 4),
291
+ json: () => ({}),
292
+ enum: (state, field) => pick(state, field.enum),
293
+ array: listOf,
294
+ set: listOf,
295
+ object: keyedOf,
296
+ map: keyedOf,
297
+ tuple: tupleOf,
298
+ union: unionOf,
299
+ schema: (state, field, key) => drawValue(field.schema, state, key),
300
+ reference: referenceOf,
301
+ one: referenceOf,
302
+ many: referenceOf,
266
303
  };
267
304
 
268
305
  // One draw for a field, by the built-in type it validates as.
@@ -271,51 +308,11 @@ const draw = (state, field, key) => {
271
308
  if (Array.isArray(examples) && examples.length > 0 && state.random() < 0.5) {
272
309
  return pick(state, examples);
273
310
  }
274
- switch (baseOf(field)) {
275
- case 'string':
276
- return stringOf(state, field, key);
277
- case 'number':
278
- return numberOf(state, field, false);
279
- case 'integer':
280
- return numberOf(state, field, true);
281
- case 'bigint':
282
- return bigintOf(state, field);
283
- case 'boolean':
284
- return state.random() < 0.5;
285
- case 'date':
286
- return new Date(1_600_000_000_000 + Math.floor(state.random() * 100_000_000_000));
287
- case 'bytes':
288
- return bytesOf(state, field);
289
- case 'flags':
290
- return flagsOf(state, field);
291
- case 'null':
292
- return null;
293
- case 'any':
294
- case 'unknown':
295
- return lettersOf(state, 4);
296
- case 'json':
297
- return {};
298
- case 'enum':
299
- return pick(state, field.enum);
300
- case 'array':
301
- case 'set':
302
- return listOf(state, field, key);
303
- case 'object':
304
- case 'map':
305
- return keyedOf(state, field);
306
- case 'tuple':
307
- return tupleOf(state, field);
308
- case 'union':
309
- return unionOf(state, field, key);
310
- case 'schema':
311
- return drawValue(field.schema, state, key);
312
- case 'reference':
313
- case 'one':
314
- case 'many':
315
- return referenceOf(state, field, key);
316
- default:
317
- return customOf(state, field, key);
318
- }
311
+ // A type of the program's own has no base (null), which must not read as
312
+ // the key "null" of the table.
313
+ const base = baseOf(field);
314
+ const drawer = base === null ? customOf : (DRAWERS[base] ?? customOf);
315
+ return drawer(state, field, key);
319
316
  };
320
317
 
321
318
  // Whether a draw passes the field's own check (its type, its rules, its
@@ -364,29 +361,22 @@ const sampleField = (field, state, key) => {
364
361
  throw unsatisfiable(state, key, issue.message);
365
362
  };
366
363
 
367
- // How a reference may be held, as in check, and how deep embedded records
368
- // may nest: a `many` reference fans out by up to four records a level.
369
- const REFERENCES = ['kind', 'embed', 'id'];
370
- const MAX_DEPTH = 32;
371
-
372
364
  const optionsOf = (options) => {
373
365
  if (options === null || typeof options !== 'object') {
374
- throw invalidOptions('Sample options must be an object');
366
+ throw wrongOption('Sample options must be an object');
375
367
  }
376
368
  const { seed = 1, locale = 'en', references = 'kind', maxDepth = 3 } = options;
377
- if (!Number.isInteger(seed)) throw invalidOptions('Sample option "seed" must be an integer');
369
+ if (!Number.isInteger(seed)) throw wrongOption('Sample option "seed" must be an integer');
378
370
  if (LETTERS[locale] === undefined) {
379
- throw invalidOptions(
380
- `Sample option "locale" must be "en" or "uk", got ${JSON.stringify(locale)}`,
381
- );
371
+ throw wrongOption(`Sample option "locale" must be "en" or "uk", got ${JSON.stringify(locale)}`);
382
372
  }
383
- if (!REFERENCES.includes(references)) {
384
- throw invalidOptions(
373
+ if (!REFERENCES.has(references)) {
374
+ throw wrongOption(
385
375
  `Sample option "references" must be "kind", "embed" or "id", got ${JSON.stringify(references)}`,
386
376
  );
387
377
  }
388
378
  if (!Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH) {
389
- throw invalidOptions(`Sample option "maxDepth" must be an integer from 0 to ${MAX_DEPTH}`);
379
+ throw wrongOption(`Sample option "maxDepth" must be an integer from 0 to ${MAX_DEPTH}`);
390
380
  }
391
381
  return { seed, letters: LETTERS[locale], references, maxDepth };
392
382
  };
package/src/model.js CHANGED
@@ -3,12 +3,14 @@ const { firstKey, isFirstLower } = require('./metautil.js');
3
3
  const { BRAND, INSPECT, CYCLES } = require('./util.js');
4
4
  const { Schema } = require('./schema.js');
5
5
  const { TYPES, createRegistry, typeFactory } = require('./types.js');
6
- const { SchemaDefinitionError, noValidation } = require('./errors.js');
6
+ const { SchemaUsageError, noValidation } = require('./errors.js');
7
7
  const { snapshotOf, orderOf } = require('./snapshot.js');
8
8
 
9
+ // An option of the constructor that is not what it must be: the call is
10
+ // wrong, not a definition.
9
11
  const invalidOption = (name, expected, value) => {
10
12
  const reason = `Model option "${name}" must be ${expected}, got ${JSON.stringify(value)}`;
11
- return new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
13
+ return new SchemaUsageError(reason, { code: 'ALX_ERR_INVALID_OPTION' });
12
14
  };
13
15
 
14
16
  const registryFor = (options) => {
@@ -14,6 +14,16 @@ const { register: coercion } = require('../coerce/index.js');
14
14
  const TAG = '_bsontype';
15
15
  const ID = '_id';
16
16
 
17
+ const HEX = /^[0-9a-fA-F]{24}$/;
18
+
19
+ // A decimal written as one (`fromString` of the driver reads `NaN`, `inf`
20
+ // and an exponent too), or a finite number.
21
+ const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
22
+
23
+ // Text of the base64 shape only: the decoder of the driver reads anything,
24
+ // and the empty string is never converted.
25
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
26
+
17
27
  const tagOf = (value) => (value !== null && typeof value === 'object' ? value[TAG] : undefined);
18
28
 
19
29
  const isObjectId = (value) => {
@@ -49,8 +59,6 @@ const typeOf = (test, bson, jsonSchema) =>
49
59
  metadata: Object.freeze({ bson, jsonSchema }),
50
60
  });
51
61
 
52
- const HEX = /^[0-9a-fA-F]{24}$/;
53
-
54
62
  // The types to give a model: `new Model({ ...types, ...own }, entities)`.
55
63
  // They are not registered by register(): a type name is a shorthand key of
56
64
  // a definition, so a program says where it uses them.
@@ -75,23 +83,15 @@ const driverOf = () => {
75
83
  const toObjectId = (value) =>
76
84
  typeof value === 'string' && HEX.test(value) ? new driver.ObjectId(value) : value;
77
85
 
78
- // A decimal written as one (`fromString` of the driver reads `NaN`, `inf`
79
- // and an exponent too), or a finite number.
80
- const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
81
-
82
86
  const toDecimal128 = (value) => {
83
87
  if (typeof value === 'number') {
84
- return Number.isFinite(value) ? driver.Decimal128.fromString(String(value)) : value;
88
+ return Number.isFinite(value) ? driver.Decimal128.fromString(`${value}`) : value;
85
89
  }
86
90
  return typeof value === 'string' && DECIMAL.test(value)
87
91
  ? driver.Decimal128.fromString(value)
88
92
  : value;
89
93
  };
90
94
 
91
- // Text of the base64 shape only: the decoder of the driver reads anything,
92
- // and the empty string is never converted.
93
- const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
94
-
95
95
  const toBinary = (value) =>
96
96
  typeof value === 'string' && value.length % 4 === 0 && BASE64.test(value)
97
97
  ? driver.Binary.createFromBase64(value)
@@ -127,4 +127,4 @@ const idOf = (schema) => {
127
127
  return id === null || ID in schema.fields ? null : id;
128
128
  };
129
129
 
130
- module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId, binaryBytes };
130
+ module.exports = { ID, HEX, isObjectId, binaryBytes, types, driverOf, register, idOf };
@@ -75,7 +75,8 @@ const record = (state, owner, value) => {
75
75
  const id = hasBrand(owner, 'Schema') ? idOf(owner) : null;
76
76
  const { calculated } = fields[STRUCT];
77
77
  const out = {};
78
- if (state.out && id !== null && value[id] != null) out[ID] = idValue(state, value[id]);
78
+ const held = id !== null && value[id] !== undefined && value[id] !== null;
79
+ if (state.out && held) out[ID] = idValue(state, value[id]);
79
80
  for (const key of Object.keys(value)) {
80
81
  const item = value[key];
81
82
  if (state.out) {
@@ -113,7 +114,7 @@ const reference = (state, node, value) => {
113
114
  };
114
115
 
115
116
  const walk = (state, node, value) => {
116
- if (value == null) return value;
117
+ if (value === undefined || value === null) return value;
117
118
  const info = infoOf(node);
118
119
  const { shape } = info;
119
120
  if (shape === SCHEMA || shape === FIELDS) return record(state, node, value);
@@ -207,11 +208,11 @@ const fromDocumentAsync = async (target, document, options) => {
207
208
 
208
209
  module.exports = {
209
210
  SHAPES,
211
+ idValue,
212
+ listOf,
213
+ walk,
214
+ stateOf,
210
215
  toDocument,
211
216
  fromDocument,
212
217
  fromDocumentAsync,
213
- walk,
214
- idValue,
215
- stateOf,
216
- listOf,
217
218
  };
@@ -9,8 +9,10 @@ import type {
9
9
  ValidationResult,
10
10
  } from '../../index.js';
11
11
 
12
- // What the subpath reads of the values of bson (4 to 6) or of the driver,
13
- // which re-exports them; nothing is imported from either.
12
+ /**
13
+ * What the subpath reads of the values of bson (4 to 6) or of the driver,
14
+ * which re-exports them; nothing is imported from either.
15
+ */
14
16
  export interface ObjectIdLike {
15
17
  readonly _bsontype: 'ObjectId' | 'ObjectID';
16
18
  toHexString(): string;
@@ -24,64 +26,80 @@ export interface BinaryLike {
24
26
  toJSON(): unknown;
25
27
  }
26
28
 
27
- // The module of the driver (`require('mongodb')`) or of bson.
29
+ /** The module of the driver (`require('mongodb')`) or of bson. */
28
30
  export interface BSONModule {
29
31
  ObjectId: new (hex: string) => ObjectIdLike;
30
32
  Decimal128?: { fromString(text: string): Decimal128Like };
31
33
  Binary?: { createFromBase64(text: string): BinaryLike };
32
34
  }
33
35
 
34
- // The BSON types, to give a model: `new Model({ ...types, ...own }, entities)`.
35
- // A value is one by its `_bsontype` and a method, never by `instanceof`;
36
- // `binary` takes a Uint8Array too.
36
+ /**
37
+ * The BSON types, to give a model: `new Model({ ...types, ...own }, entities)`.
38
+ * A value is one by its `_bsontype` and a method, never by `instanceof`;
39
+ * `binary` takes a Uint8Array too.
40
+ */
37
41
  export const types: {
38
42
  readonly objectId: TypeEntry;
39
43
  readonly decimal128: TypeEntry;
40
44
  readonly binary: TypeEntry;
41
45
  };
42
46
 
43
- // Keeps the module of the driver for the functions below and teaches
44
- // `./coerce` the BSON types (a string of 24 hex digits is an ObjectId, a
45
- // decimal string a Decimal128, base64 text a Binary). Once: another module
46
- // after the first throws.
47
+ /**
48
+ * Keeps the module of the driver for the functions of the subpath and teaches
49
+ * `./coerce` the BSON types (a string of 24 hex digits is an ObjectId, a
50
+ * decimal string a Decimal128, base64 text a Binary). Once: another module
51
+ * after the first throws.
52
+ */
47
53
  export function register(options: { bson: BSONModule }): void;
48
54
 
55
+ /** How `toDocument`, `fromDocument` and `toUpdate` write ids and references. */
49
56
  export interface DocumentOptions {
50
- // The ids of stored records and references as ObjectIds (the default) or
51
- // as the strings the program keeps.
57
+ /**
58
+ * The ids of stored records and references as ObjectIds (the default) or
59
+ * as the strings the program keeps.
60
+ */
52
61
  ids?: 'objectId' | 'string';
53
- // Which references are records (and so documents with their own `_id`)
54
- // and which ids, as in `check`.
62
+ /**
63
+ * Which references are records (and so documents with their own `_id`)
64
+ * and which ids, as in `check`.
65
+ */
55
66
  references?: 'kind' | 'embed' | 'id';
56
- // How many embedded records deep the walk goes (128 by default, as in
57
- // `check`); a record deeper is left as it is for the check to report.
67
+ /**
68
+ * How many embedded records deep the walk goes (128 by default, as in
69
+ * `check`); a record deeper is left as it is for the check to report.
70
+ */
58
71
  maxDepth?: number;
59
72
  }
60
73
 
61
- // The document of a value: its serializers run, the id field of a stored
62
- // record moved to `_id` (left out when there is none, so that the database
63
- // gives one), ids made ObjectIds, undefined values and calculated fields left
64
- // out. Needs `register()`: `ERR_NOT_REGISTERED` otherwise.
74
+ /**
75
+ * The document of a value: its serializers run, the id field of a stored
76
+ * record moved to `_id` (left out when there is none, so that the database
77
+ * gives one), ids made ObjectIds, undefined values and calculated fields left
78
+ * out. Needs `register()`: `ALX_ERR_NOT_REGISTERED` otherwise.
79
+ */
65
80
  export function toDocument(
66
81
  target: Schema,
67
82
  value: unknown,
68
83
  options?: DocumentOptions,
69
84
  ): Record<string, unknown>;
70
85
 
71
- // The value of a document: `_id` back to the id field, ObjectIds to their hex
72
- // strings, then `parse` with `coerce: true` unless the options say otherwise.
86
+ /**
87
+ * The value of a document: `_id` back to the id field, ObjectIds to their hex
88
+ * strings, then `parse` with `coerce: true` unless the options say otherwise.
89
+ */
73
90
  export function fromDocument<D extends string | object>(
74
91
  target: Schema<D>,
75
92
  document: unknown,
76
93
  options?: ParseOptions & Pick<DocumentOptions, 'references'>,
77
94
  ): ParseResult<InferOutput<D>>;
95
+ /** `fromDocument` with `parseAsync`, for a schema with async validators or decoders. */
78
96
  export function fromDocumentAsync<D extends string | object>(
79
97
  target: Schema<D>,
80
98
  document: unknown,
81
99
  options?: ParseOptions & Pick<DocumentOptions, 'references'>,
82
100
  ): Promise<ParseResult<InferOutput<D>>>;
83
101
 
84
- // An index as `createIndexes` takes it.
102
+ /** An index as `createIndexes` takes it. */
85
103
  export interface IndexDescription {
86
104
  key: Record<string, 1>;
87
105
  name?: string;
@@ -89,11 +107,11 @@ export interface IndexDescription {
89
107
  sparse?: true;
90
108
  }
91
109
 
92
- // The indexes of a schema, or of every stored entity of a model by name.
110
+ /** The indexes of a schema, or of every stored entity of a model by name. */
93
111
  export function indexesOf(target: Schema): IndexDescription[];
94
112
  export function indexesOf(target: Model): Record<string, IndexDescription[]>;
95
113
 
96
- // An update of the driver: operators and the dotted paths they act on.
114
+ /** An update of the driver: operators and the dotted paths they act on. */
97
115
  export type UpdateOperator =
98
116
  | '$set'
99
117
  | '$setOnInsert'
@@ -108,22 +126,27 @@ export type UpdateOperator =
108
126
  | '$pull'
109
127
  | '$pullAll'
110
128
  | '$pop';
129
+ /** An update document: each operator with the dotted paths it acts on. */
111
130
  export type Update = { [O in UpdateOperator]?: Record<string, unknown> };
112
131
 
113
- // The issues of an update against the schema: the field each path names,
114
- // the value each operator sets, pushes or adds to it. The id of a stored
115
- // record is set by `$setOnInsert` only.
132
+ /**
133
+ * The issues of an update against the schema: the field each path names,
134
+ * the value each operator sets, pushes or adds to it. The id of a stored
135
+ * record is set by `$setOnInsert` only.
136
+ */
116
137
  export function checkUpdate(
117
138
  target: Schema,
118
139
  update: Update,
119
140
  options?: CheckOptions,
120
141
  ): ValidationResult;
121
142
 
122
- // The update as the database takes it: the values serialized, their ids made
123
- // ObjectIds, the id of the record as `_id`. Check it with `checkUpdate` first.
143
+ /**
144
+ * The update as the database takes it: the values serialized, their ids made
145
+ * ObjectIds, the id of the record as `_id`. Check it with `checkUpdate` first.
146
+ */
124
147
  export function toUpdate(target: Schema, update: Update, options?: DocumentOptions): Update;
125
148
 
126
- // `Infer` learns the BSON types once this file is loaded.
149
+ /** `Infer` learns the BSON types once this file is loaded. */
127
150
  declare module '../../index.js' {
128
151
  interface CustomTypes {
129
152
  objectId: ObjectIdLike;
@@ -21,6 +21,7 @@ const { NESTED, LIST, KEYED, TUPLE, REFERENCE } = SHAPES;
21
21
 
22
22
  // A place an update is not checked at: a union, any, json.
23
23
  const LOOSE = Symbol('loose');
24
+ const LOOSE_TYPES = new Set(['union', 'any', 'unknown', 'json']);
24
25
  // An element of a list of ids: a string.
25
26
  const ID = Symbol('id');
26
27
  // A part a node does not have (an element of a string, a field of an id):
@@ -35,9 +36,12 @@ const INDEX = /^\d+$/;
35
36
 
36
37
  // The operators of the values a path is set to, of the lists it adds to or
37
38
  // takes from, and every operator of an update the subpath reads.
38
- const VALUES = ['$set', '$setOnInsert', '$min', '$max'];
39
- const LISTS = ['$push', '$addToSet', '$pull', '$pullAll'];
40
- const OPERATORS = [...VALUES, ...LISTS, '$unset', '$inc', '$mul', '$currentDate', '$pop'];
39
+ const VALUE_NAMES = ['$set', '$setOnInsert', '$min', '$max'];
40
+ const LIST_NAMES = ['$push', '$addToSet', '$pull', '$pullAll'];
41
+ const OTHER_NAMES = ['$unset', '$inc', '$mul', '$currentDate', '$pop'];
42
+ const VALUES = new Set(VALUE_NAMES);
43
+ const LISTS = new Set(LIST_NAMES);
44
+ const OPERATORS = new Set(OTHER_NAMES.concat(VALUE_NAMES, LIST_NAMES));
41
45
 
42
46
  // The type a field is of, through the aliases of custom types.
43
47
  const baseOf = (field) => baseTypeOf(field).type;
@@ -70,8 +74,7 @@ const step = (node, segment, references) => {
70
74
  if (!ELEMENT.test(segment)) return NONE;
71
75
  return target === null ? ID : target;
72
76
  }
73
- const base = baseOf(node);
74
- return base === 'union' || base === 'any' || base === 'unknown' || base === 'json' ? LOOSE : NONE;
77
+ return LOOSE_TYPES.has(baseOf(node)) ? LOOSE : NONE;
75
78
  };
76
79
 
77
80
  // The node a path names, or null, NONE, LOOSE or DEEP: the records a path
@@ -129,7 +132,7 @@ const checkStep = (node, value, context, key) => {
129
132
  };
130
133
 
131
134
  const checkOperation = (operator, node, value, context, key) => {
132
- if (VALUES.includes(operator)) checkAt(node, value, context, key);
135
+ if (VALUES.has(operator)) checkAt(node, value, context, key);
133
136
  else if (operator === '$unset') {
134
137
  if (hasBrand(node, 'Type') && node.required) issues.required(context, key);
135
138
  } else if (operator === '$inc' || operator === '$mul') checkStep(node, value, context, key);
@@ -186,7 +189,7 @@ const checkUpdate = (target, update, options) => {
186
189
  const unknown = [];
187
190
  for (const operator of Object.keys(update)) {
188
191
  const operand = update[operator];
189
- if (!OPERATORS.includes(operator) || !isObject(operand)) {
192
+ if (!OPERATORS.has(operator) || !isObject(operand)) {
190
193
  unknown.push(operator);
191
194
  continue;
192
195
  }
@@ -209,8 +212,8 @@ const valueOf = (state, context, node, value) => {
209
212
  };
210
213
 
211
214
  const operandOf = (state, context, operator, node, value) => {
212
- if (VALUES.includes(operator)) return valueOf(state, context, node, value);
213
- if (!LISTS.includes(operator)) return value;
215
+ if (VALUES.has(operator)) return valueOf(state, context, node, value);
216
+ if (!LISTS.has(operator)) return value;
214
217
  const element = elementOf(node, state.references);
215
218
  if (element === null) return value;
216
219
  const each = (item) => valueOf(state, context, element, item);