@alexify/metaschema 3.0.0 → 3.2.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 (47) hide show
  1. package/CHANGELOG.md +312 -1
  2. package/README.md +463 -17
  3. package/SECURITY.md +26 -7
  4. package/index.d.ts +338 -3
  5. package/package.json +42 -5
  6. package/src/codec.js +161 -73
  7. package/src/compile/code.js +1 -1
  8. package/src/compile/emit.js +60 -7
  9. package/src/compile/index.d.ts +6 -0
  10. package/src/compile/index.js +14 -3
  11. package/src/context.js +8 -9
  12. package/src/errors.js +18 -1
  13. package/src/formats/index.d.ts +19 -0
  14. package/src/formats/index.js +146 -0
  15. package/src/generators/fromjsonschema.js +517 -0
  16. package/src/generators/index.d.ts +19 -2
  17. package/src/generators/index.js +16 -10
  18. package/src/generators/jsonschema.js +2 -0
  19. package/src/issues.js +37 -20
  20. package/src/lint.js +12 -3
  21. package/src/locales/en.js +11 -2
  22. package/src/locales/uk.js +10 -2
  23. package/src/metadata.js +3 -2
  24. package/src/model/data.js +122 -0
  25. package/src/model/diff.js +439 -0
  26. package/src/model/index.d.ts +68 -0
  27. package/src/model/index.js +45 -0
  28. package/src/model/infer.js +483 -0
  29. package/src/model/merge.js +255 -0
  30. package/src/model/pattern.js +322 -0
  31. package/src/model/restore.js +226 -0
  32. package/src/model/sample.js +398 -0
  33. package/src/model.js +13 -1
  34. package/src/preprocessor.js +5 -1
  35. package/src/prototypes/collections.js +4 -3
  36. package/src/prototypes/scalars.js +4 -4
  37. package/src/prototypes/schema.js +6 -5
  38. package/src/prototypes/union.js +2 -2
  39. package/src/result.js +6 -0
  40. package/src/rules.js +53 -4
  41. package/src/schema.js +28 -7
  42. package/src/snapshot.js +111 -0
  43. package/src/stream/index.d.ts +68 -0
  44. package/src/stream/index.js +247 -0
  45. package/src/struct.js +64 -18
  46. package/src/types.js +14 -1
  47. package/src/util.js +18 -0
