@alexify/metaschema 3.3.0 → 3.4.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 (53) hide show
  1. package/CHANGELOG.md +186 -1
  2. package/README.md +24 -16
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +224 -28
  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 +15 -8
  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 +4 -1
  22. package/src/lint.js +15 -1
  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 +50 -10
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +10 -3
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +52 -7
  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 +1 -2
  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 +0 -26
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +105 -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 +24 -6
  52. package/src/util.js +43 -0
  53. package/src/validation.js +313 -0
@@ -1,30 +1,17 @@
1
1
  const { SchemaDefinitionError } = require('../errors.js');
2
- const { issues } = require('../issues.js');
3
- const { ENUM_SET_SIZE, isDate } = require('../util.js');
4
2
 
5
3
  const missingEnum = (type) => {
6
4
  const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
7
5
  return new SchemaDefinitionError('ERR_INVALID_ENUM', hint);
8
6
  };
9
7
 
10
- // A single comparison on the way through for a valid value; the optional
11
- // case is looked at only when it fails.
12
- const scalarCheck = (scalar, required) => (value, context, key) => {
13
- // oxlint-disable-next-line valid-typeof
14
- if (typeof value === scalar) return;
15
- if (!required && value == null) return;
16
- issues.type(context, scalar, value, key);
17
- };
18
-
8
+ // The scalar types: what a field of each holds (its check is `COMPILE` of
9
+ // checks.js, the validation half of the core).
19
10
  const scalar = {
20
11
  kind: 'scalar',
21
12
  options: [],
22
13
 
23
14
  construct() {},
24
-
25
- compile() {
26
- return scalarCheck(this.scalar, this.required);
27
- },
28
15
  };
29
16
 
30
17
  const enumerable = {
@@ -36,97 +23,25 @@ const enumerable = {
36
23
  if (!Array.isArray(values) || values.length === 0) throw missingEnum(this.type);
37
24
  this.enum = values;
38
25
  },
39
-
40
- compile() {
41
- const values = this.enum;
42
- const { required } = this;
43
- if (values.length > ENUM_SET_SIZE) {
44
- const set = new Set(values);
45
- return (value, context, key) => {
46
- if (set.has(value)) return;
47
- if (!required && value == null) return;
48
- issues.enum(context, values, key);
49
- };
50
- }
51
- return (value, context, key) => {
52
- if (values.includes(value)) return;
53
- if (!required && value == null) return;
54
- issues.enum(context, values, key);
55
- };
56
- },
57
26
  };
58
27
 
59
28
  // A number without a fraction; it renders as a number in TypeScript.
60
- const integer = {
61
- kind: 'scalar',
62
- scalar: 'number',
63
- rules: ['min', 'max'],
64
- options: ['min', 'max'],
65
-
66
- construct() {},
67
-
68
- compile() {
69
- const { required } = this;
70
- return (value, context, key) => {
71
- if (Number.isInteger(value)) return;
72
- if (!required && value == null) return;
73
- issues.type(context, 'integer', value, key);
74
- };
75
- },
76
- };
29
+ const integer = { ...scalar, scalar: 'number', rules: ['min', 'max'], options: ['min', 'max'] };
77
30
 
78
31
  // A Date instance with a time: an invalid Date is a type error.
79
- const date = {
80
- kind: 'scalar',
81
- scalar: 'date',
82
- options: [],
32
+ const date = { ...scalar, scalar: 'date' };
83
33
 
84
- construct() {},
34
+ // A Uint8Array of any realm, a Buffer included: the value of binary data,
35
+ // base64 text on a JSON wire. `length` counts its bytes.
36
+ const bytes = { ...scalar, scalar: 'bytes', rules: ['length'], options: ['length'] };
85
37
 
86
- compile() {
87
- const { required } = this;
88
- return (value, context, key) => {
89
- if (isDate(value) && !Number.isNaN(value.getTime())) return;
90
- if (!required && value == null) return;
91
- issues.type(context, 'date', value, key);
92
- };
93
- },
94
- };
95
-
96
- const nothing = {
97
- kind: 'scalar',
98
- scalar: 'null',
99
- options: [],
100
-
101
- construct() {},
102
-
103
- compile() {
104
- const { required } = this;
105
- return (value, context, key) => {
106
- if (value === null) return;
107
- if (value === undefined && !required) return;
108
- issues.type(context, 'null', value, key);
109
- };
110
- },
111
- };
38
+ const nothing = { ...scalar, scalar: 'null' };
112
39
 
