@alexify/metaschema 3.3.0 → 3.4.1

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 (53) hide show
  1. package/CHANGELOG.md +251 -1
  2. package/README.md +31 -20
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +280 -48
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +23 -13
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +24 -2
  22. package/src/lint.js +64 -2
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +68 -11
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +13 -6
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +60 -8
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +14 -5
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +5 -31
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +108 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +31 -10
  52. package/src/util.js +48 -0
  53. package/src/validation.js +313 -0
@@ -11,6 +11,7 @@
11
11
  // named like a field) is 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
+ const { isFirstLower } = require('../metautil.js');
14
15
  const { Schema } = require('../schema.js');
15
16
  const { Model } = require('../model.js');
16
17
  const { SchemaDefinitionError } = require('../errors.js');
@@ -21,11 +22,23 @@ const {
21
22
  atSchema,
22
23
  isObject,
23
24
  isSnapshot,
25
+ checkRoot,
24
26
  isFunctionMarker,
25
- capitalize,
27
+ kindKeyOf,
26
28
  } = require('./data.js');
27
29
 
28
30
  const nothing = () => undefined;
31
+
32
+ // The bytes of base64 text: any padded text of the alphabet, as written.
33
+ const bytesOf = (text) => {
34
+ if (text.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) {
35
+ throw invalidSnapshot(`${JSON.stringify(shorten(text))} is not base64`);
36
+ }
37
+ const binary = atob(text);
38
+ const bytes = new Uint8Array(binary.length);
39
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
40
+ return bytes;
41
+ };
29
42
  const identity = (value) => value;
30
43
 
31
44
  // What stands in for a function, by the key it is under; `at` is the path
@@ -57,6 +70,18 @@ const revive = (value, key, at, depth, context) => {
57
70
  if (Number.isNaN(+date)) throw invalidSnapshot(`${JSON.stringify(value.$date)} is not a date`);
58
71
  return date;
59
72
  }
73
+ if (typeof value.$bytes === 'string') return bytesOf(value.$bytes);
74
+ if (Array.isArray(value.$map)) {
75
+ const map = new Map();
76
+ for (const entry of revive(value.$map, key, at, depth, context)) {
77
+ if (!Array.isArray(entry) || entry.length !== 2) {
78
+ throw invalidSnapshot('An entry of a map needs a key and a value');
79
+ }
80
+ map.set(entry[0], entry[1]);
81
+ }
82
+ return map;
83
+ }
84
+ if (Array.isArray(value.$set)) return new Set(revive(value.$set, key, at, depth, context));
60
85
  const out = {};
