@alexify/metaschema 3.4.0 → 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 +227 -1
  2. package/README.md +29 -11
  3. package/SECURITY.md +5 -4
  4. package/index.d.ts +912 -480
  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 +21 -15
  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 +31 -10
  30. package/src/lint.js +64 -19
  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 +34 -20
  35. package/src/model/diff.js +29 -24
  36. package/src/model/index.d.ts +51 -35
  37. package/src/model/infer.js +70 -61
  38. package/src/model/merge.js +29 -18
  39. package/src/model/pattern.js +105 -102
  40. package/src/model/restore.js +33 -21
  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 +25 -15
  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 +11 -10
  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 +19 -14
  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 +35 -26
  65. package/src/util.js +70 -64
  66. package/src/validation.js +10 -13
@@ -7,26 +7,30 @@
7
7
  // `options.types` brings the real custom types where the model should
8
8
  // validate as the original did, and `model.placeholders` lists the paths
9
9
  // the placeholders stand at. The snapshot is input: whatever fails while it
10
- // is read (a tag that does not read, a nesting deeper than DEPTH, an index
11
- // named like a field) is ERR_INVALID_SNAPSHOT located where the walk was,
10
+ // is read (a tag that does not read, a nesting deeper than MAX_DEPTH, an index
11
+ // named like a field) is ALX_ERR_INVALID_SNAPSHOT located where the walk was,
12
12
  // and the kind metadata it declares is never loosened by its `custom` keys.
13
13
  const { define, shorten } = require('../util.js');
14
14
  const { isFirstLower } = require('../metautil.js');
15
15
  const { Schema } = require('../schema.js');
16
16
  const { Model } = require('../model.js');
17
- const { SchemaDefinitionError } = require('../errors.js');
17
+ const { SchemaDefinitionError, SchemaUsageError } = require('../errors.js');
18
18
  const {
19
- DEPTH,
19
+ MAX_DEPTH,
20
20
  tooDeep,
21
21
  invalidSnapshot,
22
- atSchema,
22
+ unreadable,
23
23
  isObject,
24
24
  isSnapshot,
25
25
  checkRoot,
26
26
  isFunctionMarker,
27
- capitalize,
27
+ kindKeyOf,
28
28
  } = require('./data.js');
29
29
 
30
+ // The keys whose function a placeholder gives the value back for: a codec
31
+ // (and the collected `format`) that returns what it was given.
32
+ const CODECS = new Set(['parse', 'serialize', 'format']);
33
+
30
34
  const nothing = () => undefined;
31
35
 
32
36
  // The bytes of base64 text: any padded text of the alphabet, as written.
@@ -46,17 +50,17 @@ const identity = (value) => value;
46
50
  // the field's key and among the struct's fields).
47
51
  const placeholderOf = (key, at, context) => {
48
52
  context.placeholders.add(at);
49
- return key === 'parse' || key === 'serialize' || key === 'format' ? identity : nothing;
53
+ return CODECS.has(key) ? identity : nothing;
50
54
  };
51
55
 
52
56
  // A value of a snapshot as a value of a definition: the tags revived (a
53
57
  // bigint that does not read throws its own error, a date is checked), a
54
58
  // function marker as the placeholder of its key. `at` is the path of the
55
59
  // value (`context.at` while it is read) and `depth` its nesting, which