package/src/issues.js CHANGED
@@ -54,6 +54,7 @@ const issues = {
54
54
  length: (context, min, max, actual, key) => record(context, 'length', { min, max, actual }, key),
55
55
  range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
56
56
  pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
57
+ format: (context, format, key) => record(context, 'format', { format }, key),
57
58
  union: (context, expected, discriminator, key) =>
58
59
  record(context, 'union', { expected, discriminator }, key),
59
60
  reference: (context, entity, key) => record(context, 'reference', { entity }, key),
@@ -173,6 +174,16 @@ const abandon = (thenable) => {
173
174
  Promise.resolve(thenable).then(undefined, swallow);
174
175
  };
175
176
 
177
+ // Drops the entries of a list of pending validators from `from` on (a failed
178
+ // branch of a union, a trial of parse, a settle stopped by the error limit):
179
+ // their promises are observed, never awaited.
180
+ const release = (list, from) => {
181
+ for (let index = from; index < list.length; index += 1) {
182
+ if (list[index].promise !== null) abandon(list[index].promise);
183
+ }
184
+ list.length = from;
185
+ };
186
+
176
187
  // The params of a bare `false`: for a checkType the type it expected and what
177
188
  // it got, built only now that there is something to record.
178
189
  const fallbackOf = (code, owner, value) =>
@@ -185,20 +196,32 @@ const conclude = (context, output, code, owner, value) => {
185
196
  absorb(context, output, code, bare ? fallbackOf(code, owner, value) : EMPTY);
186
197
  };
187
198
 
199
+ // Whether a path lies under a prefix: the prefix itself, or a key below it.
200
+ const under = (prefix, path) => {
201
+ if (path.length < prefix.length) return false;
202
+ for (let index = 0; index < prefix.length; index += 1) {
203
+ if (path[index] !== prefix[index]) return false;
204
+ }
205
+ return true;
206
+ };
207
+
188
208
  // Where user code runs (a validator, a custom checkType; the decoders have
189
209
  // their own place in codec.js): an exception is reported as an issue, not
190
210
  // thrown, and the function gets the value and the dotted path of the field,
191
211
  // called on its owner here rather than through a closure made per call. In
192
212
  // an async check (`context.async` is a list) a promise is kept with the path
193
- // it was met at, and every validator after it is kept too, with what it needs
194
- // to be called, so that the rule "a validator runs only when nothing before
195
- // it failed" holds over the promises as well; `settle` runs the list after
196
- // the walk, in field order. In a synchronous check a promise is an error of
197
- // the call.
213
+ // it was met at, and a validator met later is kept too, uncalled, when a
214
+ // promise is pending under its path (the fields of the value it validates
215
+ // were met before it, so their entries are the end of the list), so that the
216
+ // rule "a validator runs only when nothing under it failed" holds over the
217
+ // promises as well; every other validator runs at once, as in check, and
218
+ // its promise is in flight with the rest. `settle` runs the list after the
219
+ // walk, in field order. In a synchronous check a promise is an error of the
220
+ // call.
198
221
  const guarded = (context, code, owner, fn, value) => {
199
222
  const pending = context.async;
200
223
  const { path, count } = context;
201
- if (pending !== null && pending.length > 0) {
224
+ if (pending !== null && pending.length > 0 && under(path, pending[pending.length - 1].path)) {
202
225
  pending.push({ owner, fn, value, promise: null, path: path.slice(), code, count });
203
226
  return;
204
227
  }
@@ -224,29 +247,22 @@ const guarded = (context, code, owner, fn, value) => {
224
247
  // path: the fields of the value it validates were checked before it.
225
248
  const failedUnder = (context, entry) => {
226
249
  const { issues: list } = context;
227
- const { path } = entry;
228
250
  for (let index = entry.count; index < list.length; index += 1) {
229
- const recorded = list[index].path;
230
- if (recorded.length < path.length) continue;
231
- let under = true;
232
- for (let depth = 0; depth < path.length && under; depth += 1) {
233
- under = recorded[depth] === path[depth];
234
- }
235
- if (under) return true;
251
+ if (under(entry.path, list[index].path)) return true;
236
252
  }
237
253
  return false;
238
254
  };
239
255
 
240
- // Runs the validators an async check kept, one after the other in the order
241
- // they were met, each recording under the path it was met at; the error
242
- // limit stops the list as it stops the walk.
256
+ // Settles the entries an async check kept, in the order they were met: a
257
+ // promise is awaited (it has been in flight since the walk), a validator kept
258
+ // uncalled is called once the promises under it have settled, each recording
259
+ // under the path it was met at; the error limit stops the list as it stops
260
+ // the walk.
243
261
  const settle = async (context) => {
244
262
  const pending = context.async;
245
263
  for (let index = 0; index < pending.length; index += 1) {
246
264
  if (context.count >= context.limit) {
247
- for (; index < pending.length; index += 1) {
248
- if (pending[index].promise !== null) abandon(pending[index].promise);
249
- }
265
+ release(pending, index);
250
266
  break;
251
267
  }
252
268
  const entry = pending[index];
@@ -285,6 +301,7 @@ module.exports = {
285
301
  describe,
286
302
  isThenable,
287
303
  abandon,
304
+ release,
288
305
  runValidate,
289
306
  runCheckType,
290
307
  settle,
package/src/lint.js CHANGED
@@ -26,19 +26,28 @@ const KNOWN = new Set([
26
26
  'description',
27
27
  'examples',
28
28
  'deprecated',
29
+ 'aliases',
29
30
  ]);
30
31
 
31
32
  const isCustom = (Type) => Type.source !== undefined && Type.source.js === undefined;
32
33
 
33
- const lintField = (field, path, warnings) => {
34
+ // `element` says the field is an element of a tuple, whose `name` is the
35
+ // name the tuple gave it (`[{ x: 'number' }]`), not an option; `member`
36
+ // that it is a field of a struct, the one place aliases are read from.
37
+ const lintField = (field, path, warnings, element = false, member = false) => {
34
38
  const Type = field.constructor;
35
39
  if (!isCustom(Type)) {
36
40
  for (const key of Object.keys(field)) {
37
41
  if (KNOWN.has(key) || Type.options.has(key)) continue;
42
+ if (element && key === 'name') continue;
38
43
  const text = `option "${key}" of "${path}" is not known to type "${field.type}"`;
39
44
  warnings.push(warning('unknown-option', text));
40
45
  }
41
46
  }
47
+ if (field.aliases !== undefined && !member) {
48
+ const text = `"${path}" has aliases, but only a field of a struct is read from them`;
49
+ warnings.push(warning('dead-aliases', text));
50
+ }
42
51
  if (field.pattern !== undefined && field.length?.max === undefined) {
43
52
  const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
44
53
  warnings.push(warning('unbounded-pattern', text));
@@ -48,7 +57,7 @@ const lintField = (field, path, warnings) => {
48
57
  if (value !== undefined) {
49
58
  if (Array.isArray(value)) {
50
59
  for (let index = 0; index < value.length; index += 1) {
51
- lintField(value[index], `${path}[${index}]`, warnings);
60
+ lintField(value[index], `${path}[${index}]`, warnings, true);
52
61
  }
53
62
  } else {
54
63
  lintField(value, `${path}[]`, warnings);
@@ -69,7 +78,7 @@ const lintStruct = (fields, prefix, warnings) => {
69
78
  for (const key of Object.keys(fields)) {
70
79
  const field = fields[key];
71
80
  if (!hasBrand(field, 'Type')) continue;
72
- lintField(field, prefix ? `${prefix}.${key}` : key, warnings);
81
+ lintField(field, prefix ? `${prefix}.${key}` : key, warnings, false, true);
73
82
  }
74
83
  };
75
84
 
package/src/locales/en.js CHANGED
@@ -10,10 +10,16 @@ const required = () => 'is required';
10
10
  const type = ({ expected, key }) =>
11
11
  key === undefined ? `not of expected type: ${expected}` : `keys must be of type ${expected}`;
12
12
 
13
+ // The first keys of the list and how many more there are: a value with a
14
+ // million keys the schema does not have is one issue, and its message is
15
+ // not the million keys.
16
+ const SHOWN = 10;
17
+
13
18
  const list = (keys) => {
19
+ const count = Math.min(keys.length, SHOWN);
14
20
  let text = shorten(keys[0]);
15
- for (let index = 1; index < keys.length; index += 1) text += `, ${shorten(keys[index])}`;
16
- return text;
21
+ for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
22
+ return keys.length > SHOWN ? `${text} and ${keys.length - SHOWN} more` : text;
17
23
  };
18
24
 
19
25
  const unexpected = ({ keys }) => `has unexpected keys: ${list(keys)}`;
@@ -28,6 +34,8 @@ const range = ({ min, max, actual }) =>
28
34
 
29
35
  const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
30
36
 
37
+ const format = ({ format: name }) => `is not a valid ${name}`;
38
+
31
39
  const union = ({ expected, discriminator }) =>
32
40
  discriminator === undefined
33
41
  ? `does not match any of: ${expected.join(', ')}`
@@ -52,6 +60,7 @@ module.exports = {
52
60
  length,
53
61
  range,
54
62
  pattern,
63
+ format,
55
64
  union,
56
65
  reference,
57
66
  circular,
package/src/locales/uk.js CHANGED
@@ -9,10 +9,15 @@ const required = () => 'є обовʼязковим';
9
9
  const type = ({ expected, key }) =>
10
10
  key === undefined ? `не відповідає типу: ${expected}` : `ключі мають бути типу ${expected}`;
11
11
 
12
+ // Перші ключі списку і скільки їх ще: значення з мільйоном невідомих ключів
13
+ // є одним issue, і його повідомлення не є цим мільйоном.
14
+ const SHOWN = 10;
15
+
12
16
  const list = (keys) => {
17
+ const count = Math.min(keys.length, SHOWN);
13
18
  let text = shorten(keys[0]);
14
- for (let index = 1; index < keys.length; index += 1) text += `, ${shorten(keys[index])}`;
15
- return text;
19
+ for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
20
+ return keys.length > SHOWN ? `${text} і ще ${keys.length - SHOWN}` : text;
16
21
  };
17
22
 
18
23
  const unexpected = ({ keys }) => `має неочікувані ключі: ${list(keys)}`;
@@ -27,6 +32,8 @@ const range = ({ min, max, actual }) =>
27
32
 
28
33
  const pattern = ({ pattern: source }) => `не відповідає шаблону ${source}`;
29
34
 
35
+ const format = ({ format: name }) => `не є коректним ${name}`;
36
+
30
37
  const union = ({ expected, discriminator }) =>
31
38
  discriminator === undefined
32
39
  ? `не відповідає жодному з: ${expected.join(', ')}`
@@ -51,6 +58,7 @@ module.exports = {
51
58
  length,
52
59
  range,
53
60
  pattern,
61
+ format,
54
62
  union,
55
63
  reference,
56
64
  circular,
package/src/metadata.js CHANGED
@@ -2,6 +2,7 @@ const { getKindMetadata } = require('./kinds.js');
2
2
  const { ValidationResult } = require('./result.js');
3
3
  const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
4
4
  const { isThenable } = require('./issues.js');
5
+ const { safeString } = require('./util.js');
5
6
 
6
7
  // The functions of a schema definition that are the schema's own: its
7
8
  // validate, its decoder, its serializer and `format`.
@@ -101,10 +102,10 @@ class SchemaMetadata {
101
102
  if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
102
103
  return result.add(output);
103
104
  } catch (error) {
104
- if (error.code === 'ERR_ASYNC_VALIDATOR') throw error;
105
+ if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
105
106
  return result.add({
106
107
  code: 'exception',
107
- message: `validation failed ${error}`,
108
+ message: `validation failed ${safeString(error)}`,
108
109
  params: { error },
109
110
  });
110
111
  }
@@ -0,0 +1,122 @@
1
+ // What the functions of the `./model` subpath share: a snapshot from a Model
2
+ // or as given, and equality of the JSON values a snapshot is made of. A
3
+ // snapshot is input (a file, a registry, another program), so what it says
4
+ // is checked before it is read, and every error is ERR_INVALID_SNAPSHOT
5
+ // located in the entity, never a bare SyntaxError or TypeError.
6
+ const { hasBrand, define } = require('../util.js');
7
+ const { FORMAT } = require('../snapshot.js');
8
+ const { SchemaDefinitionError } = require('../errors.js');
9
+ const { isStruct } = require('../struct.js');
10
+
11
+ // How deep the walks over a snapshot go: a definition nested deeper is not
12
+ // one a program wrote.
13
+ const DEPTH = 128;
14
+
15
+ const invalidSnapshot = (reason) => new SchemaDefinitionError('ERR_INVALID_SNAPSHOT', reason);
16
+
17
+ const tooDeep = () => invalidSnapshot(`A snapshot nested deeper than ${DEPTH} levels`);
18
+
19
+ // An error of a schema as a whole, which has no field to be located at: the
20
+ // schema is the location, written as `locate` writes one.
21
+ const atSchema = (error, name) => {
22
+ error.schema = name;
23
+ error.message = `${error.message} in "${name}"`;
24
+ return error;
25
+ };
26
+
27
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
28
+
29
+ const isSnapshot = (value) =>
30
+ isObject(value) &&
31
+ value.format === FORMAT &&
32
+ isObject(value.entities) &&
33
+ (value.types === undefined || isObject(value.types));
34
+
35
+ // The snapshot of a model, or the snapshot given.
36
+ const snapshotOf = (target) => {
37
+ if (hasBrand(target, 'Model')) return target.toJSON();
38
+ if (!isSnapshot(target)) {
39
+ throw invalidSnapshot(`A Model or a snapshot of format ${FORMAT} with entities is expected`);
40
+ }
41
+ return target;
42
+ };
43
+
44
+ // Whether two values of a definition are the same: the same primitives (a
45
+ // function by identity), the same elements in order, the same keys with the
46
+ // same values in any order; a RegExp by its text and a Date by its time, for
47
+ // the definitions `merge` compares (a snapshot holds neither).
48
+ const same = (a, b, depth = 0) => {
49
+ if (a === b) return true;
50
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
51
+ if (depth > DEPTH) throw tooDeep();
52
+ const name = a.constructor?.name;
53
+ if (name === 'RegExp' || name === 'Date') {
54
+ if (name !== b.constructor?.name) return false;
55
+ return name === 'Date'
56
+ ? a.getTime() === b.getTime()
57
+ : a.source === b.source && a.flags === b.flags;
58
+ }
59
+ if (Array.isArray(a)) {
60
+ if (!Array.isArray(b) || a.length !== b.length) return false;
61
+ for (let index = 0; index < a.length; index += 1) {
62
+ if (!same(a[index], b[index], depth + 1)) return false;
63
+ }
64
+ return true;
65
+ }
66
+ if (Array.isArray(b)) return false;
67
+ const keys = Object.keys(a);
68
+ if (keys.length !== Object.keys(b).length) return false;
69
+ for (const key of keys) {
70
+ if (!Object.hasOwn(b, key) || !same(a[key], b[key], depth + 1)) return false;
71
+ }
72
+ return true;
73
+ };
74
+
75
+ const isFunctionMarker = (value) => isObject(value) && value.$function === true;
76
+
77
+ const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
78
+
79
+ // The definition a built field was made from, with its nested fields as
80
+ // definitions and its functions kept: what `merge` unifies and `Schema`
81
+ // takes back.
82
+ const definitionOf = (field) => {
83
+ const def = { type: field.type };
84
+ for (const key of Object.keys(field)) {
85
+ if (key !== 'root' && key !== 'type' && field[key] !== undefined) {
86
+ define(def, key, partOf(field[key]));
87
+ }
88
+ }
89
+ return def;
90
+ };
91
+
92
+ const partOf = (value) => {
93
+ if (hasBrand(value, 'Type')) return definitionOf(value);
94
+ if (isStruct(value)) return structDefinitionOf(value);
95
+ if (Array.isArray(value)) {
96
+ const list = [];
97
+ for (const item of value) list.push(partOf(item));
98
+ return list;
99
+ }
100
+ return value;
101
+ };
102
+
103
+ const structDefinitionOf = (fields) => {
104
+ const def = {};
105
+ for (const key in fields) define(def, key, partOf(fields[key]));
106
+ return def;
107
+ };
108
+
109
+ module.exports = {
110
+ DEPTH,
111
+ invalidSnapshot,
112
+ tooDeep,
113
+ atSchema,
114
+ isObject,
115
+ isSnapshot,
116
+ snapshotOf,
117
+ same,
118
+ isFunctionMarker,
119
+ capitalize,
120
+ definitionOf,
121
+ structDefinitionOf,
122
+ };