@alexify/metaschema 3.4.1 → 4.0.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 +162 -1
- package/README.md +22 -7
- package/SECURITY.md +5 -4
- package/index.d.ts +856 -460
- package/package.json +8 -6
- package/src/checks.js +72 -107
- package/src/codec.js +67 -58
- package/src/coerce/index.d.ts +31 -21
- package/src/coerce/index.js +64 -47
- package/src/compile/code.js +2 -2
- package/src/compile/emit.js +20 -31
- package/src/compile/index.d.ts +41 -25
- package/src/compile/index.js +45 -32
- package/src/context.js +10 -10
- package/src/definition/index.d.ts +10 -7
- package/src/definition/index.js +2 -1
- package/src/derive/index.d.ts +25 -17
- package/src/derive/index.js +14 -11
- package/src/errors.js +84 -59
- package/src/formats/index.d.ts +27 -21
- package/src/formats/index.js +15 -13
- package/src/generators/{fromjsonschema.js → from-json-schema.js} +170 -127
- package/src/generators/index.d.ts +23 -15
- package/src/generators/index.js +2 -2
- package/src/generators/{jsonschema.js → json-schema.js} +37 -43
- package/src/generators/typescript.js +9 -6
- package/src/index.js +2 -1
- package/src/issues.js +41 -42
- package/src/kinds.js +18 -16
- package/src/lint.js +15 -18
- package/src/locales/en.js +7 -7
- package/src/locales/uk.js +6 -6
- package/src/metadata.js +2 -2
- package/src/model/data.js +17 -20
- package/src/model/diff.js +29 -24
- package/src/model/index.d.ts +51 -35
- package/src/model/infer.js +69 -60
- package/src/model/merge.js +29 -18
- package/src/model/pattern.js +105 -102
- package/src/model/restore.js +24 -19
- package/src/model/sample.js +90 -100
- package/src/model.js +4 -2
- package/src/mongodb/bson.js +12 -12
- package/src/mongodb/document.js +7 -6
- package/src/mongodb/index.d.ts +54 -31
- package/src/mongodb/update.js +12 -9
- package/src/preprocessor.js +13 -13
- package/src/prototypes/abstract.js +8 -8
- package/src/prototypes/collections.js +7 -7
- package/src/prototypes/flags.js +1 -1
- package/src/prototypes/reference.js +3 -4
- package/src/prototypes/scalars.js +1 -1
- package/src/prototypes/schema.js +5 -6
- package/src/prototypes/tuple.js +6 -5
- package/src/prototypes/union.js +5 -4
- package/src/rules.js +23 -20
- package/src/runtime/browser.js +6 -1
- package/src/runtime/node.js +19 -2
- package/src/schema.js +15 -13
- package/src/snapshot.js +14 -12
- package/src/stream/index.d.ts +33 -21
- package/src/stream/index.js +37 -20
- package/src/struct.js +6 -6
- package/src/types.js +28 -22
- package/src/util.js +65 -64
- package/src/validation.js +10 -13
package/src/model/data.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// What the functions of the `./model` subpath share: a snapshot from a Model
|
|
2
2
|
// or as given, and equality of the JSON values a snapshot is made of. A
|
|
3
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
|
|
4
|
+
// is checked before it is read, and every error is ALX_ERR_INVALID_SNAPSHOT
|
|
5
5
|
// located in the entity, never a bare SyntaxError or TypeError.
|
|
6
6
|
const { hasBrand, define, isDate, isRegExp } = require('../util.js');
|
|
7
7
|
const { FORMAT } = require('../snapshot.js');
|
|
@@ -11,27 +11,24 @@ const { isKindKey } = require('../kinds.js');
|
|
|
11
11
|
|
|
12
12
|
// How deep the walks over a snapshot go: a definition nested deeper is not
|
|
13
13
|
// one a program wrote.
|
|
14
|
-
const
|
|
14
|
+
const MAX_DEPTH = 128;
|
|
15
15
|
|
|
16
|
-
const invalidSnapshot = (reason) =>
|
|
16
|
+
const invalidSnapshot = (reason, options) =>
|
|
17
|
+
new SchemaDefinitionError(reason, { ...options, code: 'ALX_ERR_INVALID_SNAPSHOT' });
|
|
17
18
|
|
|
18
|
-
const tooDeep = () => invalidSnapshot(`A snapshot nested deeper than ${
|
|
19
|
+
const tooDeep = () => invalidSnapshot(`A snapshot nested deeper than ${MAX_DEPTH} levels`);
|
|
19
20
|
|
|
20
|
-
// An error of
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
error.message = `${error.message} in "${name}"`;
|
|
25
|
-
return error;
|
|
26
|
-
};
|
|
21
|
+
// An error of another kind met while a snapshot is read (a bigint or a
|
|
22
|
+
// pattern that does not read throws its own): an error of the snapshot,
|
|
23
|
+
// with that error as its cause.
|
|
24
|
+
const unreadable = (error) => invalidSnapshot(error.message, { cause: error });
|
|
27
25
|
|
|
28
26
|
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
29
27
|
|
|
30
|
-
const isSnapshot = (value) =>
|
|
31
|
-
isObject(value)
|
|
32
|
-
value.
|
|
33
|
-
|
|
34
|
-
(value.types === undefined || isObject(value.types));
|
|
28
|
+
const isSnapshot = (value) => {
|
|
29
|
+
if (!isObject(value) || value.format !== FORMAT || !isObject(value.entities)) return false;
|
|
30
|
+
return value.types === undefined || isObject(value.types);
|
|
31
|
+
};
|
|
35
32
|
|
|
36
33
|
// The entity a snapshot of one schema is about, when it names one: a key
|
|
37
34
|
// format 1 gained in 3.4, read by nothing else.
|
|
@@ -61,7 +58,7 @@ const readSnapshot = (target) => {
|
|
|
61
58
|
const same = (a, b, depth = 0) => {
|
|
62
59
|
if (a === b) return true;
|
|
63
60
|
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
|
|
64
|
-
if (depth >
|
|
61
|
+
if (depth > MAX_DEPTH) throw tooDeep();
|
|
65
62
|
// By their shape, which a value of JSON cannot fake: `{ constructor: {
|
|
66
63
|
// name: 'Date' } }` of a snapshot is data.
|
|
67
64
|
const regExp = isRegExp(a);
|
|
@@ -142,7 +139,7 @@ const structDefinition = (base, metadata, fields) => {
|
|
|
142
139
|
const kindKey = kindKeyOf(kind);
|
|
143
140
|
if (kindKey === null) {
|
|
144
141
|
const reason = `Metadata "kind" must be the name of a kind, got ${JSON.stringify(kind)}`;
|
|
145
|
-
throw new SchemaDefinitionError('
|
|
142
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_INVALID_OPTIONS' });
|
|
146
143
|
}
|
|
147
144
|
const definition = { [kindKey]: rest };
|
|
148
145
|
for (const key of Object.keys(fields)) define(definition, key, fields[key]);
|
|
@@ -176,10 +173,10 @@ const namespacesOf = (schemas) => {
|
|
|
176
173
|
};
|
|
177
174
|
|
|
178
175
|
module.exports = {
|
|
179
|
-
|
|
176
|
+
MAX_DEPTH,
|
|
180
177
|
invalidSnapshot,
|
|
181
178
|
tooDeep,
|
|
182
|
-
|
|
179
|
+
unreadable,
|
|
183
180
|
isObject,
|
|
184
181
|
isSnapshot,
|
|
185
182
|
checkRoot,
|
package/src/model/diff.js
CHANGED
|
@@ -13,13 +13,28 @@
|
|
|
13
13
|
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
14
14
|
const {
|
|
15
15
|
invalidSnapshot,
|
|
16
|
-
|
|
16
|
+
unreadable,
|
|
17
17
|
isObject,
|
|
18
18
|
readSnapshot,
|
|
19
19
|
same,
|
|
20
20
|
isFunctionMarker,
|
|
21
21
|
} = require('./data.js');
|
|
22
22
|
|
|
23
|
+
const META = ['kind', 'scope', 'store', 'allow', 'parent', 'unknown', 'custom'];
|
|
24
|
+
|
|
25
|
+
// The keys of an entity whose change leaves no reader compatible.
|
|
26
|
+
const INCOMPATIBLE = new Set(['kind', 'store', 'parent', 'type']);
|
|
27
|
+
|
|
28
|
+
// The classes as bits, so that the class of several changes is the AND of
|
|
29
|
+
// theirs: backward and forward make full, either with its opposite makes
|
|
30
|
+
// none.
|
|
31
|
+
const NONE = 0;
|
|
32
|
+
const BACKWARD = 1;
|
|
33
|
+
const FORWARD = 2;
|
|
34
|
+
const FULL = 3;
|
|
35
|
+
|
|
36
|
+
const NAMES = ['none', 'backward', 'forward', 'full'];
|
|
37
|
+
|
|
23
38
|
const change = (kind, op, entity, name, from, to, detail) => {
|
|
24
39
|
const entry = { kind, op, entity, name };
|
|
25
40
|
if (from !== undefined) entry.from = from;
|
|
@@ -34,7 +49,9 @@ const own = (object, key) => (Object.hasOwn(object, key) ? object[key] : undefin
|
|
|
34
49
|
const keysOf = (a, b) => {
|
|
35
50
|
const keys = new Set(Object.keys(a));
|
|
36
51
|
for (const key of Object.keys(b)) keys.add(key);
|
|
37
|
-
|
|
52
|
+
const sorted = Array.from(keys);
|
|
53
|
+
sorted.sort();
|
|
54
|
+
return sorted;
|
|
38
55
|
};
|
|
39
56
|
|
|
40
57
|
// The keys whose values differ between two objects, sorted.
|
|
@@ -136,8 +153,6 @@ const diffRelations = (entity, old, current, changes) => {
|
|
|
136
153
|
}
|
|
137
154
|
};
|
|
138
155
|
|
|
139
|
-
const META = ['kind', 'scope', 'store', 'allow', 'parent', 'unknown', 'custom'];
|
|
140
|
-
|
|
141
156
|
// The metadata of an entity; a schema of one type is its type, so a struct
|
|
142
157
|
// that became one (or back) differs in `type`.
|
|
143
158
|
const metaOf = (entity) => {
|
|
@@ -157,7 +172,7 @@ const isRelations = (list) => {
|
|
|
157
172
|
// object: a definition or a function marker) or a `type`, and the relations
|
|
158
173
|
// as a list of objects, when there.
|
|
159
174
|
const checkEntity = (entity, name) => {
|
|
160
|
-
const fail = (reason) =>
|
|
175
|
+
const fail = (reason) => invalidSnapshot(reason).locate(name, '');
|
|
161
176
|
if (!isObject(entity)) throw fail('An entity of a snapshot must be an object');
|
|
162
177
|
const { fields, type, relations = [] } = entity;
|
|
163
178
|
if (!isObject(fields === undefined ? type : fields) || !isRelations(relations)) {
|
|
@@ -205,16 +220,6 @@ const diff = (prev, next) => {
|
|
|
205
220
|
return changes;
|
|
206
221
|
};
|
|
207
222
|
|
|
208
|
-
// The classes as bits, so that the class of several changes is the AND of
|
|
209
|
-
// theirs: backward and forward make full, either with its opposite makes
|
|
210
|
-
// none.
|
|
211
|
-
const NONE = 0;
|
|
212
|
-
const BACKWARD = 1;
|
|
213
|
-
const FORWARD = 2;
|
|
214
|
-
const FULL = 3;
|
|
215
|
-
|
|
216
|
-
const NAMES = ['none', 'backward', 'forward', 'full'];
|
|
217
|
-
|
|
218
223
|
// A field a reader may do without: an optional one, or one with a default
|
|
219
224
|
// the reader fills in.
|
|
220
225
|
const optional = (field) => field.required === false || field.default !== undefined;
|
|
@@ -330,7 +335,8 @@ const keyLevel = (key, from, to, field) => {
|
|
|
330
335
|
return boundLevel(from, to, false);
|
|
331
336
|
case 'pattern':
|
|
332
337
|
case 'format':
|
|
333
|
-
|
|
338
|
+
if (from === undefined) return FORWARD;
|
|
339
|
+
return to === undefined ? BACKWARD : NONE;
|
|
334
340
|
case 'enum':
|
|
335
341
|
case 'flags':
|
|
336
342
|
return Array.isArray(from) && Array.isArray(to) ? enumLevel(from, to) : NONE;
|
|
@@ -384,7 +390,7 @@ const entityLevel = (entry) => {
|
|
|
384
390
|
if (op === 'removed') return BACKWARD;
|
|
385
391
|
let level = FULL;
|
|
386
392
|
for (const key of detail.keys) {
|
|
387
|
-
if (key
|
|
393
|
+
if (INCOMPATIBLE.has(key)) level &= NONE;
|
|
388
394
|
else if (key === 'unknown') level &= to.unknown === 'ignore' ? BACKWARD : FORWARD;
|
|
389
395
|
}
|
|
390
396
|
return level;
|
|
@@ -409,11 +415,10 @@ const levelOf = (entry) => {
|
|
|
409
415
|
|
|
410
416
|
// What a change carries, as `diff` writes it: a kind and an op, and the
|
|
411
417
|
// keys that differ for `changed`.
|
|
412
|
-
const isChange = (entry) =>
|
|
413
|
-
isObject(entry) &&
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
(entry.op !== 'changed' || Array.isArray(entry.detail?.keys));
|
|
418
|
+
const isChange = (entry) => {
|
|
419
|
+
const named = isObject(entry) && typeof entry.kind === 'string' && typeof entry.op === 'string';
|
|
420
|
+
return named && (entry.op !== 'changed' || Array.isArray(entry.detail?.keys));
|
|
421
|
+
};
|
|
417
422
|
|
|
418
423
|
// The class of a change as bits. Whatever fails while its definitions are
|
|
419
424
|
// read (a bigint that does not read, a nesting the stack cannot take) is an
|
|
@@ -423,7 +428,7 @@ const classOf = (entry) => {
|
|
|
423
428
|
try {
|
|
424
429
|
return levelOf(entry);
|
|
425
430
|
} catch (error) {
|
|
426
|
-
const located = error instanceof SchemaDefinitionError ? error :
|
|
431
|
+
const located = error instanceof SchemaDefinitionError ? error : unreadable(error);
|
|
427
432
|
throw located.locate(entry.entity, entry.name);
|
|
428
433
|
}
|
|
429
434
|
};
|
|
@@ -439,4 +444,4 @@ const compatibility = (changes) => {
|
|
|
439
444
|
return NAMES[level];
|
|
440
445
|
};
|
|
441
446
|
|
|
442
|
-
module.exports = { diff,
|
|
447
|
+
module.exports = { diff, compatibilityOf, compatibility };
|
package/src/model/index.d.ts
CHANGED
|
@@ -12,57 +12,73 @@ import type {
|
|
|
12
12
|
SchemaChange,
|
|
13
13
|
} from '../../index.js';
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
/**
|
|
16
|
+
* The model of a snapshot (`model.toJSON()`), with placeholders for the
|
|
17
|
+
* functions, listed by path in `placeholders`; `options.types` brings the
|
|
18
|
+
* real custom types, the registry is 'isolated' unless `options.registry`
|
|
19
|
+
* says otherwise (a shared one takes no placeholder type). A snapshot that
|
|
20
|
+
* does not read is `ALX_ERR_INVALID_SNAPSHOT`, located in its entity.
|
|
21
|
+
*/
|
|
20
22
|
export function fromJSON(snapshot: ModelSnapshot, options?: RestoreOptions): RestoredModel;
|
|
21
23
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
24
|
+
/**
|
|
25
|
+
* The changes from `prev` to `next`, each a Model or a snapshot: the
|
|
26
|
+
* entities of `next` in their order (added, or their changes: fields,
|
|
27
|
+
* indexes, relations), the entities that are gone, then the types.
|
|
28
|
+
*/
|
|
25
29
|
export function diff(prev: Model | ModelSnapshot, next: Model | ModelSnapshot): SchemaChange[];
|
|
26
30
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The compatibility class of a list of changes by the rules of the Confluent
|
|
33
|
+
* Schema Registry: 'backward' when a reader with the new model reads data
|
|
34
|
+
* written with the old one, 'forward' the other way, 'full' when both,
|
|
35
|
+
* 'none' when neither.
|
|
36
|
+
*/
|
|
31
37
|
export function compatibility(changes: SchemaChange[]): Compatibility;
|
|
32
38
|
|
|
33
|
-
|
|
34
|
-
|
|
39
|
+
/**
|
|
40
|
+
* The compatibility class of one change, by the same rules: what to filter
|
|
41
|
+
* a list of changes by.
|
|
42
|
+
*/
|
|
35
43
|
export function compatibilityOf(change: SchemaChange): Compatibility;
|
|
36
44
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
45
|
+
/**
|
|
46
|
+
* A value the schema accepts, the same for a seed: every field is drawn
|
|
47
|
+
* from its definition and verified with its own check. A definition no
|
|
48
|
+
* value satisfies is `ALX_ERR_UNSATISFIABLE`, a pattern the sampler cannot read
|
|
49
|
+
* `ALX_ERR_SAMPLE_PATTERN`, a custom type without `metadata.sample`
|
|
50
|
+
* `ALX_ERR_SAMPLE_TYPE`.
|
|
51
|
+
*/
|
|
42
52
|
export function sample<D extends string | object>(
|
|
43
53
|
schema: Schema<D>,
|
|
44
54
|
options?: SampleOptions,
|
|
45
55
|
): Infer<D>;
|
|
46
56
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
57
|
+
/**
|
|
58
|
+
* The schema both schemas describe, by unification: a field in both takes
|
|
59
|
+
* the constraints of both, a field in one comes as it is, and what no value
|
|
60
|
+
* can satisfy (two types, two patterns, bounds with nothing in common, two
|
|
61
|
+
* defaults) is `ALX_ERR_MERGE_CONFLICT` with the field. The kind, its metadata
|
|
62
|
+
* and the name are the first schema's unless the options say otherwise.
|
|
63
|
+
*/
|
|
52
64
|
export function merge(a: Schema, b: Schema, options?: MergeOptions): Schema;
|
|
53
65
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
66
|
+
/**
|
|
67
|
+
* A definition (or a Schema, with `as: 'schema'`) that accepts every sample:
|
|
68
|
+
* the kinds seen at every place, the records of a place fused into one
|
|
69
|
+
* struct with optional keys, a string field of few values as an enum,
|
|
70
|
+
* records of many sparse keys as a dictionary, whole numbers as `integer`.
|
|
71
|
+
* The samples are input: the walk is bounded (`ALX_ERR_INFER_DEPTH`), and the
|
|
72
|
+
* definition is checked against every sample before it is returned
|
|
73
|
+
* (`ALX_ERR_INFER_MISMATCH` is a bug to report). An argument that is not a
|
|
74
|
+
* non-empty iterable is a `SchemaUsageError` with the code `ALX_ERR_INVALID_TARGET`.
|
|
75
|
+
*/
|
|
62
76
|
export function infer(samples: Iterable<unknown>, options: InferOptions & { as: 'schema' }): Schema;
|
|
63
77
|
export function infer(samples: Iterable<unknown>, options?: InferOptions): object | string;
|
|
64
78
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Installs `Model.fromJSON`, `Model.diff`, `Model.compatibility`,
|
|
81
|
+
* `Model.compatibilityOf`, `Schema.merge`, `Schema.infer` and
|
|
82
|
+
* `schema.sample`. Once per process; later calls do nothing.
|
|
83
|
+
*/
|
|
68
84
|
export function register(): void;
|
package/src/model/infer.js
CHANGED
|
@@ -10,16 +10,12 @@
|
|
|
10
10
|
// what no type describes is `any` rather than an error.
|
|
11
11
|
const { define, IDENTIFIER, shorten, isBytes } = require('../util.js');
|
|
12
12
|
const { Schema } = require('../validation.js');
|
|
13
|
-
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
13
|
+
const { SchemaDefinitionError, SchemaUsageError, invalidTarget } = require('../errors.js');
|
|
14
14
|
const { readsAsStruct } = require('../types.js');
|
|
15
15
|
const { FORMATS } = require('../rules.js');
|
|
16
16
|
const { toDotPath, finalize } = require('../issues.js');
|
|
17
17
|
const en = require('../locales/en.js');
|
|
18
|
-
const {
|
|
19
|
-
|
|
20
|
-
const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
|
|
21
|
-
|
|
22
|
-
const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
|
|
18
|
+
const { MAX_DEPTH, kindKeyOf } = require('./data.js');
|
|
23
19
|
|
|
24
20
|
// The kinds a place may hold, a bit each: a place that held values of
|
|
25
21
|
// several kinds is a union of them, and null and undefined decide presence.
|
|
@@ -43,12 +39,25 @@ const BYTES = 16384;
|
|
|
43
39
|
|
|
44
40
|
const PRESENCE = NULL | UNDEF;
|
|
45
41
|
|
|
42
|
+
// The bit of the type of a key of a Map.
|
|
43
|
+
const KEY_BITS = { string: STRING, number: FLOAT };
|
|
44
|
+
|
|
46
45
|
// How a key is written: a field, its presence (absent, undefined or null
|
|
47
46
|
// among its values) written as the language writes it.
|
|
48
47
|
const REQUIRED = 0;
|
|
49
48
|
const OPTIONAL = 1;
|
|
50
49
|
const NULLABLE = 2;
|
|
51
50
|
|
|
51
|
+
// A place in the samples, for the errors: the keys of records, `[]` for
|
|
52
|
+
// the elements of a list or the entries of a Map.
|
|
53
|
+
const ITEM = Symbol('item');
|
|
54
|
+
|
|
55
|
+
// A key a program would write as a field: a letter, a digit after it.
|
|
56
|
+
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
|
57
|
+
|
|
58
|
+
// An option of the call that is not what it must be: the call is wrong.
|
|
59
|
+
const wrongOption = (reason) => new SchemaUsageError(reason, { code: 'ALX_ERR_INVALID_OPTION' });
|
|
60
|
+
|
|
52
61
|
// The summary of one place: one shape for every node. `strings` is the
|
|
53
62
|
// distinct strings while there are few enough for an enum (undefined before
|
|
54
63
|
// the first, null once there are too many), `texts` how many strings there
|
|
@@ -68,10 +77,6 @@ const node = () => ({
|
|
|
68
77
|
formats: undefined,
|
|
69
78
|
});
|
|
70
79
|
|
|
71
|
-
// A place in the samples, for the errors: the keys of records, `[]` for
|
|
72
|
-
// the elements of a list or the entries of a Map.
|
|
73
|
-
const ITEM = Symbol('item');
|
|
74
|
-
|
|
75
80
|
const where = (state) => {
|
|
76
81
|
let text = '';
|
|
77
82
|
for (let index = 0; index < state.path.length; index += 1) {
|
|
@@ -83,11 +88,11 @@ const where = (state) => {
|
|
|
83
88
|
return text;
|
|
84
89
|
};
|
|
85
90
|
|
|
86
|
-
const tooDeep = (state) =>
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
const tooDeep = (state) => {
|
|
92
|
+
const levels = `${state.maxDepth} levels at "${where(state)}"`;
|
|
93
|
+
const message = `Sample ${state.index} nests deeper than ${levels} (a cycle?)`;
|
|
94
|
+
return new SchemaDefinitionError(message, { code: 'ALX_ERR_INFER_DEPTH' });
|
|
95
|
+
};
|
|
91
96
|
|
|
92
97
|
// The formats of a place narrow with every string: the candidates are the
|
|
93
98
|
// registered formats that infer (a format every word passes says not to),
|
|
@@ -148,8 +153,7 @@ const add = (target, value, state, depth) => {
|
|
|
148
153
|
const type = typeof value;
|
|
149
154
|
if (type === 'string') {
|
|
150
155
|
target.bits |= STRING;
|
|
151
|
-
addString(target, value, state);
|
|
152
|
-
return;
|
|
156
|
+
return void addString(target, value, state);
|
|
153
157
|
}
|
|
154
158
|
if (type === 'number') {
|
|
155
159
|
target.bits |= Number.isInteger(value) ? INTEGER : FLOAT;
|
|
@@ -179,8 +183,7 @@ const add = (target, value, state, depth) => {
|
|
|
179
183
|
}
|
|
180
184
|
if (Array.isArray(value)) {
|
|
181
185
|
target.bits |= LIST;
|
|
182
|
-
addItems(target, value, state, depth);
|
|
183
|
-
return;
|
|
186
|
+
return void addItems(target, value, state, depth);
|
|
184
187
|
}
|
|
185
188
|
if (isBytes(value)) {
|
|
186
189
|
target.bits |= BYTES;
|
|
@@ -189,8 +192,7 @@ const add = (target, value, state, depth) => {
|
|
|
189
192
|
const iterable = typeof value[Symbol.iterator] === 'function';
|
|
190
193
|
if (name === 'Set' && iterable) {
|
|
191
194
|
target.bits |= SET;
|
|
192
|
-
addItems(target, value, state, depth);
|
|
193
|
-
return;
|
|
195
|
+
return void addItems(target, value, state, depth);
|
|
194
196
|
}
|
|
195
197
|
if (name === 'Map' && iterable) {
|
|
196
198
|
target.bits |= MAP;
|
|
@@ -200,11 +202,10 @@ const add = (target, value, state, depth) => {
|
|
|
200
202
|
state.path.push(ITEM);
|
|
201
203
|
for (const pair of value) {
|
|
202
204
|
const key = typeof pair[0];
|
|
203
|
-
target.names.bits |= key
|
|
205
|
+
target.names.bits |= KEY_BITS[key] ?? ANY;
|
|
204
206
|
add(target.entries, pair[1], state, depth + 1);
|
|
205
207
|
}
|
|
206
|
-
state.path.pop();
|
|
207
|
-
return;
|
|
208
|
+
return void state.path.pop();
|
|
208
209
|
}
|
|
209
210
|
target.bits |= RECORD;
|
|
210
211
|
target.records += 1;
|
|
@@ -248,9 +249,6 @@ const fuse = (into, from, cap) => {
|
|
|
248
249
|
return into;
|
|
249
250
|
};
|
|
250
251
|
|
|
251
|
-
// A key a program would write as a field: a letter, a digit after it.
|
|
252
|
-
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
|
253
|
-
|
|
254
252
|
// Whether the records of a place are a dictionary rather than a struct: no
|
|
255
253
|
// key is a name (ids, dates, codes as keys, from one sample on), or there
|
|
256
254
|
// are more keys than `map` across several records, every key is missing
|
|
@@ -297,7 +295,10 @@ const written = (form, presence) => {
|
|
|
297
295
|
};
|
|
298
296
|
|
|
299
297
|
// A place that held nothing but null or undefined.
|
|
300
|
-
const bareOf = (bits, absent) =>
|
|
298
|
+
const bareOf = (bits, absent) => {
|
|
299
|
+
if ((bits & NULL) === 0) return '?unknown';
|
|
300
|
+
return absent ? '?null' : 'null';
|
|
301
|
+
};
|
|
301
302
|
|
|
302
303
|
// The element of a list, the value of a dictionary: `?type` when null or
|
|
303
304
|
// undefined was among them.
|
|
@@ -312,10 +313,12 @@ const itemOf = (target, state) => {
|
|
|
312
313
|
// string of the place passed, else a string.
|
|
313
314
|
const stringOf = (target, state) => {
|
|
314
315
|
const { strings, texts, formats } = target;
|
|
315
|
-
|
|
316
|
+
const counted = strings !== undefined && strings !== null;
|
|
317
|
+
if (counted && texts >= 4 && texts >= 2 * strings.size) {
|
|
316
318
|
return { def: { enum: Array.from(strings) } };
|
|
317
319
|
}
|
|
318
|
-
|
|
320
|
+
const formatted = formats !== undefined && formats !== null && formats.length > 0;
|
|
321
|
+
if (formatted) return { def: { type: 'string', format: formats[0] } };
|
|
319
322
|
return { def: 'string' };
|
|
320
323
|
};
|
|
321
324
|
|
|
@@ -335,13 +338,18 @@ const mapOf = (target, state) => {
|
|
|
335
338
|
// as an optional key, so it is written with one more.
|
|
336
339
|
const nameOf = (key) => (key.endsWith('?') ? `${key}?` : key);
|
|
337
340
|
|
|
341
|
+
const presenceOf = (absent, nul) => {
|
|
342
|
+
if (absent) return OPTIONAL;
|
|
343
|
+
return nul ? NULLABLE : REQUIRED;
|
|
344
|
+
};
|
|
345
|
+
|
|
338
346
|
// A key of a struct: optional when some record lacks it or holds undefined,
|
|
339
347
|
// nullable when every record has it and some hold null.
|
|
340
348
|
const keyOf = (child, records, state) => {
|
|
341
349
|
const absent = child.count < records || (child.bits & UNDEF) !== 0;
|
|
342
350
|
const nul = (child.bits & NULL) !== 0;
|
|
343
351
|
if ((child.bits & ~PRESENCE) === 0) return bareOf(child.bits, absent);
|
|
344
|
-
return written(formOf(child, state), absent
|
|
352
|
+
return written(formOf(child, state), presenceOf(absent, nul));
|
|
345
353
|
};
|
|
346
354
|
|
|
347
355
|
const recordOf = (target, state) => {
|
|
@@ -390,19 +398,15 @@ const formOf = (target, state) => {
|
|
|
390
398
|
const mismatch = (state, index, issue) => {
|
|
391
399
|
finalize([issue], en);
|
|
392
400
|
const at = toDotPath(issue.path, state.name);
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
`The inferred definition rejects sample ${index} at "${at}": ${issue.message}`,
|
|
396
|
-
);
|
|
397
|
-
error.index = index;
|
|
398
|
-
return error;
|
|
401
|
+
const message = `The inferred definition rejects sample ${index} at "${at}": ${issue.message}`;
|
|
402
|
+
return new SchemaDefinitionError(message, { code: 'ALX_ERR_INFER_MISMATCH', index });
|
|
399
403
|
};
|
|
400
404
|
|
|
401
|
-
const option = (name, expected) =>
|
|
405
|
+
const option = (name, expected) => wrongOption(`Infer option "${name}" must be ${expected}`);
|
|
402
406
|
|
|
403
407
|
const optionsOf = (options) => {
|
|
404
408
|
if (options === null || typeof options !== 'object') {
|
|
405
|
-
throw
|
|
409
|
+
throw wrongOption('Infer options must be an object');
|
|
406
410
|
}
|
|
407
411
|
const {
|
|
408
412
|
as = 'definition',
|
|
@@ -411,7 +415,7 @@ const optionsOf = (options) => {
|
|
|
411
415
|
enum: cap = 8,
|
|
412
416
|
integer = true,
|
|
413
417
|
map = 16,
|
|
414
|
-
maxDepth =
|
|
418
|
+
maxDepth = MAX_DEPTH,
|
|
415
419
|
formats = true,
|
|
416
420
|
} = options;
|
|
417
421
|
if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
|
|
@@ -424,8 +428,8 @@ const optionsOf = (options) => {
|
|
|
424
428
|
if (map !== false && (!Number.isInteger(map) || map < 1)) {
|
|
425
429
|
throw option('map', 'an integer of at least 1, or false');
|
|
426
430
|
}
|
|
427
|
-
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth >
|
|
428
|
-
throw option('maxDepth', `an integer from 1 to ${
|
|
431
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > MAX_DEPTH) {
|
|
432
|
+
throw option('maxDepth', `an integer from 1 to ${MAX_DEPTH}`);
|
|
429
433
|
}
|
|
430
434
|
if (typeof formats !== 'boolean') throw option('formats', 'a boolean');
|
|
431
435
|
const state = { as, name, kind, enum: cap === false ? 0 : cap, integer, map, maxDepth };
|
|
@@ -442,17 +446,33 @@ const optionsOf = (options) => {
|
|
|
442
446
|
// The samples as a list, read twice (the summary, then the self-check). A
|
|
443
447
|
// string is iterable, over its characters, and surely a mistake.
|
|
444
448
|
const listOf = (samples) => {
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
samples
|
|
448
|
-
|
|
449
|
-
typeof samples[Symbol.iterator] === 'function';
|
|
450
|
-
if (!iterable) throw invalidTarget('An iterable of samples is expected');
|
|
449
|
+
const ruledOut = samples === undefined || samples === null || typeof samples === 'string';
|
|
450
|
+
if (ruledOut || typeof samples[Symbol.iterator] !== 'function') {
|
|
451
|
+
throw invalidTarget('An iterable of samples is expected');
|
|
452
|
+
}
|
|
451
453
|
const list = Array.isArray(samples) ? samples : Array.from(samples);
|
|
452
454
|
if (list.length === 0) throw invalidTarget('At least one sample is expected');
|
|
453
455
|
return list;
|
|
454
456
|
};
|
|
455
457
|
|
|
458
|
+
// The definition of the root. A root of records is a struct with its kind;
|
|
459
|
+
// a root of records and null or undefined is a union of that one struct,
|
|
460
|
+
// since the `schema` shorthand at the root is the struct itself and cannot
|
|
461
|
+
// be optional.
|
|
462
|
+
const rootDefinition = (root, state) => {
|
|
463
|
+
const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
|
|
464
|
+
const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
|
|
465
|
+
if (form === null) return bareOf(root.bits, (root.bits & UNDEF) !== 0);
|
|
466
|
+
if (form.struct === undefined) return written(form, presence);
|
|
467
|
+
if (presence !== REQUIRED) {
|
|
468
|
+
const union = { def: { union: [written(form, REQUIRED)] } };
|
|
469
|
+
return written(union, presence);
|
|
470
|
+
}
|
|
471
|
+
const definition = { [kindKeyOf(state.kind)]: {} };
|
|
472
|
+
for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
|
|
473
|
+
return definition;
|
|
474
|
+
};
|
|
475
|
+
|
|
456
476
|
// A definition (or a Schema, with `as: 'schema'`) that accepts every
|
|
457
477
|
// sample. `options`: `as`, `name`, `kind` (the kind of a root that is a
|
|
458
478
|
// struct, 'struct'), `enum` (the most distinct strings of a place for an
|
|
@@ -466,18 +486,7 @@ const infer = (samples, options = {}) => {
|
|
|
466
486
|
state.index = index;
|
|
467
487
|
add(root, list[index], state, 0);
|
|
468
488
|
}
|
|
469
|
-
|
|
470
|
-
// null or undefined is a union of that one struct, since the `schema`
|
|
471
|
-
// shorthand at the root is the struct itself and cannot be optional.
|
|
472
|
-
let definition;
|
|
473
|
-
const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
|
|
474
|
-
const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
|
|
475
|
-
if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
|
|
476
|
-
else if (form.struct === undefined) definition = written(form, presence);
|
|
477
|
-
else if (presence === REQUIRED) {
|
|
478
|
-
definition = { [kindKeyOf(state.kind)]: {} };
|
|
479
|
-
for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
|
|
480
|
-
} else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
|
|
489
|
+
const definition = rootDefinition(root, state);
|
|
481
490
|
const schema = new Schema(state.name, definition);
|
|
482
491
|
const check = { unknown: 'reject', maxErrors: 1 };
|
|
483
492
|
for (let index = 0; index < list.length; index += 1) {
|