@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
@@ -0,0 +1,247 @@
1
+ // The `./stream` subpath: a schema over a sequence of records. `checkEach`
2
+ // and `parseEach` run `check` or `parse` on every record of an iterable and
3
+ // yield `{ index, record, result }` in the order of the records; the async
4
+ // pair does the same over a sync or async iterable with `checkAsync` or
5
+ // `parseAsync`, keeping up to `concurrency` records in flight; `transform`
6
+ // is a TransformStream that lets the valid records (or their parsed values)
7
+ // through and reports the others. Kept out of the core entry so that a
8
+ // program that validates one value at a time does not carry it; `register()`
9
+ // installs the methods on Schema for the programs that want them.
10
+ const { hasBrand } = require('../util.js');
11
+ const { abandon } = require('../issues.js');
12
+ const { invalidTarget, invalidOption: invalid } = require('../errors.js');
13
+ const { Schema } = require('../schema.js');
14
+
15
+ const optionsOf = (options) => {
16
+ if (options === undefined || (options !== null && typeof options === 'object')) return options;
17
+ throw invalid('options', 'an object', options);
18
+ };
19
+
20
+ // How many invalid records end the iteration: a whole number, or no limit.
21
+ const limitOf = (options) => {
22
+ const limit = optionsOf(options)?.maxInvalid;
23
+ if (limit === undefined) return Infinity;
24
+ if ((Number.isInteger(limit) || limit === Infinity) && limit >= 1) return limit;
25
+ throw invalid('maxInvalid', 'an integer of at least 1', limit);
26
+ };
27
+
28
+ // How many records an async iteration keeps in flight: one unless asked.
29
+ const widthOf = (options) => {
30
+ const width = options?.concurrency;
31
+ if (width === undefined) return 1;
32
+ if (Number.isInteger(width) && width >= 1) return width;
33
+ throw invalid('concurrency', 'an integer of at least 1', width);
34
+ };
35
+
36
+ const modeOf = (options) => {
37
+ const mode = options?.mode;
38
+ if (mode === undefined) return 'parse';
39
+ if (mode === 'parse' || mode === 'check') return mode;
40
+ throw invalid('mode', '"parse" or "check"', mode);
41
+ };
42
+
43
+ const asyncOf = (options) => {
44
+ const async = options?.async;
45
+ if (async === undefined || typeof async === 'boolean') return async === true;
46
+ throw invalid('async', 'a boolean', async);
47
+ };
48
+
49
+ const callbackOf = (options) => {
50
+ const onInvalid = options?.onInvalid;
51
+ if (onInvalid === undefined || typeof onInvalid === 'function') return onInvalid;
52
+ throw invalid('onInvalid', 'a function', onInvalid);
53
+ };
54
+
55
+ const schemaOf = (schema) => {
56
+ if (!hasBrand(schema, 'Schema')) throw invalidTarget('A Schema is expected');
57
+ return schema;
58
+ };
59
+
60
+ // A sequence of records: anything with an iterator, or an async one where
61
+ // the iteration is async. A string is iterable and surely a mistake.
62
+ const recordsOf = (records, async) => {
63
+ const iterable =
64
+ records !== null &&
65
+ records !== undefined &&
66
+ typeof records !== 'string' &&
67
+ (typeof records[Symbol.iterator] === 'function' ||
68
+ (async && typeof records[Symbol.asyncIterator] === 'function'));
69
+ if (!iterable) throw invalidTarget('An iterable of records is expected');
70
+ return records;
71
+ };
72
+
73
+ // The method of the schema a function of the subpath runs on each record.
74
+ const CHECK = (schema, record, options) => schema.check(record, options);
75
+ const PARSE = (schema, record, options) => schema.parse(record, options);
76
+ const CHECK_ASYNC = (schema, record, options) => schema.checkAsync(record, options);
77
+ const PARSE_ASYNC = (schema, record, options) => schema.parseAsync(record, options);
78
+
79
+ // One record after the other. The entry of a record carries its position,
80
+ // since an iterator has none, and the record itself, since a stream cannot
81
+ // be read again. The options are handed to check or parse as given (they
82
+ // read the keys they know), so nothing is allocated per record beyond what
83
+ // the check itself allocates and the entry.
84
+ const each = function* (schema, records, options, limit, call) {
85
+ let failed = 0;
86
+ let index = 0;
87
+ for (const record of records) {
88
+ const result = call(schema, record, options);
89
+ yield { index, record, result };
90
+ index += 1;
91
+ if (!result.valid && (failed += 1) >= limit) return;
92
+ }
93
+ };
94
+
95
+ // The async pair over a sync or async iterable: up to `width` records are
96
+ // checked at once, the entries come out in the order of the records, and the
97
+ // promises still in flight when the iteration ends early (`maxInvalid`, a
98
+ // consumer that stops, a record whose parse throws) are observed, never
99
+ // awaited. The queue is as long as `width`, which is small by design.
100
+ const eachAsync = async function* (schema, records, options, limit, width, call) {
101
+ const queue = [];
102
+ let failed = 0;
103
+ let index = 0;
104
+ try {
105
+ for await (const record of records) {
106
+ const result = call(schema, record, options);
107
+ // Observed from the start: a record that rejects while an earlier one
108
+ // is still awaited would reject unhandled before its turn (the await
109
+ // of its entry still throws it).
110
+ abandon(result);
111
+ queue.push({ index, record, result });
112
+ index += 1;
113
+ if (queue.length < width) continue;
114
+ const entry = queue.shift();
115
+ entry.result = await entry.result;
116
+ yield entry;
117
+ if (!entry.result.valid && (failed += 1) >= limit) return;
118
+ }
119
+ while (queue.length > 0) {
120
+ const entry = queue.shift();
121
+ entry.result = await entry.result;
122
+ yield entry;
123
+ if (!entry.result.valid && (failed += 1) >= limit) return;
124
+ }
125
+ } finally {
126
+ for (let at = 0; at < queue.length; at += 1) abandon(queue[at].result);
127
+ }
128
+ };
129
+
130
+ const checkEach = (schema, records, options) =>
131
+ each(schemaOf(schema), recordsOf(records, false), options, limitOf(options), CHECK);
132
+
133
+ const parseEach = (schema, records, options) =>
134
+ each(schemaOf(schema), recordsOf(records, false), options, limitOf(options), PARSE);
135
+
136
+ const checkEachAsync = (schema, records, options) => {
137
+ const limit = limitOf(options);
138
+ return eachAsync(
139
+ schemaOf(schema),
140
+ recordsOf(records, true),
141
+ options,
142
+ limit,
143
+ widthOf(options),
144
+ CHECK_ASYNC,
145
+ );
146
+ };
147
+
148
+ const parseEachAsync = (schema, records, options) => {
149
+ const limit = limitOf(options);
150
+ return eachAsync(
151
+ schemaOf(schema),
152
+ recordsOf(records, true),
153
+ options,
154
+ limit,
155
+ widthOf(options),
156
+ PARSE_ASYNC,
157
+ );
158
+ };
159
+
160
+ // The error a stream ends with: the record, its position and its result
161
+ // travel on it, since the stream carries them no further.
162
+ const invalidRecord = (index, record, result) => {
163
+ const error = new TypeError(`Record ${index} is invalid`);
164
+ error.code = 'ERR_INVALID_RECORD';
165
+ error.index = index;
166
+ error.record = record;
167
+ error.result = result;
168
+ return error;
169
+ };
170
+
171
+ // A TransformStream over the records of a stream: a valid record goes on as
172
+ // its parsed value (or as it is, in `check` mode); an invalid one is handed
173
+ // to `onInvalid` and dropped, or ends the stream with the error when there
174
+ // is no `onInvalid` or `maxInvalid` is reached. A stream that ends looks
175
+ // complete to what reads it, so it cannot stop quietly as a generator does.
176
+ // The stream handles one record at a time, so the async methods settle in
177
+ // order too.
178
+ const transform = (schema, options) => {
179
+ schemaOf(schema);
180
+ const limit = limitOf(options);
181
+ const mode = modeOf(options);
182
+ const async = asyncOf(options);
183
+ const onInvalid = callbackOf(options);
184
+ const parse = mode === 'parse';
185
+ const call = async ? (parse ? PARSE_ASYNC : CHECK_ASYNC) : parse ? PARSE : CHECK;
186
+ let failed = 0;
187
+ let index = 0;
188
+ const settle = (record, result, controller) => {
189
+ const at = index;
190
+ index += 1;
191
+ if (result.valid) {
192
+ controller.enqueue(parse ? result.value : record);
193
+ return;
194
+ }
195
+ failed += 1;
196
+ if (onInvalid !== undefined) onInvalid(record, result, at);
197
+ if (onInvalid === undefined || failed >= limit) {
198
+ controller.error(invalidRecord(at, record, result));
199
+ }
200
+ };
201
+ return new TransformStream({
202
+ transform(record, controller) {
203
+ const result = call(schema, record, options);
204
+ if (!async) return settle(record, result, controller);
205
+ return result.then((settled) => settle(record, settled, controller));
206
+ },
207
+ });
208
+ };
209
+
210
+ // Installed like class members: not enumerable. A copy per subpath rather
211
+ // than a helper of the core: the core is measured on its own, the subpaths
212
+ // on top of it.
213
+ const install = (target, members) => {
214
+ const descriptors = Object.getOwnPropertyDescriptors(members);
215
+ for (const name in descriptors) {
216
+ descriptors[name].enumerable = false;
217
+ Object.defineProperty(target, name, descriptors[name]);
218
+ }
219
+ };
220
+
221
+ let registered = false;
222
+
223
+ // Adds `schema.checkEach`, `schema.parseEach`, `schema.checkEachAsync`,
224
+ // `schema.parseEachAsync` and `schema.transform`. Once per process.
225
+ const register = () => {
226
+ if (registered) return;
227
+ registered = true;
228
+ install(Schema.prototype, {
229
+ checkEach(records, options) {
230
+ return checkEach(this, records, options);
231
+ },
232
+ parseEach(records, options) {
233
+ return parseEach(this, records, options);
234
+ },
235
+ checkEachAsync(records, options) {
236
+ return checkEachAsync(this, records, options);
237
+ },
238
+ parseEachAsync(records, options) {
239
+ return parseEachAsync(this, records, options);
240
+ },
241
+ transform(options) {
242
+ return transform(this, options);
243
+ },
244
+ });
245
+ };
246
+
247
+ module.exports = { checkEach, parseEach, checkEachAsync, parseEachAsync, transform, register };
package/src/struct.js CHANGED
@@ -15,6 +15,18 @@ const STRUCT = Symbol.for('alexify.metaschema.struct');
15
15
  // fields, where a calculated field lives, but a value has no key by that name.
