@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
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// `unrepresentable: 'any'`.
|
|
8
8
|
const { hasBrand, define } = require('../util.js');
|
|
9
9
|
const { isStruct } = require('../struct.js');
|
|
10
|
-
const { SchemaDefinitionError } = require('../errors.js');
|
|
10
|
+
const { SchemaDefinitionError, SchemaUsageError } = require('../errors.js');
|
|
11
11
|
const { embeds } = require('../prototypes/reference.js');
|
|
12
12
|
const { FORMATS } = require('../rules.js');
|
|
13
13
|
const { idFieldOf } = require('../kinds.js');
|
|
@@ -19,7 +19,8 @@ const { baseTypeOf } = require('../types.js');
|
|
|
19
19
|
// annotations pass through and whether the strict profile applies. The
|
|
20
20
|
// tables of this file are null-prototype dictionaries: a type or a target is
|
|
21
21
|
// looked up by a name that may be `constructor`.
|
|
22
|
-
const TARGETS =
|
|
22
|
+
const TARGETS = {
|
|
23
|
+
__proto__: null,
|
|
23
24
|
'draft-2020-12': {
|
|
24
25
|
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
25
26
|
definitions: '#/$defs/',
|
|
@@ -51,19 +52,12 @@ const TARGETS = Object.assign(Object.create(null), {
|
|
|
51
52
|
tuple: 'items',
|
|
52
53
|
annotations: ['title', 'description'],
|
|
53
54
|
},
|
|
54
|
-
}
|
|
55
|
+
};
|
|
55
56
|
|
|
56
57
|
const TARGET_NAMES = Object.keys(TARGETS);
|
|
57
58
|
|
|
58
59
|
// BSON type names where they differ from the JSON Schema ones.
|
|
59
|
-
const BSON =
|
|
60
|
-
boolean: 'bool',
|
|
61
|
-
integer: ['int', 'long'],
|
|
62
|
-
bigint: 'long',
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
// The name of an entity inside a JSON pointer (RFC 6901) in a URI fragment.
|
|
66
|
-
const escapePointer = (name) => encodeURIComponent(name.replace(/~/g, '~0').replace(/\//g, '~1'));
|
|
60
|
+
const BSON = { __proto__: null, boolean: 'bool', integer: ['int', 'long'], bigint: 'long' };
|
|
67
61
|
|
|
68
62
|
// The keys of a JSON object are strings, so a number key is a pattern.
|
|
69
63
|
const NUMBER_KEY = '^-?\\d+(\\.\\d+)?$';
|
|
@@ -71,7 +65,13 @@ const NUMBER_KEY = '^-?\\d+(\\.\\d+)?$';
|
|
|
71
65
|
// The key every stored MongoDB document has.
|
|
72
66
|
const ID = '_id';
|
|
73
67
|
|
|
74
|
-
const
|
|
68
|
+
const STANDARD_TARGETS = new Set(['draft-2020-12', 'draft-07', 'openapi-3.0']);
|
|
69
|
+
|
|
70
|
+
// The name of an entity inside a JSON pointer (RFC 6901) in a URI fragment.
|
|
71
|
+
const escapePointer = (name) => encodeURIComponent(name.replace(/~/g, '~0').replace(/\//g, '~1'));
|
|
72
|
+
|
|
73
|
+
// An option of the call that is not what it must be: the call is wrong.
|
|
74
|
+
const wrongOption = (reason) => new SchemaUsageError(reason, { code: 'ALX_ERR_INVALID_OPTION' });
|
|
75
75
|
|
|
76
76
|
const option = (options, name, allowed) => {
|
|
77
77
|
const value = options[name];
|
|
@@ -82,7 +82,7 @@ const option = (options, name, allowed) => {
|
|
|
82
82
|
list += `${index === 0 ? '' : ', '}${JSON.stringify(allowed[index])}`;
|
|
83
83
|
}
|
|
84
84
|
const got = JSON.stringify(value);
|
|
85
|
-
throw
|
|
85
|
+
throw wrongOption(`JSON Schema option "${name}" must be one of ${list}, got ${got}`);
|
|
86
86
|
}
|
|
87
87
|
return value;
|
|
88
88
|
};
|
|
@@ -97,7 +97,7 @@ const isPointer = (value) =>
|
|
|
97
97
|
// the location of an error).
|
|
98
98
|
const createContext = (options, unknown) => {
|
|
99
99
|
if (options === null || typeof options !== 'object') {
|
|
100
|
-
throw
|
|
100
|
+
throw wrongOption('JSON Schema options must be an object');
|
|
101
101
|
}
|
|
102
102
|
const name = option(options, 'target', TARGET_NAMES);
|
|
103
103
|
const target = TARGETS[name];
|
|
@@ -107,25 +107,21 @@ const createContext = (options, unknown) => {
|
|
|
107
107
|
const { profile, definitions = target.definitions } = options;
|
|
108
108
|
if (profile !== undefined && profile !== 'strict') {
|
|
109
109
|
const got = JSON.stringify(profile);
|
|
110
|
-
throw
|
|
110
|
+
throw wrongOption(`JSON Schema option "profile" must be "strict", got ${got}`);
|
|
111
111
|
}
|
|
112
112
|
const strict = profile === 'strict';
|
|
113
113
|
if (strict && target.strict !== true) {
|
|
114
|
-
throw
|
|
115
|
-
`Profile "strict" needs target "draft-2020-12" or "draft-07", got "${name}"`,
|
|
116
|
-
);
|
|
114
|
+
throw wrongOption(`Profile "strict" needs target "draft-2020-12" or "draft-07", got "${name}"`);
|
|
117
115
|
}
|
|
118
116
|
const mongo = name === 'mongodb';
|
|
119
117
|
// The ids of stored records as MongoDB holds them (the ./mongodb subpath
|
|
120
118
|
// writes them so): an ObjectId under `_id`, and in every reference.
|
|
121
119
|
const objectIds = option(options, 'ids', ['string', 'objectId']) === 'objectId';
|
|
122
120
|
if (objectIds && !mongo) {
|
|
123
|
-
throw
|
|
124
|
-
`JSON Schema option "ids" "objectId" needs target "mongodb", got "${name}"`,
|
|
125
|
-
);
|
|
121
|
+
throw wrongOption(`JSON Schema option "ids" "objectId" needs target "mongodb", got "${name}"`);
|
|
126
122
|
}
|
|
127
123
|
if (!mongo && !isPointer(definitions)) {
|
|
128
|
-
throw
|
|
124
|
+
throw wrongOption('JSON Schema option "definitions" must be a pointer such as "#/$defs/"');
|
|
129
125
|
}
|
|
130
126
|
return {
|
|
131
127
|
name,
|
|
@@ -151,7 +147,7 @@ const createContext = (options, unknown) => {
|
|
|
151
147
|
const unrepresentable = (context, what) => {
|
|
152
148
|
if (context.any) return {};
|
|
153
149
|
const reason = `${what} cannot be represented in JSON Schema target "${context.name}"`;
|
|
154
|
-
throw new SchemaDefinitionError('
|
|
150
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_UNREPRESENTABLE' });
|
|
155
151
|
};
|
|
156
152
|
|
|
157
153
|
const typed = (name, context) =>
|
|
@@ -268,7 +264,7 @@ const enumeration = (field, context) => {
|
|
|
268
264
|
const copy = [];
|
|
269
265
|
for (let index = 0; index < values.length; index += 1) {
|
|
270
266
|
const value = values[index];
|
|
271
|
-
if (!isJSON(value)) return unrepresentable(context, `Enum value ${
|
|
267
|
+
if (!isJSON(value)) return unrepresentable(context, `Enum value ${value}`);
|
|
272
268
|
copy.push(value);
|
|
273
269
|
}
|
|
274
270
|
if (copy.length === 1 && context.target.const === true) return { const: copy[0] };
|
|
@@ -317,19 +313,20 @@ const union = (field, context) => {
|
|
|
317
313
|
// the record for a memory kind, `embed` on the field and the `references`
|
|
318
314
|
// option deciding otherwise. A target that cannot be resolved is held as
|
|
319
315
|
// an id, as the dts does, unless the field embeds it.
|
|
320
|
-
const
|
|
316
|
+
const referenceOf = (field, context) => {
|
|
321
317
|
const name = field.type;
|
|
322
318
|
const target = field.root.findReference(name);
|
|
323
|
-
let json;
|
|
324
319
|
const id = context.objectIds ? { bsonType: 'objectId' } : typed('string', context);
|
|
325
320
|
if (target === null) {
|
|
326
|
-
if (field.embed === true)
|
|
327
|
-
|
|
328
|
-
} else if (!embeds(target, field.embed, context.references)) {
|
|
329
|
-
json = id;
|
|
330
|
-
} else {
|
|
331
|
-
json = definition(target, name, context);
|
|
321
|
+
if (field.embed === true) return unrepresentable(context, `Reference "${name}" (embed)`);
|
|
322
|
+
return id;
|
|
332
323
|
}
|
|
324
|
+
if (!embeds(target, field.embed, context.references)) return id;
|
|
325
|
+
return definition(target, name, context);
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
const reference = (field, context) => {
|
|
329
|
+
const json = referenceOf(field, context);
|
|
333
330
|
return field.many === undefined ? json : { [context.key]: 'array', items: json };
|
|
334
331
|
};
|
|
335
332
|
|
|
@@ -354,7 +351,8 @@ const definition = (schema, name, context) => {
|
|
|
354
351
|
return { $ref: context.prefix + escapePointer(name) };
|
|
355
352
|
};
|
|
356
353
|
|
|
357
|
-
const RENDER =
|
|
354
|
+
const RENDER = {
|
|
355
|
+
__proto__: null,
|
|
358
356
|
string: (field, context) => {
|
|
359
357
|
const json = typed('string', context);
|
|
360
358
|
if (context.strict) return json;
|
|
@@ -428,7 +426,7 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
428
426
|
reference,
|
|
429
427
|
one: reference,
|
|
430
428
|
many: reference,
|
|
431
|
-
}
|
|
429
|
+
};
|
|
432
430
|
|
|
433
431
|
// The built-in type a field validates as: its own, or the one its alias
|
|
434
432
|
// chain ends in.
|
|
@@ -517,9 +515,7 @@ const renderSchema = (schema, context, root = false) => {
|
|
|
517
515
|
const renderRoot = (schema, context) => {
|
|
518
516
|
context.closed = context.strict || schema.unknown !== 'ignore';
|
|
519
517
|
if (context.strict && !isStruct(schema.fields)) {
|
|
520
|
-
throw
|
|
521
|
-
`Profile "strict" needs a struct at the root, got "${schema.fields.type}"`,
|
|
522
|
-
);
|
|
518
|
+
throw wrongOption(`Profile "strict" needs a struct at the root, got "${schema.fields.type}"`);
|
|
523
519
|
}
|
|
524
520
|
const json = renderSchema(schema, context, true);
|
|
525
521
|
// Every stored document has an `_id`; a closed mongodb root must let it in.
|
|
@@ -570,11 +566,11 @@ const modelToJSONSchema = (model, options = {}) => {
|
|
|
570
566
|
const { root, ...rest } = options;
|
|
571
567
|
if (root !== undefined) {
|
|
572
568
|
const entity = model.entities.get(root);
|
|
573
|
-
if (entity === undefined) throw
|
|
569
|
+
if (entity === undefined) throw wrongOption(`Entity "${root}" is not in the model`);
|
|
574
570
|
return toJSONSchema(entity, rest);
|
|
575
571
|
}
|
|
576
572
|
const context = createContext(rest, 'reject');
|
|
577
|
-
if (context.strict) throw
|
|
573
|
+
if (context.strict) throw wrongOption('Profile "strict" needs a root entity');
|
|
578
574
|
const { entities, order } = model;
|
|
579
575
|
const documents = new Map();
|
|
580
576
|
for (const name of order) documents.set(name, null);
|
|
@@ -587,16 +583,14 @@ const modelToJSONSchema = (model, options = {}) => {
|
|
|
587
583
|
return place({}, context);
|
|
588
584
|
};
|
|
589
585
|
|
|
590
|
-
const STANDARD_TARGETS = ['draft-2020-12', 'draft-07', 'openapi-3.0'];
|
|
591
|
-
|
|
592
586
|
// The converter of Standard JSON Schema: `input` and `output` take the
|
|
593
587
|
// target (one of the three JSON ones) and the other options as
|
|
594
588
|
// `libraryOptions`.
|
|
595
589
|
const standardConverter = (schema) => {
|
|
596
590
|
const convert = (io) => (options) => {
|
|
597
591
|
const target = options === null || typeof options !== 'object' ? undefined : options.target;
|
|
598
|
-
if (!STANDARD_TARGETS.
|
|
599
|
-
throw
|
|
592
|
+
if (!STANDARD_TARGETS.has(target)) {
|
|
593
|
+
throw wrongOption(`JSON Schema target ${JSON.stringify(target)} is not supported`);
|
|
600
594
|
}
|
|
601
595
|
return toJSONSchema(schema, { ...options.libraryOptions, target, io });
|
|
602
596
|
};
|
|
@@ -8,7 +8,8 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
8
8
|
const { embeds } = require('../prototypes/reference.js');
|
|
9
9
|
const { baseTypeOf } = require('../types.js');
|
|
10
10
|
|
|
11
|
-
const TS_SCALARS =
|
|
11
|
+
const TS_SCALARS = {
|
|
12
|
+
__proto__: null,
|
|
12
13
|
string: 'string',
|
|
13
14
|
number: 'number',
|
|
14
15
|
boolean: 'boolean',
|
|
@@ -18,10 +19,12 @@ const TS_SCALARS = Object.assign(Object.create(null), {
|
|
|
18
19
|
null: 'null',
|
|
19
20
|
any: 'any',
|
|
20
21
|
unknown: 'unknown',
|
|
21
|
-
}
|
|
22
|
+
};
|
|
22
23
|
|
|
23
24
|
const unrepresentable = (what) =>
|
|
24
|
-
new SchemaDefinitionError(
|
|
25
|
+
new SchemaDefinitionError(`${what} cannot be represented in TypeScript`, {
|
|
26
|
+
code: 'ALX_ERR_UNREPRESENTABLE',
|
|
27
|
+
});
|
|
25
28
|
|
|
26
29
|
// The name of an interface or a type is an identifier; a declaration has no
|
|
27
30
|
// place for anything else.
|
|
@@ -40,11 +43,11 @@ const tsLiteral = (value) => {
|
|
|
40
43
|
case 'string':
|
|
41
44
|
return JSON.stringify(value);
|
|
42
45
|
case 'number':
|
|
43
|
-
return Number.isFinite(value) ?
|
|
46
|
+
return Number.isFinite(value) ? `${value}` : 'number';
|
|
44
47
|
case 'bigint':
|
|
45
48
|
return `${value}n`;
|
|
46
49
|
case 'boolean':
|
|
47
|
-
return
|
|
50
|
+
return `${value}`;
|
|
48
51
|
case 'undefined':
|
|
49
52
|
return 'undefined';
|
|
50
53
|
default:
|
|
@@ -185,7 +188,7 @@ const tsFields = (fields, ts, prefix) => {
|
|
|
185
188
|
};
|
|
186
189
|
|
|
187
190
|
// Text inside a comment: `*/` would close it.
|
|
188
|
-
const tsComment = (text) =>
|
|
191
|
+
const tsComment = (text) => `${text}`.replace(/\*\//g, '*\\/');
|
|
189
192
|
|
|
190
193
|
// The JSDoc of a field: its description, line by line, and `@deprecated`
|
|
191
194
|
// (with the note when the field gives one) when it says so.
|
package/src/index.js
CHANGED
|
@@ -3,7 +3,7 @@ const { constants, getKindMetadata } = require('./kinds.js');
|
|
|
3
3
|
// half installed into them (validation.js).
|
|
4
4
|
const { Schema, ValidationResult } = require('./validation.js');
|
|
5
5
|
const { Model } = require('./model.js');
|
|
6
|
-
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
|
+
const { SchemaDefinitionError, SchemaUsageError } = require('./errors.js');
|
|
7
7
|
|
|
8
8
|
const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
|
|
9
9
|
|
|
@@ -18,5 +18,6 @@ module.exports = {
|
|
|
18
18
|
Schema,
|
|
19
19
|
Model,
|
|
20
20
|
SchemaDefinitionError,
|
|
21
|
+
SchemaUsageError,
|
|
21
22
|
ValidationResult,
|
|
22
23
|
};
|
package/src/issues.js
CHANGED
|
@@ -15,6 +15,15 @@ const EMPTY = Object.freeze({});
|
|
|
15
15
|
// never allocates a list.
|
|
16
16
|
const NONE = Object.freeze([]);
|
|
17
17
|
|
|
18
|
+
// A key of the value that is not an identifier is bracketed and quoted, so
|
|
19
|
+
// `a.b` as one key and `a` then `b` render differently. Keys taken from the
|
|
20
|
+
// value may be huge; a message must not be.
|
|
21
|
+
const IDENTIFIER = /^[\w$]+$/;
|
|
22
|
+
|
|
23
|
+
// A message that already names its field (`Field "User.name" is not hex`, the
|
|
24
|
+
// upstream convention for custom types) is kept as it is.
|
|
25
|
+
const PREFIXED = 'Field';
|
|
26
|
+
|
|
18
27
|
const push = (context, issue) => {
|
|
19
28
|
if (context.issues === NONE) context.issues = [];
|
|
20
29
|
context.issues.push(issue);
|
|
@@ -50,13 +59,10 @@ const issues = {
|
|
|
50
59
|
pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
|
|
51
60
|
format: (context, format, key) => record(context, 'format', { format }, key),
|
|
52
61
|
// NaN and the infinities have no decimals: the value is named then.
|
|
53
|
-
decimals: (context, decimals, value, key) =>
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
Number.isFinite(value) ? { decimals } : { decimals, received: String(value) },
|
|
58
|
-
key,
|
|
59
|
-
),
|
|
62
|
+
decimals: (context, decimals, value, key) => {
|
|
63
|
+
const params = Number.isFinite(value) ? { decimals } : { decimals, received: `${value}` };
|
|
64
|
+
return record(context, 'decimals', params, key);
|
|
65
|
+
},
|
|
60
66
|
union: (context, expected, discriminator, key) =>
|
|
61
67
|
record(context, 'union', { expected, discriminator }, key),
|
|
62
68
|
reference: (context, entity, key) => record(context, 'reference', { entity }, key),
|
|
@@ -65,11 +71,6 @@ const issues = {
|
|
|
65
71
|
exception: (context, error, key) => record(context, 'exception', { error }, key),
|
|
66
72
|
};
|
|
67
73
|
|
|
68
|
-
// A key of the value that is not an identifier is bracketed and quoted, so
|
|
69
|
-
// `a.b` as one key and `a` then `b` render differently. Keys taken from the
|
|
70
|
-
// value may be huge; a message must not be.
|
|
71
|
-
const IDENTIFIER = /^[\w$]+$/;
|
|
72
|
-
|
|
73
74
|
const toDotPath = (path, root = '') => {
|
|
74
75
|
let text = root;
|
|
75
76
|
for (let index = 0; index < path.length; index += 1) {
|
|
@@ -100,14 +101,8 @@ const isIssue = (output) =>
|
|
|
100
101
|
// issues already.
|
|
101
102
|
const absorb = (context, output, code, fallback) => {
|
|
102
103
|
if (output === true || output === null || output === undefined) return;
|
|
103
|
-
if (output === false)
|
|
104
|
-
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
if (typeof output === 'string') {
|
|
108
|
-
record(context, code, EMPTY, undefined, output);
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
104
|
+
if (output === false) return void record(context, code, fallback);
|
|
105
|
+
if (typeof output === 'string') return void record(context, code, EMPTY, undefined, output);
|
|
111
106
|
if (Array.isArray(output)) {
|
|
112
107
|
// One by one: a validator may legitimately return more messages than a
|
|
113
108
|
// spread call accepts.
|
|
@@ -128,8 +123,7 @@ const absorb = (context, output, code, fallback) => {
|
|
|
128
123
|
if (isIssue(output)) {
|
|
129
124
|
const path = relative(context, output.path);
|
|
130
125
|
const params = output.params === undefined ? EMPTY : output.params;
|
|
131
|
-
push(context, { code: output.code || code, path, message: output.message, params });
|
|
132
|
-
return;
|
|
126
|
+
return void push(context, { code: output.code || code, path, message: output.message, params });
|
|
133
127
|
}
|
|
134
128
|
record(context, code, EMPTY, undefined, safeString(output));
|
|
135
129
|
};
|
|
@@ -153,10 +147,6 @@ const finalize = (list, messages) => {
|
|
|
153
147
|
}
|
|
154
148
|
};
|
|
155
149
|
|
|
156
|
-
// A message that already names its field (`Field "User.name" is not hex`, the
|
|
157
|
-
// upstream convention for custom types) is kept as it is.
|
|
158
|
-
const PREFIXED = 'Field';
|
|
159
|
-
|
|
160
150
|
const describe = (messages, root, issue) => {
|
|
161
151
|
const { message } = issue;
|
|
162
152
|
if (message.startsWith(PREFIXED)) return message;
|
|
@@ -167,13 +157,22 @@ const describe = (messages, root, issue) => {
|
|
|
167
157
|
const isThenable = (value) =>
|
|
168
158
|
value !== null && typeof value === 'object' && typeof value.then === 'function';
|
|
169
159
|
|
|
170
|
-
// A promise
|
|
171
|
-
//
|
|
172
|
-
//
|
|
160
|
+
// A promise is observed as soon as it is met, so that its rejection is never
|
|
161
|
+
// an unhandled one: one the check awaits later still rejects into that await
|
|
162
|
+
// (settle awaits the list in order, and a later promise may reject while an
|
|
163
|
+
// earlier one is pending), and one nothing waits for any more (a synchronous
|
|
164
|
+
// call that throws for it, a settle stopped by the error limit, the trial of
|
|
165
|
+
// a union branch) is dropped. A thenable is adopted once, here.
|
|
173
166
|
const swallow = () => {};
|
|
174
167
|
|
|
168
|
+
const observe = (thenable) => {
|
|
169
|
+
const promise = Promise.resolve(thenable);
|
|
170
|
+
promise.then(undefined, swallow);
|
|
171
|
+
return promise;
|
|
172
|
+
};
|
|
173
|
+
|
|
175
174
|
const abandon = (thenable) => {
|
|
176
|
-
|
|
175
|
+
observe(thenable);
|
|
177
176
|
};
|
|
178
177
|
|
|
179
178
|
// Drops the entries of a list of pending validators from `from` on (a failed
|
|
@@ -193,7 +192,7 @@ const fallbackOf = (code, owner, value) =>
|
|
|
193
192
|
|
|
194
193
|
// What a validator or a checkType returned, into the context.
|
|
195
194
|
const conclude = (context, output, code, owner, value) => {
|
|
196
|
-
if (output === true || output
|
|
195
|
+
if (output === true || output === undefined || output === null) return;
|
|
197
196
|
const bare = output === false || Array.isArray(output);
|
|
198
197
|
absorb(context, output, code, bare ? fallbackOf(code, owner, value) : EMPTY);
|
|
199
198
|
};
|
|
@@ -224,23 +223,22 @@ const guarded = (context, code, owner, fn, value) => {
|
|
|
224
223
|
const pending = context.async;
|
|
225
224
|
const { path, count } = context;
|
|
226
225
|
if (pending !== null && pending.length > 0 && under(path, pending[pending.length - 1].path)) {
|
|
227
|
-
pending.push({ owner, fn, value, promise: null, path: path.slice(), code, count });
|
|
228
|
-
return;
|
|
226
|
+
return void pending.push({ owner, fn, value, promise: null, path: path.slice(), code, count });
|
|
229
227
|
}
|
|
230
|
-
let output;
|
|
228
|
+
let output = undefined;
|
|
231
229
|
try {
|
|
232
230
|
output = fn.call(owner, value, toDotPath(path, context.root));
|
|
233
231
|
} catch (error) {
|
|
234
|
-
issues.exception(context, error);
|
|
235
|
-
return;
|
|
232
|
+
return void issues.exception(context, error);
|
|
236
233
|
}
|
|
237
234
|
if (isThenable(output)) {
|
|
238
235
|
if (pending === null) {
|
|
239
236
|
abandon(output);
|
|
240
237
|
throw asyncReturn('validator', toDotPath(path, context.root), 'checkAsync or parseAsync');
|
|
241
238
|
}
|
|
242
|
-
|
|
243
|
-
|
|
239
|
+
const promise = observe(output);
|
|
240
|
+
const entry = { owner, fn: null, value, promise, path: path.slice(), code, count };
|
|
241
|
+
return void pending.push(entry);
|
|
244
242
|
}
|
|
245
243
|
conclude(context, output, code, owner, value);
|
|
246
244
|
};
|
|
@@ -270,7 +268,7 @@ const settle = async (context) => {
|
|
|
270
268
|
const entry = pending[index];
|
|
271
269
|
if (entry.fn !== null && failedUnder(context, entry)) continue;
|
|
272
270
|
context.path = entry.path;
|
|
273
|
-
let output;
|
|
271
|
+
let output = undefined;
|
|
274
272
|
try {
|
|
275
273
|
output =
|
|
276
274
|
entry.fn === null
|
|
@@ -292,19 +290,20 @@ const runCheckType = (type, value, context) =>
|
|
|
292
290
|
guarded(context, 'type', type, type.checkType, value);
|
|
293
291
|
|
|
294
292
|
module.exports = {
|
|
293
|
+
typeOf,
|
|
295
294
|
EMPTY,
|
|
296
295
|
NONE,
|
|
297
|
-
issues,
|
|
298
|
-
typeOf,
|
|
299
296
|
pathOf,
|
|
297
|
+
issues,
|
|
300
298
|
toDotPath,
|
|
301
299
|
absorb,
|
|
302
300
|
finalize,
|
|
303
301
|
describe,
|
|
304
302
|
isThenable,
|
|
303
|
+
observe,
|
|
305
304
|
abandon,
|
|
306
305
|
release,
|
|
306
|
+
settle,
|
|
307
307
|
runValidate,
|
|
308
308
|
runCheckType,
|
|
309
|
-
settle,
|
|
310
309
|
};
|
package/src/kinds.js
CHANGED
|
@@ -2,14 +2,12 @@ const { toLowerCamel } = require('./metautil.js');
|
|
|
2
2
|
const { hasBrand } = require('./util.js');
|
|
3
3
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
4
4
|
|
|
5
|
-
const projectionError = (name, reason) =>
|
|
6
|
-
new SchemaDefinitionError('ERR_PROJECTION', `Projection "${name}" ${reason}`);
|
|
7
|
-
|
|
8
5
|
const KIND_ENT = ['entity', 'registry', 'dictionary'];
|
|
9
6
|
const KIND_AUX = ['journal', 'details', 'relation', 'view'];
|
|
10
|
-
const KIND_STORED =
|
|
7
|
+
const KIND_STORED = KIND_ENT.concat(KIND_AUX);
|
|
11
8
|
const KIND_MEMORY = ['struct', 'scalar', 'form', 'projection'];
|
|
12
|
-
const KIND =
|
|
9
|
+
const KIND = KIND_MEMORY.concat(KIND_STORED);
|
|
10
|
+
const STORED = new Set(KIND_STORED);
|
|
13
11
|
|
|
14
12
|
// A key is a kind when its name is one a kind may have (a capital letter,
|
|
15
13
|
// then letters and digits, one of them lowercase: `Entity`, `Settings`,
|
|
@@ -21,18 +19,25 @@ const KIND = [...KIND_MEMORY, ...KIND_STORED];
|
|
|
21
19
|
// the typings mirrors it.
|
|
22
20
|
const KIND_NAME = /^[A-Z][A-Z\d]*[a-z][A-Za-z\d]*$/;
|
|
23
21
|
|
|
22
|
+
const SCOPE = ['application', 'global', 'local'];
|
|
23
|
+
const STORE = ['persistent', 'memory'];
|
|
24
|
+
const ALLOW = ['write', 'append', 'read'];
|
|
25
|
+
|
|
26
|
+
const KIND_METADATA = Object.create(null);
|
|
27
|
+
|
|
28
|
+
const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
|
|
29
|
+
|
|
30
|
+
const projectionError = (name, reason) =>
|
|
31
|
+
new SchemaDefinitionError(`Projection "${name}" ${reason}`, { code: 'ALX_ERR_PROJECTION' });
|
|
32
|
+
|
|
24
33
|
const isMetadata = (value) => {
|
|
25
34
|
if (value === null || typeof value !== 'object' || hasBrand(value, 'Struct')) return false;
|
|
26
|
-
const
|
|
27
|
-
return
|
|
35
|
+
const prototype = Object.getPrototypeOf(value);
|
|
36
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
28
37
|
};
|
|
29
38
|
|
|
30
39
|
const isKindKey = (key, meta) => KIND_NAME.test(key) && isMetadata(meta);
|
|
31
40
|
|
|
32
|
-
const SCOPE = ['application', 'global', 'local'];
|
|
33
|
-
const STORE = ['persistent', 'memory'];
|
|
34
|
-
const ALLOW = ['write', 'append', 'read'];
|
|
35
|
-
|
|
36
41
|
const projection = (kind, meta, root) => {
|
|
37
42
|
const { scope = 'local', store = 'memory', allow = 'write' } = meta;
|
|
38
43
|
const { schema, fields } = meta;
|
|
@@ -62,7 +67,7 @@ const idKeyOf = (name) => (name ? `${toLowerCamel(name)}Id` : 'id');
|
|
|
62
67
|
// The id field of a built schema: the key above for a stored kind, null for
|
|
63
68
|
// a memory kind. The one rule, read by the derive, mongodb and generators
|
|
64
69
|
// subpaths (which each add what `_id` means to them).
|
|
65
|
-
const idFieldOf = (schema) => (
|
|
70
|
+
const idFieldOf = (schema) => (STORED.has(schema.kind) ? idKeyOf(schema.name) : null);
|
|
66
71
|
|
|
67
72
|
// The metadata of a kind over the defaults of its scope and store; a stored
|
|
68
73
|
// kind adds the optional id field named after the entity.
|
|
@@ -77,7 +82,6 @@ const kindStored = kindOf('application', 'persistent', true);
|
|
|
77
82
|
|
|
78
83
|
const kindMemory = kindOf('local', 'memory', false);
|
|
79
84
|
|
|
80
|
-
const KIND_METADATA = Object.create(null);
|
|
81
85
|
for (const kind of KIND_MEMORY) {
|
|
82
86
|
KIND_METADATA[kind] = kindMemory;
|
|
83
87
|
}
|
|
@@ -91,6 +95,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
|
|
|
91
95
|
return handler(kind, meta, root);
|
|
92
96
|
};
|
|
93
97
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
module.exports = { constants, getKindMetadata, idFieldOf, isKindKey };
|
|
98
|
+
module.exports = { constants, isKindKey, idFieldOf, getKindMetadata };
|
package/src/lint.js
CHANGED
|
@@ -6,24 +6,10 @@ const { hasBrand, formatters, KINDS } = require('./util.js');
|
|
|
6
6
|
const { firstKey } = require('./metautil.js');
|
|
7
7
|
const { embeds } = require('./prototypes/reference.js');
|
|
8
8
|
|
|
9
|
-
const warning = (code, text) => `Warning [${code}]: ${text}`;
|
|
10
|
-
|
|
11
9
|
// The types no converter of coercion exists for: a value of them is taken
|
|
12
10
|
// as it is.
|
|
13
11
|
const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null', 'flags']);
|
|
14
12
|
|
|
15
|
-
// A `coerce` key where no conversion can happen: a reference checked as an
|
|
16
|
-
// id (the record it names is never entered), a type that takes any value.
|
|
17
|
-
const deadCoerce = (field) => {
|
|
18
|
-
const name = field.one || field.many;
|
|
19
|
-
if (name !== undefined) {
|
|
20
|
-
const target = field.root.findReference(name);
|
|
21
|
-
if (target !== null && embeds(target, field.embed, 'kind')) return '';
|
|
22
|
-
return 'a reference checked as an id';
|
|
23
|
-
}
|
|
24
|
-
return NEVER_CONVERTED.has(field.type) ? `a value of type "${field.type}"` : '';
|
|
25
|
-
};
|
|
26
|
-
|
|
27
13
|
// A field lints by its definition keys: the keys every type knows, the
|
|
28
14
|
// annotations that any field may carry for code that reads the schema, and
|
|
29
15
|
// the options of its own type. A custom type with its own construct owns
|
|
@@ -48,6 +34,20 @@ const KNOWN = new Set([
|
|
|
48
34
|
'aliases',
|
|
49
35
|
]);
|
|
50
36
|
|
|
37
|
+
const warning = (code, text) => `Warning [${code}]: ${text}`;
|
|
38
|
+
|
|
39
|
+
// A `coerce` key where no conversion can happen: a reference checked as an
|
|
40
|
+
// id (the record it names is never entered), a type that takes any value.
|
|
41
|
+
const deadCoerce = (field) => {
|
|
42
|
+
const name = field.one || field.many;
|
|
43
|
+
if (name !== undefined) {
|
|
44
|
+
const target = field.root.findReference(name);
|
|
45
|
+
if (target !== null && embeds(target, field.embed, 'kind')) return '';
|
|
46
|
+
return 'a reference checked as an id';
|
|
47
|
+
}
|
|
48
|
+
return NEVER_CONVERTED.has(field.type) ? `a value of type "${field.type}"` : '';
|
|
49
|
+
};
|
|
50
|
+
|
|
51
51
|
const isCustom = (Type) => Type.source !== undefined && Type.source.js === undefined;
|
|
52
52
|
|
|
53
53
|
// `element` says the field is an element of a tuple, whose `name` is the
|
|
@@ -110,10 +110,7 @@ const lintField = (field, path, warnings, element = false, member = false) => {
|
|
|
110
110
|
};
|
|
111
111
|
|
|
112
112
|
const lintStruct = (fields, prefix, warnings) => {
|
|
113
|
-
if (!hasBrand(fields, 'Struct'))
|
|
114
|
-
lintField(fields, prefix, warnings);
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
113
|
+
if (!hasBrand(fields, 'Struct')) return void lintField(fields, prefix, warnings);
|
|
117
114
|
for (const key of Object.keys(fields)) {
|
|
118
115
|
const field = fields[key];
|
|
119
116
|
if (!hasBrand(field, 'Type')) continue;
|
package/src/locales/en.js
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
// message. `field` renders the location prefix of an error line.
|
|
4
4
|
const { shorten, safeString } = require('../util.js');
|
|
5
5
|
|
|
6
|
+
// The first keys of the list and how many more there are: a value with a
|
|
7
|
+
// million keys the schema does not have is one issue, and its message is
|
|
8
|
+
// not the million keys.
|
|
9
|
+
const SHOWN_KEYS = 10;
|
|
10
|
+
|
|
6
11
|
const field = (path) => `Field "${path}"`;
|
|
7
12
|
|
|
8
13
|
const required = () => 'is required';
|
|
@@ -10,16 +15,11 @@ const required = () => 'is required';
|
|
|
10
15
|
const type = ({ expected, key }) =>
|
|
11
16
|
key === undefined ? `not of expected type: ${expected}` : `keys must be of type ${expected}`;
|
|
12
17
|
|
|
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
|
-
|
|
18
18
|
const list = (keys) => {
|
|
19
|
-
const count = Math.min(keys.length,
|
|
19
|
+
const count = Math.min(keys.length, SHOWN_KEYS);
|
|
20
20
|
let text = shorten(keys[0]);
|
|
21
21
|
for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
|
|
22
|
-
return keys.length >
|
|
22
|
+
return keys.length > SHOWN_KEYS ? `${text} and ${keys.length - SHOWN_KEYS} more` : text;
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
const unexpected = ({ keys }) => `has unexpected keys: ${list(keys)}`;
|
package/src/locales/uk.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// check as `messages`: `schema.check(value, { messages: uk })`.
|
|
3
3
|
const { shorten, safeString } = require('../util.js');
|
|
4
4
|
|
|
5
|
+
// Перші ключі списку і скільки їх ще: значення з мільйоном невідомих ключів
|
|
6
|
+
// є одним issue, і його повідомлення не є цим мільйоном.
|
|
7
|
+
const SHOWN_KEYS = 10;
|
|
8
|
+
|
|
5
9
|
const field = (path) => `Поле "${path}"`;
|
|
6
10
|
|
|
7
11
|
const required = () => 'є обовʼязковим';
|
|
@@ -9,15 +13,11 @@ const required = () => 'є обовʼязковим';
|
|
|
9
13
|
const type = ({ expected, key }) =>
|
|
10
14
|
key === undefined ? `не відповідає типу: ${expected}` : `ключі мають бути типу ${expected}`;
|
|
11
15
|
|
|
12
|
-
// Перші ключі списку і скільки їх ще: значення з мільйоном невідомих ключів
|
|
13
|
-
// є одним issue, і його повідомлення не є цим мільйоном.
|
|
14
|
-
const SHOWN = 10;
|
|
15
|
-
|
|
16
16
|
const list = (keys) => {
|
|
17
|
-
const count = Math.min(keys.length,
|
|
17
|
+
const count = Math.min(keys.length, SHOWN_KEYS);
|
|
18
18
|
let text = shorten(keys[0]);
|
|
19
19
|
for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
|
|
20
|
-
return keys.length >
|
|
20
|
+
return keys.length > SHOWN_KEYS ? `${text} і ще ${keys.length - SHOWN_KEYS}` : text;
|
|
21
21
|
};
|
|
22
22
|
|
|
23
23
|
const unexpected = ({ keys }) => `має неочікувані ключі: ${list(keys)}`;
|
package/src/metadata.js
CHANGED
|
@@ -12,7 +12,7 @@ const unknownOf = (unknown) => {
|
|
|
12
12
|
if (unknown === undefined) return 'reject';
|
|
13
13
|
if (unknown !== 'reject' && unknown !== 'ignore') {
|
|
14
14
|
const reason = `Schema metadata "unknown" must be "reject" or "ignore", got ${JSON.stringify(unknown)}`;
|
|
15
|
-
throw new SchemaDefinitionError('
|
|
15
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_INVALID_OPTIONS' });
|
|
16
16
|
}
|
|
17
17
|
return unknown;
|
|
18
18
|
};
|
|
@@ -60,7 +60,7 @@ class SchemaMetadata {
|
|
|
60
60
|
const { kind, scope, store, allow, parent, unknown, ...custom } = values;
|
|
61
61
|
if (custom.coerce !== undefined && typeof custom.coerce !== 'boolean') {
|
|
62
62
|
const reason = `Schema metadata "coerce" must be a boolean, got ${JSON.stringify(custom.coerce)}`;
|
|
63
|
-
throw new SchemaDefinitionError('
|
|
63
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_INVALID_OPTIONS' });
|
|
64
64
|
}
|
|
65
65
|
this.kind = kind || this.kind;
|
|
66
66
|
this.scope = scope || this.scope;
|