113
40
  // Any value at all, null and undefined included; `required` still says
114
41
  // whether the key must be there.
115
- const accept = () => {};
116
-
117
- const any = {
118
- kind: 'scalar',
119
- scalar: 'any',
120
- options: [],
121
-
122
- construct() {},
42
+ const any = { ...scalar, scalar: 'any' };
123
43
 
124
- compile() {
125
- return accept;
126
- },
127
- };
128
-
129
- const unknown = { ...any, scalar: 'unknown' };
44
+ const unknown = { ...scalar, scalar: 'unknown' };
130
45
 
131
46
  const string = {
132
47
  ...scalar,
@@ -134,7 +49,12 @@ const string = {
134
49
  rules: ['length', 'pattern', 'format'],
135
50
  options: ['length', 'unicode', 'pattern', 'format'],
136
51
  };
137
- const number = { ...scalar, scalar: 'number', rules: ['min', 'max'], options: ['min', 'max'] };
52
+ const number = {
53
+ ...scalar,
54
+ scalar: 'number',
55
+ rules: ['min', 'max', 'decimals'],
56
+ options: ['min', 'max', 'decimals'],
57
+ };
138
58
  const bigint = { ...scalar, scalar: 'bigint', rules: ['min', 'max'], options: ['min', 'max'] };
139
59
  const boolean = { ...scalar, scalar: 'boolean' };
140
60
 
@@ -145,6 +65,7 @@ module.exports = {
145
65
  bigint,
146
66
  boolean,
147
67
  date,
68
+ bytes,
148
69
  null: nothing,
149
70
  any,
150
71
  unknown,
@@ -1,5 +1,5 @@
1
1
  const { hasBrand } = require('../util.js');
2
- const { createStruct, isStruct, checkOf } = require('../struct.js');
2
+ const { createStruct, isStruct } = require('../struct.js');
3
3
  const { SchemaDefinitionError } = require('../errors.js');
4
4
 
5
5
  const missingSchema = (type) => {
@@ -43,15 +43,6 @@ const schema = {
43
43
  else this.schema = createStruct(definition, prep);
44
44
  adopt(this, definition);
45
45
  },
46
-
47
- compile() {
48
- const { required } = this;
49
- const check = isStruct(this.schema) ? checkOf(this.schema) : this.schema.check;
50
- return (value, context, key) => {
51
- if (!required && value == null) return;
52
- check(value, context, key);
53
- };
54
- },
55
46
  };
56
47
 
57
48
  module.exports = { schema };
@@ -1,7 +1,6 @@
1
1
  const { isFirstUpper } = require('../metautil.js');
2
2
  const { formatters } = require('../util.js');
3
3
  const { SchemaDefinitionError } = require('../errors.js');
4
- const { issues } = require('../issues.js');
5
4
 
6
5
  const invalidTuple = (reason) => new SchemaDefinitionError('ERR_INVALID_TUPLE', `Tuple ${reason}`);
7
6
 
@@ -43,31 +42,6 @@ const tuple = {
43
42
  }
44
43
  this.value = built;
45
44
  },
46
-
47
- compile() {
48
- const { required, type } = this;
49
- const checks = [];
50
- for (let index = 0; index < this.value.length; index += 1) checks.push(this.value[index].check);
51
- const { length } = checks;
52
- return (value, context, key) => {
53
- if (!Array.isArray(value)) {
54
- if (!required && value == null) return;
55
- issues.type(context, type, value, key);
56
- return;
57
- }
58
- if (value.length > length) {
59
- issues.length(context, undefined, length, value.length, key);
60
- return;
61
- }
62
- const nested = key !== undefined;
63
- if (nested) context.path.push(key);
64
- for (let index = 0; index < length; index += 1) {
65
- if (context.count >= context.limit) break;
66
- checks[index](value[index], context, index);
67
- }
68
- if (nested) context.path.pop();
69
- };
70
- },
71
45
  };
72
46
 
73
47
  module.exports = { tuple };
@@ -1,11 +1,7 @@
1
1
  const { SchemaDefinitionError } = require('../errors.js');
2
- const { issues, release } = require('../issues.js');
3
2
 
4
3
  const invalidUnion = (reason) => new SchemaDefinitionError('ERR_INVALID_UNION', `Union ${reason}`);
5
4
 
6
- // What a branch is called in the message of a value that matched none.
7
- const nameOf = (branch) => (branch.type === 'schema' ? 'object' : branch.type);
8
-
9
5
  // The values of the discriminator field of a branch: the branch must be a
