@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.
- package/CHANGELOG.md +312 -1
- package/README.md +463 -17
- package/SECURITY.md +26 -7
- package/index.d.ts +338 -3
- package/package.json +42 -5
- package/src/codec.js +161 -73
- package/src/compile/code.js +1 -1
- package/src/compile/emit.js +60 -7
- package/src/compile/index.d.ts +6 -0
- package/src/compile/index.js +14 -3
- package/src/context.js +8 -9
- package/src/errors.js +18 -1
- package/src/formats/index.d.ts +19 -0
- package/src/formats/index.js +146 -0
- package/src/generators/fromjsonschema.js +517 -0
- package/src/generators/index.d.ts +19 -2
- package/src/generators/index.js +16 -10
- package/src/generators/jsonschema.js +2 -0
- package/src/issues.js +37 -20
- package/src/lint.js +12 -3
- package/src/locales/en.js +11 -2
- package/src/locales/uk.js +10 -2
- package/src/metadata.js +3 -2
- package/src/model/data.js +122 -0
- package/src/model/diff.js +439 -0
- package/src/model/index.d.ts +68 -0
- package/src/model/index.js +45 -0
- package/src/model/infer.js +483 -0
- package/src/model/merge.js +255 -0
- package/src/model/pattern.js +322 -0
- package/src/model/restore.js +226 -0
- package/src/model/sample.js +398 -0
- package/src/model.js +13 -1
- package/src/preprocessor.js +5 -1
- package/src/prototypes/collections.js +4 -3
- package/src/prototypes/scalars.js +4 -4
- package/src/prototypes/schema.js +6 -5
- package/src/prototypes/union.js +2 -2
- package/src/result.js +6 -0
- package/src/rules.js +53 -4
- package/src/schema.js +28 -7
- package/src/snapshot.js +111 -0
- package/src/stream/index.d.ts +68 -0
- package/src/stream/index.js +247 -0
- package/src/struct.js +64 -18
- package/src/types.js +14 -1
- package/src/util.js +18 -0
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
// The reverse of `sample` (`infer`): a definition that accepts every sample
|
|
2
|
+
// given, to bootstrap a model from documents that exist. One pass builds a
|
|
3
|
+
// summary of every place of the values (the kinds seen there, how often,
|
|
4
|
+
// the keys of records with their presence, the elements of lists), fusing
|
|
5
|
+
// the records of one place into one record with optional keys, as the
|
|
6
|
+
// schema inference of Baazizi et al. (EDBT 2017) does; the summary is then
|
|
7
|
+
// written as the most readable definition, and the definition is checked
|
|
8
|
+
// against every sample, so that what comes back is a schema the samples
|
|
9
|
+
// pass. The samples are input: the walk is bounded, no key is trusted, and
|
|
10
|
+
// what no type describes is `any` rather than an error.
|
|
11
|
+
const { define, IDENTIFIER, shorten } = require('../util.js');
|
|
12
|
+
const { Schema } = require('../schema.js');
|
|
13
|
+
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
14
|
+
const { readsAsStruct } = require('../types.js');
|
|
15
|
+
const { FORMATS } = require('../rules.js');
|
|
16
|
+
const { toDotPath, finalize } = require('../issues.js');
|
|
17
|
+
const en = require('../locales/en.js');
|
|
18
|
+
const { DEPTH, capitalize } = require('./data.js');
|
|
19
|
+
|
|
20
|
+
const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
|
|
21
|
+
|
|
22
|
+
const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
|
|
23
|
+
|
|
24
|
+
// The kinds a place may hold, a bit each: a place that held values of
|
|
25
|
+
// several kinds is a union of them, and null and undefined decide presence.
|
|
26
|
+
const NULL = 1;
|
|
27
|
+
const UNDEF = 2;
|
|
28
|
+
const BOOLEAN = 4;
|
|
29
|
+
const INTEGER = 8;
|
|
30
|
+
const FLOAT = 16;
|
|
31
|
+
const BIGINT = 32;
|
|
32
|
+
const STRING = 64;
|
|
33
|
+
const DATE = 128;
|
|
34
|
+
const LIST = 256;
|
|
35
|
+
const SET = 512;
|
|
36
|
+
const MAP = 1024;
|
|
37
|
+
const RECORD = 2048;
|
|
38
|
+
// An empty dictionary or Map was seen: a required one rejects it.
|
|
39
|
+
const BLANK = 4096;
|
|
40
|
+
// A value no type describes but `any`: a function, a symbol, an invalid Date.
|
|
41
|
+
const ANY = 8192;
|
|
42
|
+
|
|
43
|
+
const PRESENCE = NULL | UNDEF;
|
|
44
|
+
|
|
45
|
+
// How a key is written: a field, its presence (absent, undefined or null
|
|
46
|
+
// among its values) written as the language writes it.
|
|
47
|
+
const REQUIRED = 0;
|
|
48
|
+
const OPTIONAL = 1;
|
|
49
|
+
const NULLABLE = 2;
|
|
50
|
+
|
|
51
|
+
// The summary of one place: one shape for every node. `strings` is the
|
|
52
|
+
// distinct strings while there are few enough for an enum (undefined before
|
|
53
|
+
// the first, null once there are too many), `texts` how many strings there
|
|
54
|
+
// were, `formats` the registered formats every string so far passed
|
|
55
|
+
// (undefined before the first, null once none is left), `records` how many
|
|
56
|
+
// of the values were records (the presence of a key is counted against it).
|
|
57
|
+
const node = () => ({
|
|
58
|
+
bits: 0,
|
|
59
|
+
count: 0,
|
|
60
|
+
records: 0,
|
|
61
|
+
texts: 0,
|
|
62
|
+
keys: null,
|
|
63
|
+
item: null,
|
|
64
|
+
names: null,
|
|
65
|
+
entries: null,
|
|
66
|
+
strings: undefined,
|
|
67
|
+
formats: undefined,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// A place in the samples, for the errors: the keys of records, `[]` for
|
|
71
|
+
// the elements of a list or the entries of a Map.
|
|
72
|
+
const ITEM = Symbol('item');
|
|
73
|
+
|
|
74
|
+
const where = (state) => {
|
|
75
|
+
let text = '';
|
|
76
|
+
for (let index = 0; index < state.path.length; index += 1) {
|
|
77
|
+
const key = state.path[index];
|
|
78
|
+
if (key === ITEM) text += '[]';
|
|
79
|
+
else if (IDENTIFIER.test(key)) text += text === '' ? shorten(key) : `.${shorten(key)}`;
|
|
80
|
+
else text += `[${JSON.stringify(shorten(key))}]`;
|
|
81
|
+
}
|
|
82
|
+
return text;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const tooDeep = (state) =>
|
|
86
|
+
invalid(
|
|
87
|
+
'ERR_INFER_DEPTH',
|
|
88
|
+
`Sample ${state.index} nests deeper than ${state.maxDepth} levels at "${where(state)}" (a cycle?)`,
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
// The formats of a place narrow with every string: the candidates are the
|
|
92
|
+
// registered formats that infer (a format every word passes says not to),
|
|
93
|
+
// in the order they were registered, and a string drops the ones it fails.
|
|
94
|
+
const addFormats = (target, value, state) => {
|
|
95
|
+
if (target.formats === null) return;
|
|
96
|
+
if (target.formats === undefined) target.formats = state.candidates.slice();
|
|
97
|
+
const list = target.formats;
|
|
98
|
+
let kept = 0;
|
|
99
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
100
|
+
const name = list[index];
|
|
101
|
+
if (FORMATS[name].test(value)) {
|
|
102
|
+
list[kept] = name;
|
|
103
|
+
kept += 1;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
list.length = kept;
|
|
107
|
+
if (kept === 0) target.formats = null;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const addString = (target, value, state) => {
|
|
111
|
+
target.texts += 1;
|
|
112
|
+
if (state.candidates.length > 0) addFormats(target, value, state);
|
|
113
|
+
if (target.strings === null) return;
|
|
114
|
+
if (target.strings === undefined) target.strings = new Set();
|
|
115
|
+
target.strings.add(value);
|
|
116
|
+
if (target.strings.size > state.enum) target.strings = null;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const childOf = (target, key) => {
|
|
120
|
+
if (target.keys === null) target.keys = new Map();
|
|
121
|
+
let child = target.keys.get(key);
|
|
122
|
+
if (child === undefined) {
|
|
123
|
+
child = node();
|
|
124
|
+
target.keys.set(key, child);
|
|
125
|
+
}
|
|
126
|
+
return child;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const addItems = (target, items, state, depth) => {
|
|
130
|
+
if (target.item === null) target.item = node();
|
|
131
|
+
state.path.push(ITEM);
|
|
132
|
+
for (const item of items) add(target.item, item, state, depth + 1);
|
|
133
|
+
state.path.pop();
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// One value into the summary of its place. The tests are the ones the
|
|
137
|
+
// check makes (a Date by its constructor name and a valid time, a Set and a
|
|
138
|
+
// Map by name, an integer by Number.isInteger, the keys of a record by
|
|
139
|
+
// Object.keys), so what infer calls a date the check accepts as one.
|
|
140
|
+
const add = (target, value, state, depth) => {
|
|
141
|
+
target.count += 1;
|
|
142
|
+
if (value === null) {
|
|
143
|
+
target.bits |= NULL;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const type = typeof value;
|
|
147
|
+
if (type === 'string') {
|
|
148
|
+
target.bits |= STRING;
|
|
149
|
+
addString(target, value, state);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (type === 'number') {
|
|
153
|
+
target.bits |= Number.isInteger(value) ? INTEGER : FLOAT;
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (type === 'boolean') {
|
|
157
|
+
target.bits |= BOOLEAN;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (type === 'undefined') {
|
|
161
|
+
target.bits |= UNDEF;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (type === 'bigint') {
|
|
165
|
+
target.bits |= BIGINT;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (type !== 'object') {
|
|
169
|
+
target.bits |= ANY;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (depth >= state.maxDepth) throw tooDeep(state);
|
|
173
|
+
const name = value.constructor?.name;
|
|
174
|
+
if (name === 'Date' && typeof value.getTime === 'function') {
|
|
175
|
+
target.bits |= Number.isNaN(value.getTime()) ? ANY : DATE;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (Array.isArray(value)) {
|
|
179
|
+
target.bits |= LIST;
|
|
180
|
+
addItems(target, value, state, depth);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const iterable = typeof value[Symbol.iterator] === 'function';
|
|
184
|
+
if (name === 'Set' && iterable) {
|
|
185
|
+
target.bits |= SET;
|
|
186
|
+
addItems(target, value, state, depth);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (name === 'Map' && iterable) {
|
|
190
|
+
target.bits |= MAP;
|
|
191
|
+
if (value.size === 0) target.bits |= BLANK;
|
|
192
|
+
if (target.names === null) target.names = node();
|
|
193
|
+
if (target.entries === null) target.entries = node();
|
|
194
|
+
state.path.push(ITEM);
|
|
195
|
+
for (const pair of value) {
|
|
196
|
+
const key = typeof pair[0];
|
|
197
|
+
target.names.bits |= key === 'string' ? STRING : key === 'number' ? FLOAT : ANY;
|
|
198
|
+
add(target.entries, pair[1], state, depth + 1);
|
|
199
|
+
}
|
|
200
|
+
state.path.pop();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
target.bits |= RECORD;
|
|
204
|
+
target.records += 1;
|
|
205
|
+
const keys = Object.keys(value);
|
|
206
|
+
if (keys.length === 0) target.bits |= BLANK;
|
|
207
|
+
for (let index = 0; index < keys.length; index += 1) {
|
|
208
|
+
const key = keys[index];
|
|
209
|
+
state.path.push(key);
|
|
210
|
+
add(childOf(target, key), value[key], state, depth + 1);
|
|
211
|
+
state.path.pop();
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// The summary of one node into another, copies of the nodes under it: what
|
|
216
|
+
// the values of a dictionary share.
|
|
217
|
+
const fuse = (into, from, cap) => {
|
|
218
|
+
into.bits |= from.bits;
|
|
219
|
+
into.count += from.count;
|
|
220
|
+
into.records += from.records;
|
|
221
|
+
into.texts += from.texts;
|
|
222
|
+
if (from.keys !== null) {
|
|
223
|
+
for (const pair of from.keys) fuse(childOf(into, pair[0]), pair[1], cap);
|
|
224
|
+
}
|
|
225
|
+
if (from.item !== null) into.item = fuse(into.item ?? node(), from.item, cap);
|
|
226
|
+
if (from.names !== null) into.names = fuse(into.names ?? node(), from.names, cap);
|
|
227
|
+
if (from.entries !== null) into.entries = fuse(into.entries ?? node(), from.entries, cap);
|
|
228
|
+
if (from.strings === null || into.strings === null) into.strings = null;
|
|
229
|
+
else if (from.strings !== undefined) {
|
|
230
|
+
if (into.strings === undefined) into.strings = new Set();
|
|
231
|
+
for (const text of from.strings) into.strings.add(text);
|
|
232
|
+
if (into.strings.size > cap) into.strings = null;
|
|
233
|
+
}
|
|
234
|
+
// The formats both kept, in the order of the target.
|
|
235
|
+
if (from.formats === null || into.formats === null) into.formats = null;
|
|
236
|
+
else if (into.formats === undefined) into.formats = from.formats?.slice();
|
|
237
|
+
else if (from.formats !== undefined) {
|
|
238
|
+
const kept = [];
|
|
239
|
+
for (const name of into.formats) if (from.formats.includes(name)) kept.push(name);
|
|
240
|
+
into.formats = kept.length === 0 ? null : kept;
|
|
241
|
+
}
|
|
242
|
+
return into;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// A key a program would write as a field: a letter, a digit after it.
|
|
246
|
+
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
|
247
|
+
|
|
248
|
+
// Whether the records of a place are a dictionary rather than a struct: no
|
|
249
|
+
// key is a name (ids, dates, codes as keys, from one sample on), or there
|
|
250
|
+
// are more keys than `map` across several records, every key is missing
|
|
251
|
+
// from some record and the values are all of one kind.
|
|
252
|
+
const dictionary = (target, state) => {
|
|
253
|
+
const { keys } = target;
|
|
254
|
+
if (state.map === false || keys === null || keys.size === 0) return false;
|
|
255
|
+
let named = false;
|
|
256
|
+
for (const key of keys.keys()) {
|
|
257
|
+
if (NAME.test(key)) {
|
|
258
|
+
named = true;
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (!named) return true;
|
|
263
|
+
if (keys.size <= state.map || target.records < 2) return false;
|
|
264
|
+
let kinds = 0;
|
|
265
|
+
for (const child of keys.values()) {
|
|
266
|
+
if (child.count >= target.records) return false;
|
|
267
|
+
const bits = child.bits & ~PRESENCE;
|
|
268
|
+
kinds |= bits & INTEGER ? (bits & ~INTEGER) | FLOAT : bits;
|
|
269
|
+
}
|
|
270
|
+
return kinds !== 0 && (kinds & (kinds - 1)) === 0;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// The definition of a form with its presence: a type name is `?name` or
|
|
274
|
+
// `{ type, nullable }`, an object form takes `required: false` or
|
|
275
|
+
// `nullable: true`, a struct is bare only where it reads as one.
|
|
276
|
+
const written = (form, presence) => {
|
|
277
|
+
const { struct } = form;
|
|
278
|
+
if (struct !== undefined) {
|
|
279
|
+
if (presence === REQUIRED) return readsAsStruct(struct) ? struct : { schema: struct };
|
|
280
|
+
if (presence === OPTIONAL) return { schema: struct, required: false };
|
|
281
|
+
return { schema: struct, nullable: true };
|
|
282
|
+
}
|
|
283
|
+
const { def } = form;
|
|
284
|
+
if (typeof def === 'string') {
|
|
285
|
+
if (presence === REQUIRED) return def;
|
|
286
|
+
return presence === OPTIONAL ? `?${def}` : { type: def, nullable: true };
|
|
287
|
+
}
|
|
288
|
+
if (presence === OPTIONAL) def.required = false;
|
|
289
|
+
else if (presence === NULLABLE) def.nullable = true;
|
|
290
|
+
return def;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// A place that held nothing but null or undefined.
|
|
294
|
+
const bareOf = (bits, absent) => (bits & NULL ? (absent ? '?null' : 'null') : '?unknown');
|
|
295
|
+
|
|
296
|
+
// The element of a list, the value of a dictionary: `?type` when null or
|
|
297
|
+
// undefined was among them.
|
|
298
|
+
const itemOf = (target, state) => {
|
|
299
|
+
if (target === null || target.count === 0) return 'unknown';
|
|
300
|
+
const { bits } = target;
|
|
301
|
+
if ((bits & ~PRESENCE) === 0) return bareOf(bits, (bits & UNDEF) !== 0);
|
|
302
|
+
return written(formOf(target, state), bits & PRESENCE ? OPTIONAL : REQUIRED);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// An enum of few recurring values, else the first registered format every
|
|
306
|
+
// string of the place passed, else a string.
|
|
307
|
+
const stringOf = (target, state) => {
|
|
308
|
+
const { strings, texts, formats } = target;
|
|
309
|
+
if (strings != null && texts >= 4 && texts >= 2 * strings.size) {
|
|
310
|
+
return { def: { enum: Array.from(strings) } };
|
|
311
|
+
}
|
|
312
|
+
if (formats != null && formats.length > 0) return { def: { type: 'string', format: formats[0] } };
|
|
313
|
+
return { def: 'string' };
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const mapOf = (target, state) => {
|
|
317
|
+
const names = target.names === null ? 0 : target.names.bits;
|
|
318
|
+
let key = 'string';
|
|
319
|
+
if (names !== 0 && names !== STRING) {
|
|
320
|
+
if ((names & ~(INTEGER | FLOAT)) !== 0) return { def: 'json' };
|
|
321
|
+
key = 'number';
|
|
322
|
+
}
|
|
323
|
+
const def = { map: { [key]: itemOf(target.entries, state) } };
|
|
324
|
+
if (target.bits & BLANK) def.required = false;
|
|
325
|
+
return { def };
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
// A key of the data as a key of a definition: one ending in `?` would read
|
|
329
|
+
// as an optional key, so it is written with one more.
|
|
330
|
+
const nameOf = (key) => (key.endsWith('?') ? `${key}?` : key);
|
|
331
|
+
|
|
332
|
+
// A key of a struct: optional when some record lacks it or holds undefined,
|
|
333
|
+
// nullable when every record has it and some hold null.
|
|
334
|
+
const keyOf = (child, records, state) => {
|
|
335
|
+
const absent = child.count < records || (child.bits & UNDEF) !== 0;
|
|
336
|
+
const nul = (child.bits & NULL) !== 0;
|
|
337
|
+
if ((child.bits & ~PRESENCE) === 0) return bareOf(child.bits, absent);
|
|
338
|
+
return written(formOf(child, state), absent ? OPTIONAL : nul ? NULLABLE : REQUIRED);
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
const recordOf = (target, state) => {
|
|
342
|
+
if (dictionary(target, state)) {
|
|
343
|
+
const value = node();
|
|
344
|
+
for (const child of target.keys.values()) fuse(value, child, state.enum);
|
|
345
|
+
const def = { object: { string: itemOf(value, state) } };
|
|
346
|
+
if (target.bits & BLANK) def.required = false;
|
|
347
|
+
return { def };
|
|
348
|
+
}
|
|
349
|
+
const fields = {};
|
|
350
|
+
if (target.keys !== null) {
|
|
351
|
+
for (const pair of target.keys) {
|
|
352
|
+
define(fields, nameOf(pair[0]), keyOf(pair[1], target.records, state));
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return { struct: fields };
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// The form of a place from the kinds it held: one, or a union of them in a
|
|
359
|
+
// fixed order with the record last, since a struct accepts any object that
|
|
360
|
+
// is not an array and the Set, Map and Date branches must be tried first.
|
|
361
|
+
const formOf = (target, state) => {
|
|
362
|
+
const bits = target.bits & ~PRESENCE;
|
|
363
|
+
if (bits & ANY) return { def: 'any' };
|
|
364
|
+
const forms = [];
|
|
365
|
+
if (bits & BOOLEAN) forms.push({ def: 'boolean' });
|
|
366
|
+
if (bits & (INTEGER | FLOAT)) {
|
|
367
|
+
forms.push({ def: (bits & FLOAT) === 0 && state.integer ? 'integer' : 'number' });
|
|
368
|
+
}
|
|
369
|
+
if (bits & BIGINT) forms.push({ def: 'bigint' });
|
|
370
|
+
if (bits & STRING) forms.push(stringOf(target, state));
|
|
371
|
+
if (bits & DATE) forms.push({ def: 'date' });
|
|
372
|
+
if (bits & LIST) forms.push({ def: { array: itemOf(target.item, state) } });
|
|
373
|
+
if (bits & SET) forms.push({ def: { set: itemOf(target.item, state) } });
|
|
374
|
+
if (bits & MAP) forms.push(mapOf(target, state));
|
|
375
|
+
if (bits & RECORD) forms.push(recordOf(target, state));
|
|
376
|
+
if (forms.length === 0) return { def: 'unknown' };
|
|
377
|
+
if (forms.length === 1) return forms[0];
|
|
378
|
+
const union = [];
|
|
379
|
+
for (let index = 0; index < forms.length; index += 1) union.push(written(forms[index], REQUIRED));
|
|
380
|
+
return { def: { union } };
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
const mismatch = (state, index, issue) => {
|
|
384
|
+
finalize([issue], en);
|
|
385
|
+
const at = toDotPath(issue.path, state.name);
|
|
386
|
+
const error = invalid(
|
|
387
|
+
'ERR_INFER_MISMATCH',
|
|
388
|
+
`The inferred definition rejects sample ${index} at "${at}": ${issue.message}`,
|
|
389
|
+
);
|
|
390
|
+
error.index = index;
|
|
391
|
+
return error;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const option = (name, expected) => invalidOptions(`Infer option "${name}" must be ${expected}`);
|
|
395
|
+
|
|
396
|
+
const optionsOf = (options) => {
|
|
397
|
+
if (options === null || typeof options !== 'object') {
|
|
398
|
+
throw invalidOptions('Infer options must be an object');
|
|
399
|
+
}
|
|
400
|
+
const {
|
|
401
|
+
as = 'definition',
|
|
402
|
+
name = '',
|
|
403
|
+
kind = 'struct',
|
|
404
|
+
enum: cap = 8,
|
|
405
|
+
integer = true,
|
|
406
|
+
map = 16,
|
|
407
|
+
maxDepth = DEPTH,
|
|
408
|
+
formats = true,
|
|
409
|
+
} = options;
|
|
410
|
+
if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
|
|
411
|
+
if (typeof name !== 'string') throw option('name', 'a string');
|
|
412
|
+
if (typeof kind !== 'string' || kind === '') throw option('kind', 'the name of a kind');
|
|
413
|
+
if (cap !== false && (!Number.isInteger(cap) || cap < 0)) {
|
|
414
|
+
throw option('enum', 'an integer of at least 0, or false');
|
|
415
|
+
}
|
|
416
|
+
if (typeof integer !== 'boolean') throw option('integer', 'a boolean');
|
|
417
|
+
if (map !== false && (!Number.isInteger(map) || map < 1)) {
|
|
418
|
+
throw option('map', 'an integer of at least 1, or false');
|
|
419
|
+
}
|
|
420
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > DEPTH) {
|
|
421
|
+
throw option('maxDepth', `an integer from 1 to ${DEPTH}`);
|
|
422
|
+
}
|
|
423
|
+
if (typeof formats !== 'boolean') throw option('formats', 'a boolean');
|
|
424
|
+
const state = { as, name, kind, enum: cap === false ? 0 : cap, integer, map, maxDepth };
|
|
425
|
+
state.path = [];
|
|
426
|
+
state.index = 0;
|
|
427
|
+
// The formats a string place may be, in the order they were registered.
|
|
428
|
+
state.candidates = [];
|
|
429
|
+
if (formats) {
|
|
430
|
+
for (const key in FORMATS) if (FORMATS[key].infer !== false) state.candidates.push(key);
|
|
431
|
+
}
|
|
432
|
+
return state;
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
// The samples as a list, read twice (the summary, then the self-check). A
|
|
436
|
+
// string is iterable, over its characters, and surely a mistake.
|
|
437
|
+
const listOf = (samples) => {
|
|
438
|
+
const iterable =
|
|
439
|
+
samples !== null &&
|
|
440
|
+
samples !== undefined &&
|
|
441
|
+
typeof samples !== 'string' &&
|
|
442
|
+
typeof samples[Symbol.iterator] === 'function';
|
|
443
|
+
if (!iterable) throw invalidTarget('An iterable of samples is expected');
|
|
444
|
+
const list = Array.isArray(samples) ? samples : Array.from(samples);
|
|
445
|
+
if (list.length === 0) throw invalidTarget('At least one sample is expected');
|
|
446
|
+
return list;
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// A definition (or a Schema, with `as: 'schema'`) that accepts every
|
|
450
|
+
// sample. `options`: `as`, `name`, `kind` (the kind of a root that is a
|
|
451
|
+
// struct, 'struct'), `enum` (the most distinct strings of a place for an
|
|
452
|
+
// enum, 8), `integer` (whole numbers are `integer`, true), `map` (the keys
|
|
453
|
+
// past which records read as a dictionary, 16), `maxDepth` (128).
|
|
454
|
+
const infer = (samples, options = {}) => {
|
|
455
|
+
const state = optionsOf(options);
|
|
456
|
+
const list = listOf(samples);
|
|
457
|
+
const root = node();
|
|
458
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
459
|
+
state.index = index;
|
|
460
|
+
add(root, list[index], state, 0);
|
|
461
|
+
}
|
|
462
|
+
// A root of records is a struct with its kind; a root of records and
|
|
463
|
+
// null or undefined is a union of that one struct, since the `schema`
|
|
464
|
+
// shorthand at the root is the struct itself and cannot be optional.
|
|
465
|
+
let definition;
|
|
466
|
+
const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
|
|
467
|
+
const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
|
|
468
|
+
if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
|
|
469
|
+
else if (form.struct === undefined) definition = written(form, presence);
|
|
470
|
+
else if (presence === REQUIRED) {
|
|
471
|
+
definition = { [capitalize(state.kind)]: {} };
|
|
472
|
+
for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
|
|
473
|
+
} else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
|
|
474
|
+
const schema = new Schema(state.name, definition);
|
|
475
|
+
const check = { unknown: 'reject', maxErrors: 1 };
|
|
476
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
477
|
+
const result = schema.check(list[index], check);
|
|
478
|
+
if (!result.valid) throw mismatch(state, index, result.issues[0]);
|
|
479
|
+
}
|
|
480
|
+
return state.as === 'schema' ? schema : definition;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
module.exports = { infer };
|