56
- // stops at DEPTH.
60
+ // stops at MAX_DEPTH.
57
61
  const revive = (value, key, at, depth, context) => {
58
62
  context.at = at;
59
- if (depth > DEPTH) throw tooDeep();
63
+ if (depth > MAX_DEPTH) throw tooDeep();
60
64
  if (Array.isArray(value)) {
61
65
  const list = [];
62
66
  for (const item of value) list.push(revive(item, key, at, depth + 1, context));
@@ -97,7 +101,7 @@ const isField = (value) => isObject(value) && typeof value.type === 'string';
97
101
  // instance (the one form the schema type takes it in).
98
102
  const fieldDef = (def, at, depth, context) => {
99
103
  context.at = at;
100
- if (depth > DEPTH) throw tooDeep();
104
+ if (depth > MAX_DEPTH) throw tooDeep();
101
105
  if (!isField(def)) throw invalidSnapshot('A field of a snapshot needs a type');
102
106
  const out = { type: def.type };
103
107
  for (const key of Object.keys(def)) {
@@ -146,6 +150,13 @@ const entityDef = (name, entity, context) => {
146
150
  if (!isObject(entity) || typeof entity.kind !== 'string' || !isFirstLower(entity.kind)) {
147
151
  throw invalidSnapshot('An entity of a snapshot needs a kind');
148
152
  }
153
+ // A kind is written as the first key of the definition: one that would not
154
+ // be read back as a kind from there would turn into a field.
155
+ const kindKey = kindKeyOf(entity.kind);
156
+ if (kindKey === null) {
157
+ const kind = JSON.stringify(shorten(entity.kind));
158
+ throw invalidSnapshot(`The kind ${kind} of an entity is not the name of a kind`);
159
+ }
149
160
  const { scope, store, allow, unknown, parent, custom, fields, indexes } = entity;
150
161
  if (parent !== undefined && typeof parent !== 'string') {
151
162
  throw invalidSnapshot('The parent of an entity must be a name');
@@ -160,7 +171,7 @@ const entityDef = (name, entity, context) => {
160
171
  // `unknown` through its metadata.
161
172
  const revived = revive(custom, 'custom', `${name}.custom`, 0, context);
162
173
  const meta = { ...revived, scope, store, allow, unknown, parent };
163
- const def = { [capitalize(entity.kind)]: meta };
174
+ const def = { [kindKey]: meta };
164
175
  const struct = structDef(fields, name, 0, context);
165
176
  for (const key of Object.keys(struct)) define(def, key, struct[key]);
166
177
  for (const key of Object.keys(indexes ?? {})) {
@@ -199,13 +210,13 @@ const typeDef = (name, entry, context) => {
199
210
  };
200
211
 
201
212
  // The types in an order the registry accepts: an alias after the type it
202
- // aliases, down a chain no longer than DEPTH.
213
+ // aliases, down a chain no longer than MAX_DEPTH.
203
214
  const typesDef = (given, context) => {
204
215
  const out = {};
205
216
  const seen = new Set();
206
217
  const add = (name, depth) => {
207
218
  if (seen.has(name)) return;
208
- if (depth > DEPTH) throw tooDeep();
219
+ if (depth > MAX_DEPTH) throw tooDeep();
209
220
  seen.add(name);
210
221
  const entry = given[name];
211
222
  if (isObject(entry) && typeof entry.js === 'string' && Object.hasOwn(given, entry.js)) {
@@ -230,13 +241,15 @@ const fromJSON = (snapshot, options = {}) => {
230
241
  }
231
242
  checkRoot(snapshot);
232
243
  if (!isObject(options)) {
233
- throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Restore options must be an object');
244
+ throw new SchemaUsageError('Restore options must be an object', {
245
+ code: 'ALX_ERR_INVALID_OPTION',
246
+ });
234
247
  }
235
248
  const { registry = 'isolated', types: given = {} } = options;
236
249
  const context = { name: 'types', at: 'types', given, shared: registry === 'shared' };
237
250
  context.placeholders = new Set();
238
251
  const entities = [];
239
- let types;
252
+ let types = null;
240
253
  try {
241
254
  types = typesDef(snapshot.types ?? {}, context);
242
255
  for (const name of Object.keys(snapshot.entities)) {
@@ -248,21 +261,20 @@ const fromJSON = (snapshot, options = {}) => {
248
261
  // (a bigint or a pattern that does not read throws its own), located in
249
262
  // the entity at the path the walk was on, as a struct locates a
250
263
  // definition error.
251
- const located = error instanceof SchemaDefinitionError ? error : invalidSnapshot(error.message);
264
+ const located = error instanceof SchemaDefinitionError ? error : unreadable(error);
252
265
  const field = context.at.slice(context.name.length + 1);
253
- throw field ? located.locate(context.name, field) : atSchema(located, context.name);
266
+ throw field ? located.locate(context.name, field) : located.locate(context.name, '');
254
267
  }
255
268
  Object.assign(types, given);
256
- let model;
269
+ let model = null;
257
270
  try {
258
271
  model = new Model(types, entities, snapshot.database ?? null, { registry });
259
272
  } catch (error) {
260
273
  // What the core rejects is located already; anything else is the
261
274
  // snapshot's too, never a bare TypeError.
262
275
  if (error instanceof SchemaDefinitionError) throw error;
263
- const wrapped = invalidSnapshot(`The model of the snapshot cannot be built: ${error.message}`);
264
- wrapped.cause = error;
265
- throw wrapped;
276
+ const reason = `The model of the snapshot cannot be built: ${error.message}`;
277
+ throw invalidSnapshot(reason, { cause: error });
266
278
  }
267
279
  Object.defineProperty(model, 'placeholders', { value: Array.from(context.placeholders) });
268
280
  return model;
@@ -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
  };