10
6
  // struct whose field of that name is an enum, so the branch is known from
11
7
  // one lookup.
@@ -18,29 +14,8 @@ const valuesOf = (branch, discriminator, index) => {
18
14
  return field.enum;
19
15
  };
20
16
 
21
- // The branch of a discriminated union by the value of its discriminator, as
22
- // a Map of value to branch index: built once per field, on first use, and
23
- // shared by the check, the passes of parse and the JIT.
24
- const TABLES = new WeakMap();
25
-
26
- const tableOf = (field) => {
27
- let table = TABLES.get(field);
28
- if (table === undefined) {
29
- table = new Map();
30
- const { union: branches, discriminator } = field;
31
- for (let index = 0; index < branches.length; index += 1) {
32
- const values = branches[index].schema[discriminator].enum;
33
- for (let at = 0; at < values.length; at += 1) table.set(values[at], index);
34
- }
35
- TABLES.set(field, table);
36
- }
37
- return table;
38
- };
39
-
40
- // A value of one of several definitions. Without a discriminator the
41
- // branches are tried in order and the first one that records nothing wins;
42
- // what a failed branch recorded is dropped. With one, the branch is picked
43
- // by the value of that field in one Map lookup.
17
+ // A value of one of several definitions: plain, or picked by the value of
18
+ // a discriminator field (`COMPILE.union` of checks.js has the check).
44
19
  const union = {
45
20
  kind: 'struct',
46
21
  options: ['union', 'discriminator'],
@@ -66,12 +41,19 @@ const union = {
66
41
  for (let index = 0; index < built.length; index += 1) {
67
42
  const values = valuesOf(built[index], discriminator, index);
68
43
  // The branch is picked by the value before any default is applied, so
69
- // a default on the discriminator could never decide anything.
70
- if (built[index].schema[discriminator].default !== undefined) {
44
+ // a default on the discriminator could never decide anything; nor can
45
+ // a missing or a null one, which no branch has among its values.
46
+ const tag = built[index].schema[discriminator];
47
+ if (tag.default !== undefined) {
71
48
  throw invalidUnion(
72
49
  `discriminator "${discriminator}" of branch ${index} cannot have a default`,
73
50
  );
74
51
  }
52
+ if (tag.required === false || tag.nullable === true) {
53
+ throw invalidUnion(
54
+ `discriminator "${discriminator}" of branch ${index} must be required and not nullable`,
55
+ );
56
+ }
75
57
  for (let at = 0; at < values.length; at += 1) {
76
58
  const value = values[at];
77
59
  if (seen.has(value)) {
@@ -82,58 +64,6 @@ const union = {
82
64
  }
83
65
  }
84
66
  },
85
-
86
- compile() {
87
- const { required, discriminator } = this;
88
- if (discriminator === undefined) return this.compilePlain(required);
89
- const checks = [];
90
- for (let index = 0; index < this.union.length; index += 1) checks.push(this.union[index].check);
91
- const table = tableOf(this);
92
- const expected = [];
93
- for (const value of table.keys()) expected.push(value);
94
- return (value, context, key) => {
95
- if (value === null || typeof value !== 'object') {
96
- if (!required && value == null) return;
97
- issues.type(context, 'object', value, key);
98
- return;
99
- }
100
- const index = table.get(value[discriminator]);
101
- if (index !== undefined) {
102
- checks[index](value, context, key);
103
- return;
104
- }
105
- const nested = key !== undefined;
106
- if (nested) context.path.push(key);
107
- issues.union(context, expected, discriminator, discriminator);
108
- if (nested) context.path.pop();
109
- };
110
- },
111
-
112
- compilePlain(required) {
113
- const checks = [];
114
- const expected = [];
115
- for (let index = 0; index < this.union.length; index += 1) {
116
- const branch = this.union[index];
117
- checks.push(branch.check);
118
- expected.push(nameOf(branch));
119
- }
120
- const { length } = checks;
121
- return (value, context, key) => {
122
- if (!required && value == null) return;
123
- const { count } = context;
124
- // The validators a failed branch set aside in an async check go with
125
- // its issues: they belong to a branch the value does not match.
126
- const pending = context.async === null ? 0 : context.async.length;
127
- for (let index = 0; index < length; index += 1) {
128
- checks[index](value, context, key);
129
- if (context.count === count) return;
130
- context.issues.length = count;
131
- context.count = count;
132
- if (context.async !== null) release(context.async, pending);
133
- }
134
- issues.union(context, expected, undefined, key);
135
- };
136
- },
137
67
  };
138
68
 
139
- module.exports = { union, nameOf, tableOf };
69
+ module.exports = { union };
package/src/rules.js CHANGED
@@ -1,12 +1,11 @@
1
- // The rule checks a field may carry besides its type. A type lists the rules
2
- // it accepts (`rules: ['length']` on a prototype); a rule in a definition of a
1
+ // The rules a field may carry besides its type. A type lists the rules it
2
+ // accepts (`rules: ['length']` on a prototype); a rule in a definition of a
3
3
  // type that does not accept it is a definition error, not a silent no-op. A
4
- // rule's value is checked and normalized when the field is built (`format`),
5
- // and its check is compiled into a closure over the field's bounds, run after
6
- // the type check.
7
- const { issues } = require('./issues.js');
4
+ // rule's value is checked and normalized when the field is built (`format`);
5
+ // its check is the validation half's (`compileRules` of `checks.js`),
6
+ // compiled into a closure over the field's bounds and run after the type
7
+ // check.
8
8
  const { SchemaDefinitionError } = require('./errors.js');
9
- const { isMap, isSet } = require('./util.js');
10
9
 
11
10
  const invalidRule = (reason) => new SchemaDefinitionError('ERR_INVALID_RULE', reason);
12
11
 
@@ -60,12 +59,28 @@ const formatPattern = (value) => {
60
59
  // the hint, never a check that passes everything.
61
60
  const FORMATS = Object.create(null);
62
61
 
63
- const formatName = (value) => {
62
+ // The entry a field's format named when the field was built: a format the
63
+ // program registers later under that name does not change the field, whose
64
+ // check is compiled on its first use.
65
+ const NAMED = new WeakMap();
66
+
67
+ const formatName = (value, type) => {
64
68
  if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
65
69
  if (FORMATS[value] === undefined) {
66
70
  const hint = 'register() of @alexify/metaschema/formats';
67
71
  throw invalidRule(`Rule "format" names a format that is not registered: "${value}" (${hint})`);
68
72
  }
73
+ NAMED.set(type, FORMATS[value]);
74
+ return value;
75
+ };
76
+
77
+ const formatOf = (type) => NAMED.get(type);
78
+
79
+ // The decimals a number may have: what a double holds exactly in a fraction.
80
+ const formatDecimals = (value) => {
81
+ if (!Number.isInteger(value) || value < 0 || value > 15) {
82
+ throw invalidRule('Rule "decimals" needs an integer from 0 to 15');
83
+ }
69
84
  return value;
70
85
  };
71
86
 
@@ -75,160 +90,21 @@ const FORMAT = Object.assign(Object.create(null), {
75
90
  max: formatLimit('max'),
76
91
  pattern: formatPattern,
77
92
  format: formatName,
93
+ decimals: formatDecimals,
78
94
  });
79
95
 
80
- const notApplicable = (rule, type, rules) => {
81
- const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
82
- return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
83
- };
84
-
85
- // Code points of a string: a surrogate pair counts once, a lone surrogate
86
- // once too.
87
- const codePoints = (text) => {
88
- const { length } = text;
89
- let count = 0;
90
- for (let index = 0; index < length; index += 1) {
91
- const unit = text.charCodeAt(index);
92
- if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < length) {
93
- const next = text.charCodeAt(index + 1);
94
- if (next >= 0xdc00 && next <= 0xdfff) index += 1;
95
- }
96
- count += 1;
97
- }
98
- return count;
99
- };
100
-
101
- // The own keys of an object, counted without a list of them.
102
- const keyCount = (value) => {
103
- let count = 0;
104
- for (const name in value) if (Object.hasOwn(value, name)) count += 1;
105
- return count;
106
- };
107
-
108
- // The length of a value, by what the value is rather than by what it carries
109
- // (an object with a `size` key is an object): the units of a string, the
110
- // length of an array, the size of a Set or a Map, the own keys of an object.
111
- const lengthOf = (value) => {
112
- if (typeof value === 'string' || Array.isArray(value)) return value.length;
113
- return isMap(value) || isSet(value) ? value.size : keyCount(value);
114
- };
115
-
116
- // A string field measures its units, or its code points when it asks for
117
- // them; anything else is measured by what it is. One closure per case, each
118
- // calling its measure directly: a measure held in a variable is a call site
119
- // shared by every length rule of the process, which V8 then cannot inline.
120
- const compileLength = (type) => {
121
- const { min, max } = type.length;
122
- if (type.scalar === 'string') {
123
- if (type.unicode === true) {
124
- return (value, context, key) => {
125
- const actual = codePoints(value);
126
- const short = min !== undefined && actual < min;
127
- const long = max !== undefined && actual > max;
128
- if (short || long) issues.length(context, min, max, actual, key);
129
- };
130
- }
131
- return (value, context, key) => {
132
- const actual = value.length;
133
- const short = min !== undefined && actual < min;
134
- const long = max !== undefined && actual > max;
135
- if (short || long) issues.length(context, min, max, actual, key);
136
- };
137
- }
138
- return (value, context, key) => {
139
- const actual = lengthOf(value);
140
- const short = min !== undefined && actual < min;
141
- const long = max !== undefined && actual > max;
142
- if (short || long) issues.length(context, min, max, actual, key);
143
- };
144
- };
145
-
146
- // One closure for both bounds when a field has both.
147
- const compileRange = (type) => {
96
+ // The bounds of a field leave room for a value: the definition is checked
97
+ // when the field is built, its check compiled later.
98
+ const checkBounds = (type) => {
148
99
  const { min, max } = type;
149
- if (min === undefined) {
150
- return (value, context, key) => {
151
- if (value > max) issues.range(context, min, max, value, key);
152
- };
153
- }
154
- if (max === undefined) {
155
- return (value, context, key) => {
156
- if (value < min) issues.range(context, min, max, value, key);
157
- };
158
- }
159
- if (min > max) throw invalidRule('Rule "max" is below "min"');
160
- return (value, context, key) => {
161
- if (value < min || value > max) issues.range(context, min, max, value, key);
162
- };
163
- };
164
-
165
- // The units a pattern may be run over: `length.max` (twice it when the
166
- // length counts code points, each at most two units), so that a string past
167
- // the bound, reported for its length already, never reaches a pattern that
168
- // backtracks over it; no limit without the bound.
169
- const patternLimit = (type) => {
170
- const max = type.length?.max;
171
- if (max === undefined) return Infinity;
172
- return type.unicode === true ? 2 * max : max;
173
- };
174
-
175
- const compilePattern = (type) => {
176
- const { pattern } = type;
177
- const { source } = pattern;
178
- const limit = patternLimit(type);
179
- return (value, context, key) => {
180
- if (value.length <= limit && !pattern.test(value)) issues.pattern(context, source, key);
181
- };
182
- };
183
-
184
- // A format is the test the subpath registered under its name, run after the
185
- // pattern and under the same bound.
186
- const compileFormat = (type) => {
187
- const { format } = type;
188
- const { test } = FORMATS[format];
189
- const limit = patternLimit(type);
190
- return (value, context, key) => {
191
- if (value.length <= limit && !test(value)) issues.format(context, format, key);
192
- };
193
- };
194
-
195
- // The rules a field carries, by name, in the order its type lists them, min
196
- // and max as the one `range`: the order the closures run them in and the JIT
197
- // emits them in.
198
- const ruleNames = (type) => {
199
- const names = [];
200
- let range = false;
201
- for (const name of type.constructor.rules) {
202
- if (type[name] === undefined) continue;
203
- if (name === 'min' || name === 'max') range = true;
204
- else names.push(name);
100
+ if (min !== undefined && max !== undefined && min > max) {
101
+ throw invalidRule('Rule "max" is below "min"');
205
102
  }
206
- if (range) names.push('range');
207
- return names;
208
103
  };
209
104
 
210
- const COMPILERS = Object.assign(Object.create(null), {
211
- length: compileLength,
212
- pattern: compilePattern,
213
- format: compileFormat,
214
- range: compileRange,
215
- });
216
-
217
- // The checks of the rules a field carries.
218
- const compileRules = (type) => {
219
- const names = ruleNames(type);
220
- const checks = [];
221
- for (let index = 0; index < names.length; index += 1) checks.push(COMPILERS[names[index]](type));
222
- return checks;
105
+ const notApplicable = (rule, type, rules) => {
106
+ const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
107
+ return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
223
108
  };
224
109
 
225
- module.exports = {
226
- FORMAT,
227
- FORMATS,
228
- notApplicable,
229
- ruleNames,
230
- compileRules,
231
- patternLimit,
232
- codePoints,
233
- lengthOf,
234
- };
110
+ module.exports = { FORMAT, FORMATS, formatOf, checkBounds, notApplicable };