61
86
  for (const name of Object.keys(value)) {
62
87
  define(out, name, revive(value[name], name, `${at}.${name}`, depth + 1, context));
@@ -111,14 +136,27 @@ const structDef = (fields, at, depth, context) => {
111
136
  return out;
112
137
  };
113
138
 
114
- // An entity as a definition: its kind as the first key with the metadata,
115
- // then its fields and its indexes; a schema of one type is that type.
139
+ // An entity as a definition: its kind as the first key with the metadata
140
+ // (a lowercase name, which becomes the capitalized key), then its fields
141
+ // and its indexes; a schema of one type is that type. A name that starts
142
+ // with `.` is no entity a model writes (it skips them).
116
143
  const entityDef = (name, entity, context) => {
117
144
  context.at = name;
118
- if (!isObject(entity) || typeof entity.kind !== 'string') {
145
+ if (name.startsWith('.')) throw invalidSnapshot('An entity of a snapshot needs a name');
146
+ if (!isObject(entity) || typeof entity.kind !== 'string' || !isFirstLower(entity.kind)) {
119
147
  throw invalidSnapshot('An entity of a snapshot needs a kind');
120
148
  }
121
- const { scope, store, allow, unknown, custom, fields, indexes } = entity;
149
+ // A kind is written as the first key of the definition: one that would not
150
+ // be read back as a kind from there would turn into a field.
151
+ const kindKey = kindKeyOf(entity.kind);
152
+ if (kindKey === null) {
153
+ const kind = JSON.stringify(shorten(entity.kind));
154
+ throw invalidSnapshot(`The kind ${kind} of an entity is not the name of a kind`);
155
+ }
156
+ const { scope, store, allow, unknown, parent, custom, fields, indexes } = entity;
157
+ if (parent !== undefined && typeof parent !== 'string') {
158
+ throw invalidSnapshot('The parent of an entity must be a name');
159
+ }
122
160
  if (fields === undefined) return fieldDef(entity.type, name, 0, context);
123
161
  for (const key of ['fields', 'custom', 'indexes']) {
124
162
  if (entity[key] !== undefined && !isObject(entity[key])) {
@@ -128,7 +166,8 @@ const entityDef = (name, entity, context) => {
128
166
  // The keys of the kind win over `custom`: a snapshot does not loosen
129
167
  // `unknown` through its metadata.
130
168
  const revived = revive(custom, 'custom', `${name}.custom`, 0, context);
131
- const def = { [capitalize(entity.kind)]: { ...revived, scope, store, allow, unknown } };
169
+ const meta = { ...revived, scope, store, allow, unknown, parent };
170
+ const def = { [kindKey]: meta };
132
171
  const struct = structDef(fields, name, 0, context);
133
172
  for (const key of Object.keys(struct)) define(def, key, struct[key]);
134
173
  for (const key of Object.keys(indexes ?? {})) {
@@ -185,7 +224,9 @@ const typesDef = (given, context) => {
185
224
  return out;
186
225
  };
187
226
 
188
- // The model of a snapshot. `options.types` are entries of the table Model
227
+ // The model of a snapshot, of a model or of one schema (`root` names the
228
+ // entity it is about; `model.entities.get(snapshot.root)` is that schema
229
+ // again). `options.types` are entries of the table Model
189
230
  // takes, over the ones of the snapshot (the real custom types); the
190
231
  // registry is 'isolated' unless `options.registry` says otherwise, so the
191
232
  // placeholders never reach the shared one. The model lists the paths of its
@@ -194,6 +235,7 @@ const fromJSON = (snapshot, options = {}) => {
194
235
  if (!isSnapshot(snapshot)) {
195
236
  throw invalidSnapshot('A snapshot of format 1 with entities is expected');
196
237
  }
238
+ checkRoot(snapshot);
197
239
  if (!isObject(options)) {
198
240
  throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Restore options must be an object');
199
241
  }
@@ -218,7 +260,17 @@ const fromJSON = (snapshot, options = {}) => {
218
260
  throw field ? located.locate(context.name, field) : atSchema(located, context.name);
219
261
  }
220
262
  Object.assign(types, given);
221
- const model = new Model(types, entities, snapshot.database ?? null, { registry });
263
+ let model;
264
+ try {
265
+ model = new Model(types, entities, snapshot.database ?? null, { registry });
266
+ } catch (error) {
267
+ // What the core rejects is located already; anything else is the
268
+ // snapshot's too, never a bare TypeError.
269
+ if (error instanceof SchemaDefinitionError) throw error;
270
+ const wrapped = invalidSnapshot(`The model of the snapshot cannot be built: ${error.message}`);
271
+ wrapped.cause = error;
272
+ throw wrapped;
273
+ }
222
274
  Object.defineProperty(model, 'placeholders', { value: Array.from(context.placeholders) });
223
275
  return model;
224
276
  };
@@ -89,13 +89,20 @@ const stringOf = (state, field, key) => {
89
89
 
90
90
  const asNumber = (value) => (typeof value === 'bigint' ? Number(value) : value);
91
91
 
92
+ // A number within the bounds; a whole one, or one of `decimals` decimals,
93
+ // rounded toward the inside of the bounds.
92
94
  const numberOf = (state, field, whole) => {
93
95
  const min = asNumber(field.min);
94
96
  const max = asNumber(field.max);
95
97
  const low = min ?? (max === undefined ? 0 : max - 100);
96
98
  const high = max ?? low + 100;
97
99
  const value = low + state.random() * (high - low);
98
- return whole ? Math.min(Math.ceil(value), Math.floor(high)) : value;
100
+ const scale = whole ? 1 : field.decimals === undefined ? 0 : 10 ** field.decimals;
101
+ // Past 2⁵³ units of the last decimal every double is a whole number of
102
+ // them (and the product may be no number at all): the value is one.
103
+ if (scale === 0 || !(Math.abs(value * scale) < 2 ** 53)) return value;
104
+ const up = Math.ceil(value * scale) / scale;
105
+ return up > high ? Math.floor(value * scale) / scale : up;
99
106
  };
100
107
 
101
108
  // The widest span a bigint is drawn from: what a number holds exactly.
@@ -113,6 +120,20 @@ const bigintOf = (state, field) => {
113
120
  return low + BigInt(int(state, Number(span)));
114
121
  };
115
122
 
123
+ // Random bytes within the length rule, up to sixteen without one.
124
+ const bytesOf = (state, field) => {
125
+ const bytes = new Uint8Array(countOf(state, field.length, 0, 16));
126
+ for (let index = 0; index < bytes.length; index += 1) bytes[index] = int(state, 255);
127
+ return bytes;
128
+ };
129
+
130
+ // Every name of a flags field present half the time, each true or false.
131
+ const flagsOf = (state, field) => {
132
+ const out = {};
133
+ for (const name of field.flags) if (state.random() < 0.5) out[name] = state.random() < 0.5;
134
+ return out;
135
+ };
136
+
116
137
  const idOf = (state, name) => `${name.toLowerCase()}-${int(state, 0xffff).toString(16)}`;
117
138
 
118
139
  const keyOf = (state, index, numeric) =>
@@ -263,6 +284,10 @@ const draw = (state, field, key) => {
263
284
  return state.random() < 0.5;
264
285
  case 'date':
265
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);
266
291
  case 'null':
267
292
  return null;
268
293
  case 'any':
package/src/model.js CHANGED
@@ -1,11 +1,10 @@
1
1
  const { firstKey, isFirstLower } = require('./metautil.js');
2
2
 
3
- const { BRAND, INSPECT } = require('./util.js');
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 } = require('./errors.js');
7
- const { warning } = require('./lint.js');
8
- const { snapshotOf } = require('./snapshot.js');
6
+ const { SchemaDefinitionError, noValidation } = require('./errors.js');
7
+ const { snapshotOf, orderOf } = require('./snapshot.js');
9
8
 
10
9
  const invalidOption = (name, expected, value) => {
11
10
  const reason = `Model option "${name}" must be ${expected}, got ${JSON.stringify(value)}`;
@@ -42,17 +41,13 @@ const coercionsFor = (options) => {
42
41
  };
43
42
 
44
43
  class Model {
45
- // The model's own warnings (the cycles met while ordering), found while
46
- // building; the rest comes from the entities on first use.
47
- #cycles = [];
48
- #warnings = null;
49
-
50
44
  constructor(types, entities, database = null, options = {}) {
51
45
  this.types = typeFactory(types, registryFor(options));
52
46
  this.coercions = coercionsFor(options);
53
47
  this.entities = new Map();
54
48
  this.database = database;
55
49
  this.order = new Set();
50
+ this[CYCLES] = [];
56
51
  const projections = [];
57
52
  for (const pair of entities) {
58
53
  const name = pair[0];
@@ -74,26 +69,6 @@ class Model {
74
69
  this.#preprocess();
75
70
  }
76
71
 
77
- // The lint warnings of every entity, the references and types they cannot
78
- // resolve, and the recursive dependencies, as `Warning [code]: text`.
79
- get warnings() {
80
- if (this.#warnings !== null) return this.#warnings;
81
- const warnings = [];
82
- const add = (list) => {
83
- for (let index = 0; index < list.length; index += 1) warnings.push(list[index]);
84
- };
85
- for (const pair of this.entities) {
86
- const name = pair[0];
87
- const entity = pair[1];
88
- if (name.startsWith('.')) continue;
89
- add(entity.warnings);
90
- add(entity.checkConsistency());
91
- }
92
- add(this.#cycles);
93
- this.#warnings = warnings;
94
- return warnings;
95
- }
96
-
97
72
  // The model as plain JSON: `{ format, database, types, entities }`, the
98
73
  // entities in dependency order with their metadata, fields, indexes and
99
74
  // relations, and the types they use. What JSON.stringify(model) writes.
@@ -105,37 +80,34 @@ class Model {
105
80
  return `Model ${inspect(this.toJSON(), options)}`;
106
81
  }
107
82
 
83
+ // Depth-first ordering (`orderOf`): an entity after everything it
84
+ // references among the entities, `Identifier` first; a reference back into
85
+ // the path of the walk is a cycle of any length, recorded.
108
86
  #preprocess() {
109
87
  const { entities, order } = this;
110
88
  if (entities.has('Identifier')) order.add('Identifier');
111
- for (const name of entities.keys()) {
112
- const isMeta = name.startsWith('.');
113
- if (!isMeta) this.#reorderEntity(name, new Set());
114
- }
115
- }
116
-
117
- // Depth-first ordering: an entity is added after everything it references.
118
- // `visiting` holds the current path, so a reference back into it is a cycle
119
- // of any length, not only one through the entity the walk started from.
120
- #reorderEntity(name, visiting) {
121
- const entity = this.entities.get(name);
122
- if (!entity || this.order.has(name)) return;
123
- visiting.add(name);
124
- for (const ref of entity.references) {
125
- if (ref === name) continue;
126
- if (visiting.has(ref)) {
127
- this.#cycles.push(
128
- warning('recursive-reference', `"${name}" depends on "${ref}" recursively`),
129
- );
130
- continue;
89
+ const starts = [];
90
+ for (const pair of entities) if (!pair[0].startsWith('.')) starts.push(pair);
91
+ const edgesOf = (entity) => {
92
+ const edges = [];
93
+ for (const ref of entity.references) {
94
+ const target = entities.get(ref);
95
+ if (target !== undefined) edges.push([ref, target]);
131
96
  }
132
- this.#reorderEntity(ref, visiting);
133
- }
134
- visiting.delete(name);
135
- this.order.add(name);
97
+ return edges;
98
+ };
99
+ orderOf(starts, edgesOf, (name, ref) => this[CYCLES].push([name, ref]), order);
136
100
  }
137
101
  }
138
102
 
103
+ // The warnings of a model are the validation half's, as a schema's are.
104
+ Object.defineProperty(Model.prototype, 'warnings', {
105
+ get() {
106
+ throw noValidation('warnings');
107
+ },
108
+ configurable: true,
109
+ });
110
+
139
111
  Model.prototype[BRAND] = 'Model';
140
112
 
141
113
  module.exports = { Model };
@@ -7,6 +7,7 @@
7
7
  // value of another realm or of another copy of bson is one too.
8
8
  const { idFieldOf } = require('../kinds.js');
9
9
  const { invalidOption, notRegistered } = require('../errors.js');
10
+ const { isBytes } = require('../util.js');
10
11
  const { register: coercion } = require('../coerce/index.js');
11
12
 
12
13
  // The tag every value of bson carries, and the key of a document.
@@ -22,9 +23,20 @@ const isObjectId = (value) => {
22
23
 
23
24
  const isDecimal128 = (value) => tagOf(value) === 'Decimal128' && typeof value.toJSON === 'function';
24
25
 
26
+ // The bytes of a generic Binary of the driver (subtype 0, or 2, its old
27
+ // form), copied off the memory the driver read it into; null for anything
28
+ // else. A Binary of another subtype (a UUID, an encrypted value, a vector)
29
+ // written back as bytes would lose its subtype, so it is left for the check.
30
+ const binaryBytes = (value) => {
31
+ const binary = tagOf(value) === 'Binary' && typeof value.toJSON === 'function';
32
+ if (!binary || !isBytes(value.buffer)) return null;
33
+ const subtype = value.sub_type;
34
+ if (subtype !== 0 && subtype !== 2) return null;
35
+ return new Uint8Array(value.buffer.subarray(0, value.position));
36
+ };
37
+
25
38
  const isBinary = (value) =>
26
- (tagOf(value) === 'Binary' && typeof value.toJSON === 'function') ||
27
- Object.prototype.toString.call(value) === '[object Uint8Array]';
39
+ (tagOf(value) === 'Binary' && typeof value.toJSON === 'function') || isBytes(value);
28
40
 
29
41
  const construct = () => {};
30
42
 
@@ -115,4 +127,4 @@ const idOf = (schema) => {
115
127
  return id === null || ID in schema.fields ? null : id;
116
128
  };
117
129
 
118
- module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId };
130
+ module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId, binaryBytes };
@@ -11,7 +11,8 @@ const { embeds } = require('../prototypes/reference.js');
11
11
  const { infoOf } = require('../codec.js');
12
12
  const { referencesOf } = require('../context.js');
13
13
  const { invalidTarget, invalidOption } = require('../errors.js');
14
- const { ID, HEX, driverOf, idOf, isObjectId } = require('./bson.js');
14
+ const { baseTypeOf } = require('../types.js');
15
+ const { ID, HEX, driverOf, idOf, isObjectId, binaryBytes } = require('./bson.js');
15
16
 
16
17
  // The shapes of infoOf in codec.js, by name, for the three walks of the
17
18
  // subpath; `mongodb.test.js` holds them to the numbers of the core.
@@ -25,9 +26,10 @@ const SHAPES = Object.freeze({
25
26
  TUPLE: 6,
26
27
  UNION: 7,
27
28
  REFERENCE: 8,
29
+ FLAGS: 9,
28
30
  });
29
31
 
30
- const { SCHEMA, FIELDS, NESTED, LIST, KEYED, TUPLE, UNION, REFERENCE } = SHAPES;
32
+ const { LEAF, SCHEMA, FIELDS, NESTED, LIST, KEYED, TUPLE, UNION, REFERENCE } = SHAPES;
31
33
 
32
34
  // A plain object of any realm: its prototype is the root of its realm or
33
35
  // none (an Array, a Date, a Map or a value of bson has one in between).
@@ -139,6 +141,12 @@ const walk = (state, node, value) => {
139
141
  const index = info.table.get(value[node.discriminator]);
140
142
  return index === undefined ? value : walk(state, node.union[index], value);
141
143
  }
144
+ // The driver writes a Uint8Array as binData and reads it back as a Binary:
145
+ // its bytes again, where the field holds bytes.
146
+ if (shape === LEAF && !state.out && typeof value === 'object') {
147
+ const bytes = binaryBytes(value);
148
+ if (bytes !== null && baseTypeOf(node).type === 'bytes') return bytes;
149
+ }
142
150
  return value;
143
151
  };
144
152
 
@@ -1,12 +1,14 @@
1
1
  const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
2
2
 
3
- const { hasBrand, formatters } = require('./util.js');
3
+ const { hasBrand, formatters, typeOf } = require('./util.js');
4
+ const { constants, isKindKey } = require('./kinds.js');
4
5
  const { SchemaDefinitionError } = require('./errors.js');
5
- const { typeOf } = require('./issues.js');
6
6
 
7
7
  // The first key of an object decides what it is: a Schema or a built field is
8
- // used as it is, a capitalized key is a kind, `type` is the long form, a type
9
- // name is that type's shorthand, and anything else is a nested struct.
8
+ // used as it is, a kind key (`isKindKey` of kinds.js: a name like `Entity`
9
+ // holding the metadata object) is a kind, `type` is the long form, a type
10
+ // name is that type's shorthand, and anything else is a nested struct, a
11
+ // capitalized key that is no kind (`PORT`, `Name: 'string'`) included.
10
12
  const PARSERS = Object.assign(Object.create(null), {
11
13
  string: ['stringShorthand'],
12
14
  object: [
@@ -32,6 +34,7 @@ class Preprocessor {
32
34
  this.Schema = root.constructor;
33
35
  this.root = root;
34
36
  this.types = root.types;
37
+ this.kinds = null;
35
38
  }
36
39
 
37
40
  // The first key of an object is read once here and handed to the parsers
@@ -103,9 +106,15 @@ class Preprocessor {
103
106
 
104
107
  schemaWithKind(source, first) {
105
108
  const { types, root } = this;
106
- if (!isFirstUpper(first)) return null;
109
+ if (!isKindKey(first, source[first])) return null;
107
110
  const { [first]: meta, ...fields } = source;
108
111
  const kind = toLowerCamel(first);
112
+ // A kind of the program's own is kept for the lint: metadata that reads
113
+ // as field definitions is most likely a field that was read as a kind.
114
+ if (!constants.KIND.includes(kind)) {
115
+ if (this.kinds === null) this.kinds = [];
116
+ this.kinds.push([first, meta]);
117
+ }
109
118
  const kindMeta = { kind, meta, root };
110
119
  const defs = { schema: fields };
111
120
  return { Type: types.schema, defs, kindMeta };
@@ -1,12 +1,20 @@
1
1
  const { BRAND, INSPECT } = require('../util.js');
2
- const { FORMAT, notApplicable, compileRules } = require('../rules.js');
3
- const { runValidate, runCheckType } = require('../issues.js');
4
- const { SchemaDefinitionError } = require('../errors.js');
2
+ const { FORMAT, checkBounds, notApplicable } = require('../rules.js');
3
+ const { SchemaDefinitionError, noValidation } = require('../errors.js');
5
4
 
6
5
  // Keys of a field definition become properties of the field, so a key that
7
6
  // names one of its methods (or the prototype itself) would replace it. The
8
- // methods of the type contract are reserved whether the type has them or not.
9
- const RESERVED = new Set(['__proto__', 'prototype', 'check', 'checkType', 'compile', 'construct']);
7
+ // methods of the type contract are reserved whether the type has them or
8
+ // not, and so is `root`, the schema the field belongs to.
9
+ const RESERVED = new Set([
10
+ '__proto__',
11
+ 'prototype',
12
+ 'check',
13
+ 'checkType',
14
+ 'compile',
15
+ 'construct',
16
+ 'root',
17
+ ]);
10
18
 
11
19
  const reservedKey = (key) =>
12
20
  new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
@@ -30,37 +38,16 @@ const checkCodecs = (type) => {
30
38
  }
31
39
  };
32
40
 
33
- // A nullable field accepts null in place of a value of its type, whatever
34
- // its rules; `required` still says whether the key must be there.
35
- const nullable = (inner) => (value, context, key) => {
36
- if (value === null) return;
37
- inner(value, context, key);
38
- };
39
-
40
- // The check of a field with rules or a validate function: the type check,
41
- // then the rules, then the validate function. A type failure cancels the
42
- // rest (a length or a validator makes no sense for a value of another type),
43
- // and validate runs only on a value that passed everything before it, so it
44
- // can rely on the type and the rules. A field with neither is its type check
45
- // alone.
46
- const withRules = (type, inner, rules) => {
47
- const { required, validate } = type;
48
- return (value, context, key) => {
49
- if (value == null && !required) return;
50
- const before = context.count;
51
- inner(value, context, key);
52
- if (context.count !== before) return;
53
- for (let index = 0; index < rules.length; index += 1) {
54
- if (context.count >= context.limit) break;
55
- rules[index](value, context, key);
56
- }
57
- if (validate && context.count === before) {
58
- const nested = key !== undefined;
59
- if (nested) context.path.push(key);
60
- runValidate(type, validate, value, context);
61
- if (nested) context.path.pop();
62
- }
63
- };
41
+ // What builds the checks of a schema and of its fields on their first use:
42
+ // the validation half of the core installs them (`validation.js`), and a
43
+ // schema built through `./definition` alone says that it cannot validate.
44
+ const BUILD = {
45
+ field() {
46
+ throw noValidation('check');
47
+ },
48
+ schema() {
49
+ throw noValidation('check');
50
+ },
64
51
  };
65
52
 
66
53
  class AbstractType {
@@ -69,9 +56,11 @@ class AbstractType {
69
56
  static rules = new Set();
70
57
  static options = new Set();
71
58
 
72
- // The compiled check of the field: a closure built once from the field,
73
- // kept out of its definition (toJSON, util.inspect) as a private field.
74
- #check;
59
+ // The compiled check of the field: a closure built from the field on the
60
+ // first use of `check`, kept out of its definition (toJSON, util.inspect)
61
+ // as a private field. A schema that is only read (rendered, written as a
62
+ // snapshot) never compiles one.
63
+ #check = undefined;
75
64
 
76
65
  constructor(def, preprocessor) {
77
66
  this.root = preprocessor.root;
@@ -86,45 +75,24 @@ class AbstractType {
86
75
  continue;
87
76
  }
88
77
  if (!rules.has(key)) throw notApplicable(key, this.type, rules);
89
- this[key] = format(value);
78
+ this[key] = format(value, this);
90
79
  }
80
+ checkBounds(this);
91
81
  this.construct(def, preprocessor);
92
82
  if (this.type) this.root.references.add(this.type);
93
83
  for (const key of FLAGS) {
94
84
  if (this[key] !== undefined && typeof this[key] !== 'boolean') throw invalidFlag(key);
95
85
  }
96
86
  checkCodecs(this);
97
- // The rule checks that apply to this field, compiled once: a field
98
- // without rules is its type check alone, and check is the hot path.
99
- const checks = compileRules(this);
100
- const inner = this.compile();
101
- const plain = checks.length === 0 && !this.validate;
102
- const check = plain ? inner : withRules(this, inner, checks);
103
- this.#check = this.nullable === true ? nullable(check) : check;
104
87
  }
105
88
 
106
89
  // Records the problems of a value into the context of the current check,
107
90
  // under `key` when the field is reached through one.
108
91
  get check() {
92
+ if (this.#check === undefined) this.#check = BUILD.field(this);
109
93
  return this.#check;
110
94
  }
111
95
 
112
- // The type check of a field, as a closure built once from the field. A
113
- // built-in prototype compiles its own; a custom type has a
114
- // `checkType(value, path)` that returns messages, run through the
115
- // validator contract.
116
- compile() {
117
- const type = this;
118
- const { required } = this;
119
- return (value, context, key) => {
120
- if (value == null && !required) return;
121
- const nested = key !== undefined;
122
- if (nested) context.path.push(key);
123
- runCheckType(type, value, context);
124
- if (nested) context.path.pop();
125
- };
126
- }
127
-
128
96
  toJSON() {
129
97
  const { root, ...rest } = this;
130
98
  return rest;
@@ -137,4 +105,4 @@ class AbstractType {
137
105
 
138
106
  AbstractType.prototype[BRAND] = 'Type';
139
107
 
140
- module.exports = { AbstractType };
108
+ module.exports = { AbstractType, BUILD };