16
16
  const CODEC_KEYS = new Set(['validate', 'parse', 'serialize']);
17
17
 
18
+ const invalidAliases = (reason) => new SchemaDefinitionError('ERR_INVALID_DEFINITION', reason);
19
+
20
+ const ALIASES = 'Option "aliases" needs a list of key names';
21
+
22
+ // The key a value carries for a field that has nothing under its own key: a
23
+ // field renamed with `aliases: ['old']` is still read from its old key, and
24
+ // the field's own key when the value has none of them.
25
+ const aliasOf = (value, aliases, name) => {
26
+ for (const alias of aliases) if (Object.hasOwn(value, alias)) return alias;
27
+ return name;
28
+ };
29
+
18
30
  // A field is read with a keyed load, and `Object.hasOwn` is consulted only
19
31
  // when the value is undefined, to tell a missing key from one set to
20
32
  // undefined. A field named after a member of Object.prototype (`toString`,
@@ -37,6 +49,30 @@ const scanUnknown = (value, known, context) => {
37
49
  // never touches the path. Unknown keys are looked for only when the value has
38
50
  // more keys than the plan found, so a value with exactly the expected keys is
39
51
  // never scanned twice.
52
+ // A field with nothing under its own key (absent, inherited, or own and set
53
+ // to undefined): an alias may hold the value, and the check reports it under
54
+ // the key it found it under. Then the same for an optional field, a required
55
+ // one asks which (own and undefined is a type error). Kept out of the loop
56
+ // of the struct check, whose body is the fast path of a present field; the
57
+ // return is what the field adds to the keys found.
58
+ const checkAbsent = (entry, value, context, name) => {
59
+ const under = aliasOf(value, entry.aliases, name);
60
+ let item;
61
+ if (under !== name) {
62
+ item = value[under];
63
+ context.renamed = true;
64
+ }
65
+ if (item === undefined) {
66
+ if (!entry.required) return 0;
67
+ if (!Object.hasOwn(value, under)) {
68
+ issues.required(context, name);
69
+ return 0;
70
+ }
71
+ }
72
+ entry.check(item, context, under);
73
+ return 1;
74
+ };
75
+
40
76
  const compileStruct = (plan, known) => (value, context, key) => {
41
77
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
42
78
  issues.type(context, 'object', value, key);
@@ -50,20 +86,10 @@ const compileStruct = (plan, known) => (value, context, key) => {
50
86
  const entry = plan[index];
51
87
  const name = entry.key;
52
88
  const item = value[name];
53
- if (item === undefined) {
54
- // Absent, or own and set to undefined: the same for an optional field,
55
- // a required one asks which (the latter is a type error).
56
- if (!entry.required) continue;
57
- if (!Object.hasOwn(value, name)) {
58
- issues.required(context, name);
59
- continue;
60
- }
61
- } else if (entry.own && !Object.hasOwn(value, name)) {
62
- if (entry.required) issues.required(context, name);
63
- continue;
64
- }
65
- found += 1;
66
- entry.check(item, context, name);
89
+ if (item !== undefined && (!entry.own || Object.hasOwn(value, name))) {
90
+ found += 1;
91
+ entry.check(item, context, name);
92
+ } else found += checkAbsent(entry, value, context, name);
67
93
  }
68
94
  if (context.unknown === 'reject' && context.count < context.limit) {
69
95
  let total = 0;
@@ -74,6 +100,25 @@ const compileStruct = (plan, known) => (value, context, key) => {
74
100
  if (nested) context.path.pop();
75
101
  };
76
102
 
103
+ // A key a value may carry: a field, a calculated field or an alias, each
104
+ // once.
105
+ const know = (known, key) => {
106
+ if (key in known) throw invalidAliases(`Key "${key}" is a field or an alias already`);
107
+ known[key] = true;
108
+ };
109
+
110
+ // The aliases of a field: the keys it is also read from, as a list of names.
111
+ const aliasesOf = (field, known) => {
112
+ const { aliases } = field;
113
+ if (aliases === undefined) return [];
114
+ if (!Array.isArray(aliases) || aliases.length === 0) throw invalidAliases(ALIASES);
115
+ for (const alias of aliases) {
116
+ if (typeof alias !== 'string' || alias === '') throw invalidAliases(ALIASES);
117
+ know(known, alias);
118
+ }
119
+ return aliases;
120
+ };
121
+
77
122
  // A struct is a null-prototype dictionary of field name -> Type (or the
78
123
  // function of a calculated field), not a class instance with methods: a field
79
124
  // may be named `check`, `name` or `constructor`, and an input key such as
@@ -86,13 +131,13 @@ const createStruct = (defs, prep) => {
86
131
  const calculated = [];
87
132
  for (const key of Object.keys(defs)) {
88
133
  const entry = defs[key];
89
- const { field, required } = formatters.key(key, entry?.required);
134
+ const { field, required } = formatters.key(key);
90
135
  try {
91
136
  const { Type, defs: typeDefs } = prep.parse(entry);
92
137
  if (!Type) {
93
138
  fields[field] = entry;
94
139
  if (!CODEC_KEYS.has(field)) {
95
- known[field] = true;
140
+ know(known, field);
96
141
  calculated.push(field);
97
142
  }
98
143
  continue;
@@ -103,12 +148,13 @@ const createStruct = (defs, prep) => {
103
148
  typeDefs.required = (typeDefs.required ?? true) && required;
104
149
  const child = new Type(typeDefs, prep);
105
150
  fields[field] = child;
106
- known[field] = true;
151
+ know(known, field);
107
152
  plan.push({
108
153
  key: field,
109
154
  type: child,
110
155
  required: child.required,
111
156
  own: field in Object.prototype,
157
+ aliases: aliasesOf(child, known),
112
158
  check: child.check,
113
159
  });
114
160
  } catch (error) {
@@ -128,4 +174,4 @@ const isStruct = (fields) => hasBrand(fields, 'Struct');
128
174
 
129
175
  const checkOf = (fields) => fields[STRUCT].check;
130
176
 
131
- module.exports = { STRUCT, createStruct, isStruct, checkOf };
177
+ module.exports = { STRUCT, createStruct, isStruct, checkOf, aliasOf };
package/src/types.js CHANGED
@@ -7,6 +7,7 @@ const { tuple } = require('./prototypes/tuple.js');
7
7
  const { union } = require('./prototypes/union.js');
8
8
  const { json } = require('./prototypes/json.js');
9
9
  const { SchemaDefinitionError } = require('./errors.js');
10
+ const { firstKey, isFirstUpper } = require('./metautil.js');
10
11
 
11
12
  const PROTOTYPES = {
12
13
  ...scalars,
@@ -58,6 +59,18 @@ const TYPES = createTypes(PROTOTYPES);
58
59
 
59
60
  const createRegistry = () => createTypes(PROTOTYPES);
60
61
 
62
+ // Whether a dictionary of fields reads as a struct under the first-key rule
63
+ // (`preprocessor.js`): the first key that starts with a letter is a kind
64
+ // when capitalized, the long form when it is `type` and a shorthand when it
65
+ // is a type name of the registry; a struct that reads otherwise needs the
66
+ // `schema` shorthand around it. What generates a definition asks here.
67
+ const readsAsStruct = (fields, types = TYPES) => {
68
+ const first = firstKey(fields);
69
+ if (first === undefined) return true;
70
+ const key = first.endsWith('?') ? first.slice(0, -1) : first;
71
+ return key !== 'type' && types[key] === undefined && !isFirstUpper(key);
72
+ };
73
+
61
74
  // The own keys of the metadata given, as data: the table has no prototype.
62
75
  const updateTypeMetadata = (Type, metadata) => {
63
76
  Object.assign(Type.metadata, metadata);
@@ -124,4 +137,4 @@ const typeFactory = (customTypes, registry = TYPES) => {
124
137
  return registry;
125
138
  };
126
139
 
127
- module.exports = { TYPES, createRegistry, typeFactory };
140
+ module.exports = { TYPES, createRegistry, readsAsStruct, typeFactory };
package/src/util.js CHANGED
@@ -9,6 +9,21 @@ const INSPECT = Symbol.for('nodejs.util.inspect.custom');
9
9
 
10
10
  const hasBrand = (value, name) => value?.[BRAND] === name;
11
11
 
12
+ // A built-in is recognised by the name of its constructor, which nothing
13
+ // renames, and by its shape, which a value parsed from JSON cannot fake: an
14
+ // own key called `constructor` holding `{ name: 'Map' }` is data, and
15
+ // iterating such a value, or calling `getTime` on it, would throw out of a
16
+ // check. The name is tested first, since most values fail it at once.
17
+ const iterableNamed = (name) => (value) =>
18
+ value?.constructor?.name === name && typeof value[Symbol.iterator] === 'function';
19
+
20
+ const isMap = iterableNamed('Map');
21
+
22
+ const isSet = iterableNamed('Set');
23
+
24
+ const isDate = (value) =>
25
+ value?.constructor?.name === 'Date' && typeof value.getTime === 'function';
26
+
12
27
  // A JavaScript identifier: what generated code may write as `object.key` and
13
28
  // a TypeScript declaration as a bare name.
14
29
  const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
@@ -77,6 +92,9 @@ module.exports = {
77
92
  BRAND,
78
93
  INSPECT,
79
94
  hasBrand,
95
+ isMap,
96
+ isSet,
97
+ isDate,
80
98
  IDENTIFIER,
81
99
  define,
82
100
  RUN,