@alexify/metaschema 3.2.0 → 3.4.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 +307 -1
- package/README.md +173 -89
- package/SECURITY.md +24 -1
- package/index.d.ts +601 -29
- package/package.json +28 -3
- package/src/checks.js +789 -0
- package/src/codec.js +201 -46
- package/src/coerce/index.d.ts +34 -0
- package/src/coerce/index.js +385 -0
- package/src/compile/emit.js +87 -28
- package/src/compile/index.js +9 -4
- package/src/context.js +6 -1
- package/src/definition/index.d.ts +19 -0
- package/src/definition/index.js +27 -0
- package/src/derive/index.d.ts +86 -0
- package/src/derive/index.js +273 -0
- package/src/errors.js +46 -4
- package/src/formats/index.d.ts +20 -8
- package/src/formats/index.js +450 -39
- package/src/generators/fromjsonschema.js +21 -2
- package/src/generators/index.js +1 -1
- package/src/generators/jsonschema.js +90 -21
- package/src/generators/typescript.js +11 -0
- package/src/index.js +3 -2
- package/src/issues.js +9 -7
- package/src/kinds.js +15 -3
- package/src/lint.js +38 -0
- package/src/locales/en.js +6 -0
- package/src/locales/uk.js +6 -0
- package/src/metadata.js +6 -24
- package/src/model/data.js +67 -10
- package/src/model/diff.js +7 -4
- package/src/model/index.js +1 -1
- package/src/model/infer.js +10 -3
- package/src/model/merge.js +16 -9
- package/src/model/restore.js +52 -7
- package/src/model/sample.js +28 -4
- package/src/model.js +54 -56
- package/src/mongodb/bson.js +130 -0
- package/src/mongodb/document.js +217 -0
- package/src/mongodb/index.d.ts +133 -0
- package/src/mongodb/index.js +24 -0
- package/src/mongodb/indexes.js +79 -0
- package/src/mongodb/update.js +258 -0
- package/src/preprocessor.js +1 -2
- package/src/prototypes/abstract.js +41 -67
- package/src/prototypes/collections.js +3 -90
- package/src/prototypes/flags.js +34 -0
- package/src/prototypes/json.js +0 -11
- package/src/prototypes/reference.js +0 -76
- package/src/prototypes/scalars.js +17 -96
- package/src/prototypes/schema.js +1 -10
- package/src/prototypes/tuple.js +0 -26
- package/src/prototypes/union.js +12 -82
- package/src/rules.js +33 -157
- package/src/schema.js +105 -220
- package/src/snapshot.js +216 -41
- package/src/stream/index.js +1 -1
- package/src/struct.js +6 -91
- package/src/types.js +43 -6
- package/src/util.js +43 -0
- package/src/validation.js +313 -0
|
@@ -9,6 +9,9 @@ const { hasBrand, define } = require('../util.js');
|
|
|
9
9
|
const { isStruct } = require('../struct.js');
|
|
10
10
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
11
11
|
const { embeds } = require('../prototypes/reference.js');
|
|
12
|
+
const { FORMATS } = require('../rules.js');
|
|
13
|
+
const { idFieldOf } = require('../kinds.js');
|
|
14
|
+
const { baseTypeOf } = require('../types.js');
|
|
12
15
|
|
|
13
16
|
// What differs between the dialects: the keyword of a type, where the
|
|
14
17
|
// definitions live, whether `const`, tuples, `propertyNames` and siblings of
|
|
@@ -40,6 +43,8 @@ const TARGETS = Object.assign(Object.create(null), {
|
|
|
40
43
|
definitions: '#/components/schemas/',
|
|
41
44
|
nullable: true,
|
|
42
45
|
oneOf: true,
|
|
46
|
+
// OpenAPI's name of base64 text.
|
|
47
|
+
byte: true,
|
|
43
48
|
annotations: ['title', 'description', 'default', 'example', 'deprecated'],
|
|
44
49
|
},
|
|
45
50
|
mongodb: {
|
|
@@ -111,6 +116,14 @@ const createContext = (options, unknown) => {
|
|
|
111
116
|
);
|
|
112
117
|
}
|
|
113
118
|
const mongo = name === 'mongodb';
|
|
119
|
+
// The ids of stored records as MongoDB holds them (the ./mongodb subpath
|
|
120
|
+
// writes them so): an ObjectId under `_id`, and in every reference.
|
|
121
|
+
const objectIds = option(options, 'ids', ['string', 'objectId']) === 'objectId';
|
|
122
|
+
if (objectIds && !mongo) {
|
|
123
|
+
throw invalidOptions(
|
|
124
|
+
`JSON Schema option "ids" "objectId" needs target "mongodb", got "${name}"`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
114
127
|
if (!mongo && !isPointer(definitions)) {
|
|
115
128
|
throw invalidOptions('JSON Schema option "definitions" must be a pointer such as "#/$defs/"');
|
|
116
129
|
}
|
|
@@ -124,6 +137,7 @@ const createContext = (options, unknown) => {
|
|
|
124
137
|
input: mongo || io === 'input',
|
|
125
138
|
any,
|
|
126
139
|
references,
|
|
140
|
+
objectIds,
|
|
127
141
|
strict,
|
|
128
142
|
closed: strict || unknown !== 'ignore',
|
|
129
143
|
prefix: mongo ? null : definitions,
|
|
@@ -234,6 +248,18 @@ const dictionary = (field, context) => {
|
|
|
234
248
|
return json;
|
|
235
249
|
};
|
|
236
250
|
|
|
251
|
+
// A flags value: a boolean per name, every one optional (all of them
|
|
252
|
+
// under the strict profile, which lists every property as required), no
|
|
253
|
+
// other key when the document is closed.
|
|
254
|
+
const flags = (field, context) => {
|
|
255
|
+
const properties = {};
|
|
256
|
+
for (const name of field.flags) define(properties, name, typed('boolean', context));
|
|
257
|
+
const json = { [context.key]: 'object', properties };
|
|
258
|
+
if (context.strict) json.required = field.flags.slice();
|
|
259
|
+
if (context.closed) json.additionalProperties = false;
|
|
260
|
+
return json;
|
|
261
|
+
};
|
|
262
|
+
|
|
237
263
|
const isJSON = (value) =>
|
|
238
264
|
value === null || (typeof value !== 'object' && typeof value !== 'bigint');
|
|
239
265
|
|
|
@@ -295,22 +321,24 @@ const reference = (field, context) => {
|
|
|
295
321
|
const name = field.type;
|
|
296
322
|
const target = field.root.findReference(name);
|
|
297
323
|
let json;
|
|
324
|
+
const id = context.objectIds ? { bsonType: 'objectId' } : typed('string', context);
|
|
298
325
|
if (target === null) {
|
|
299
326
|
if (field.embed === true) json = unrepresentable(context, `Reference "${name}" (embed)`);
|
|
300
|
-
else json =
|
|
327
|
+
else json = id;
|
|
301
328
|
} else if (!embeds(target, field.embed, context.references)) {
|
|
302
|
-
json =
|
|
329
|
+
json = id;
|
|
303
330
|
} else {
|
|
304
|
-
json = definition(target, context);
|
|
331
|
+
json = definition(target, name, context);
|
|
305
332
|
}
|
|
306
333
|
return field.many === undefined ? json : { [context.key]: 'array', items: json };
|
|
307
334
|
};
|
|
308
335
|
|
|
309
|
-
// A referenced entity
|
|
310
|
-
//
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
336
|
+
// A referenced entity, under the name the reference reached it through (an
|
|
337
|
+
// anonymous schema of a model is the entity of the name the model gives
|
|
338
|
+
// it): `#` for the root of the document, a `$ref` into the definitions
|
|
339
|
+
// (rendered once) otherwise, and inline where the target has no `$ref`
|
|
340
|
+
// (mongodb), where a cycle has no form.
|
|
341
|
+
const definition = (schema, name, context) => {
|
|
314
342
|
if (context.prefix === null) {
|
|
315
343
|
if (context.stack.has(name)) return unrepresentable(context, `Recursive reference "${name}"`);
|
|
316
344
|
context.stack.add(name);
|
|
@@ -331,12 +359,25 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
331
359
|
const json = typed('string', context);
|
|
332
360
|
if (context.strict) return json;
|
|
333
361
|
bounds(json, field.length, 'minLength', 'maxLength');
|
|
362
|
+
// A format a validator may not know (`ulid`, `iban`) is asserted by its
|
|
363
|
+
// shape too, where the field has no pattern of its own.
|
|
364
|
+
const shape = field.format === undefined ? undefined : FORMATS[field.format]?.pattern;
|
|
334
365
|
if (field.pattern !== undefined) json.pattern = field.pattern.source;
|
|
366
|
+
else if (shape !== undefined) json.pattern = shape;
|
|
335
367
|
// The names are those of JSON Schema; a $jsonSchema has no `format`.
|
|
336
|
-
if (field.format !== undefined && !context.mongo)
|
|
368
|
+
if (field.format !== undefined && !context.mongo) {
|
|
369
|
+
const byte = field.format === 'base64' && context.target.byte === true;
|
|
370
|
+
json.format = byte ? 'byte' : field.format;
|
|
371
|
+
}
|
|
372
|
+
return json;
|
|
373
|
+
},
|
|
374
|
+
// A number of `n` decimals is a multiple of 10⁻ⁿ (a validator that
|
|
375
|
+
// divides may disagree with `check` on the last bit of a sum).
|
|
376
|
+
number: (field, context) => {
|
|
377
|
+
const json = ranged(typed('number', context), field, context);
|
|
378
|
+
if (field.decimals !== undefined && !context.strict) json.multipleOf = 10 ** -field.decimals;
|
|
337
379
|
return json;
|
|
338
380
|
},
|
|
339
|
-
number: (field, context) => ranged(typed('number', context), field, context),
|
|
340
381
|
integer: (field, context) => ranged(typed('integer', context), field, context),
|
|
341
382
|
bigint: (field, context) =>
|
|
342
383
|
context.mongo ? typed('bigint', context) : unrepresentable(context, 'Type "bigint"'),
|
|
@@ -346,6 +387,24 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
346
387
|
if (context.input) return { type: 'string', format: 'date-time' };
|
|
347
388
|
return unrepresentable(context, 'Type "date" (output)');
|
|
348
389
|
},
|
|
390
|
+
// Binary data is base64 text on a JSON wire (the input `./coerce` reads
|
|
391
|
+
// back) and binData in MongoDB; the Uint8Array parse gives is no JSON. The
|
|
392
|
+
// length of the text bounds the bytes: four characters for every three
|
|
393
|
+
// started (a text that long may decode to two bytes more than `max`).
|
|
394
|
+
bytes: (field, context) => {
|
|
395
|
+
if (context.mongo) return typed('binData', context);
|
|
396
|
+
if (!context.input) return unrepresentable(context, 'Type "bytes" (output)');
|
|
397
|
+
if (context.strict) return typed('string', context);
|
|
398
|
+
const json =
|
|
399
|
+
context.target.byte === true
|
|
400
|
+
? { type: 'string', format: 'byte' }
|
|
401
|
+
: { type: 'string', contentEncoding: 'base64' };
|
|
402
|
+
const { length } = field;
|
|
403
|
+
if (length?.min !== undefined) json.minLength = 4 * Math.ceil(length.min / 3);
|
|
404
|
+
if (length?.max !== undefined) json.maxLength = 4 * Math.ceil(length.max / 3);
|
|
405
|
+
return json;
|
|
406
|
+
},
|
|
407
|
+
flags,
|
|
349
408
|
null: (field, context) => typed('null', context),
|
|
350
409
|
any: (field, context) => unconstrained(context, 'any') || {},
|
|
351
410
|
unknown: (field, context) => unconstrained(context, 'unknown') || {},
|
|
@@ -373,12 +432,7 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
373
432
|
|
|
374
433
|
// The built-in type a field validates as: its own, or the one its alias
|
|
375
434
|
// chain ends in.
|
|
376
|
-
const baseOf = (field) =>
|
|
377
|
-
const { types } = field.root;
|
|
378
|
-
let Type = field.constructor;
|
|
379
|
-
while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
|
|
380
|
-
return Type.type;
|
|
381
|
-
};
|
|
435
|
+
const baseOf = (field) => baseTypeOf(field).type;
|
|
382
436
|
|
|
383
437
|
// The schema of the type of a field: the metadata of a custom type when it
|
|
384
438
|
// says (`jsonSchema`, or `bson` for mongodb), else the built-in it is or
|
|
@@ -407,14 +461,20 @@ const render = (field, context) => {
|
|
|
407
461
|
// A struct: its validated fields as properties (a calculated field is a
|
|
408
462
|
// function and has no schema), the required ones listed, no other keys
|
|
409
463
|
// unless the schema ignores them. The strict profile lists every property.
|
|
410
|
-
const struct = (fields, context) => {
|
|
464
|
+
const struct = (fields, context, id = null, root = false) => {
|
|
411
465
|
const properties = {};
|
|
412
466
|
const required = [];
|
|
467
|
+
// The id field of a stored record is `_id` in the document, the first key;
|
|
468
|
+
// the database gives one to a record inserted without it.
|
|
469
|
+
if (id !== null) {
|
|
470
|
+
properties[ID] = { bsonType: 'objectId' };
|
|
471
|
+
if (root) required.push(ID);
|
|
472
|
+
}
|
|
413
473
|
// A struct is a null-prototype dictionary: its own keys, in order; a key
|
|
414
474
|
// such as `__proto__` is defined as data on the document.
|
|
415
475
|
for (const key in fields) {
|
|
416
476
|
const field = fields[key];
|
|
417
|
-
if (!hasBrand(field, 'Type')) continue;
|
|
477
|
+
if (key === id || !hasBrand(field, 'Type')) continue;
|
|
418
478
|
try {
|
|
419
479
|
define(properties, key, render(field, context));
|
|
420
480
|
} catch (error) {
|
|
@@ -430,14 +490,23 @@ const struct = (fields, context) => {
|
|
|
430
490
|
return json;
|
|
431
491
|
};
|
|
432
492
|
|
|
493
|
+
// The id field a stored kind adds, which `ids: 'objectId'` writes as `_id`,
|
|
494
|
+
// unless the schema has an `_id` of its own.
|
|
495
|
+
const idOf = (schema, context) => {
|
|
496
|
+
if (!context.objectIds) return null;
|
|
497
|
+
const id = idFieldOf(schema);
|
|
498
|
+
return id === null || ID in schema.fields ? null : id;
|
|
499
|
+
};
|
|
500
|
+
|
|
433
501
|
// The schema being rendered owns the location of an error met in it, and
|
|
434
502
|
// is restored when the rendering leaves it, thrown out of or not.
|
|
435
|
-
const renderSchema = (schema, context) => {
|
|
503
|
+
const renderSchema = (schema, context, root = false) => {
|
|
436
504
|
const { owner } = context;
|
|
437
505
|
const { fields } = schema;
|
|
438
506
|
context.owner = schema.name;
|
|
439
507
|
try {
|
|
440
|
-
|
|
508
|
+
if (!isStruct(fields)) return render(fields, context);
|
|
509
|
+
return struct(fields, context, idOf(schema, context), root);
|
|
441
510
|
} finally {
|
|
442
511
|
context.owner = owner;
|
|
443
512
|
}
|
|
@@ -452,7 +521,7 @@ const renderRoot = (schema, context) => {
|
|
|
452
521
|
`Profile "strict" needs a struct at the root, got "${schema.fields.type}"`,
|
|
453
522
|
);
|
|
454
523
|
}
|
|
455
|
-
const json = renderSchema(schema, context);
|
|
524
|
+
const json = renderSchema(schema, context, true);
|
|
456
525
|
// Every stored document has an `_id`; a closed mongodb root must let it in.
|
|
457
526
|
if (context.mongo && json.additionalProperties === false && json.properties[ID] === undefined) {
|
|
458
527
|
json.properties[ID] = {};
|
|
@@ -6,6 +6,7 @@ const { isFirstUpper } = require('../metautil.js');
|
|
|
6
6
|
const { hasBrand, IDENTIFIER } = require('../util.js');
|
|
7
7
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
8
8
|
const { embeds } = require('../prototypes/reference.js');
|
|
9
|
+
const { baseTypeOf } = require('../types.js');
|
|
9
10
|
|
|
10
11
|
const TS_SCALARS = Object.assign(Object.create(null), {
|
|
11
12
|
string: 'string',
|
|
@@ -13,6 +14,7 @@ const TS_SCALARS = Object.assign(Object.create(null), {
|
|
|
13
14
|
boolean: 'boolean',
|
|
14
15
|
bigint: 'bigint',
|
|
15
16
|
date: 'Date',
|
|
17
|
+
bytes: 'Uint8Array',
|
|
16
18
|
null: 'null',
|
|
17
19
|
any: 'any',
|
|
18
20
|
unknown: 'unknown',
|
|
@@ -118,6 +120,15 @@ const tsBase = (def, ts, name, target, top) => {
|
|
|
118
120
|
ts.blocks.push(`type ${named} = ${text};`);
|
|
119
121
|
return named;
|
|
120
122
|
}
|
|
123
|
+
// By the type, as JSON Schema tells it: `flags` is an option name any type
|
|
124
|
+
// may carry (a pattern's, a custom type's).
|
|
125
|
+
if (baseTypeOf(def).type === 'flags') {
|
|
126
|
+
const names = [];
|
|
127
|
+
for (let index = 0; index < def.flags.length; index += 1) {
|
|
128
|
+
names.push(`${tsKey(def.flags[index])}?: boolean`);
|
|
129
|
+
}
|
|
130
|
+
return `{ ${names.join('; ')} }`;
|
|
131
|
+
}
|
|
121
132
|
if (def.union) {
|
|
122
133
|
const branches = [];
|
|
123
134
|
for (let index = 0; index < def.union.length; index += 1) {
|
package/src/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
const { constants, getKindMetadata } = require('./kinds.js');
|
|
2
|
-
|
|
2
|
+
// The core entry: the definition half (the classes) with the validation
|
|
3
|
+
// half installed into them (validation.js).
|
|
4
|
+
const { Schema, ValidationResult } = require('./validation.js');
|
|
3
5
|
const { Model } = require('./model.js');
|
|
4
6
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
5
|
-
const { ValidationResult } = require('./result.js');
|
|
6
7
|
|
|
7
8
|
const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
|
|
8
9
|
|
package/src/issues.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// are rendered once, at the end of the check, through the locale of that check.
|
|
5
5
|
// Every issue has the same keys in the same order, so loops over them see one
|
|
6
6
|
// shape.
|
|
7
|
-
const { hasBrand, shorten, safeString } = require('./util.js');
|
|
7
|
+
const { hasBrand, shorten, safeString, typeOf } = require('./util.js');
|
|
8
8
|
const { asyncReturn } = require('./errors.js');
|
|
9
9
|
const en = require('./locales/en.js');
|
|
10
10
|
|
|
@@ -37,12 +37,6 @@ const record = (context, code, params, key, message = '') => {
|
|
|
37
37
|
push(context, { code, path: pathOf(context, key), message, params });
|
|
38
38
|
};
|
|
39
39
|
|
|
40
|
-
const typeOf = (value) => {
|
|
41
|
-
if (value === null) return 'null';
|
|
42
|
-
if (Array.isArray(value)) return 'array';
|
|
43
|
-
return typeof value;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
40
|
const issues = {
|
|
47
41
|
required: (context, key) => record(context, 'required', EMPTY, key),
|
|
48
42
|
type: (context, expected, value, key) =>
|
|
@@ -55,6 +49,14 @@ const issues = {
|
|
|
55
49
|
range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
|
|
56
50
|
pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
|
|
57
51
|
format: (context, format, key) => record(context, 'format', { format }, key),
|
|
52
|
+
// NaN and the infinities have no decimals: the value is named then.
|
|
53
|
+
decimals: (context, decimals, value, key) =>
|
|
54
|
+
record(
|
|
55
|
+
context,
|
|
56
|
+
'decimals',
|
|
57
|
+
Number.isFinite(value) ? { decimals } : { decimals, received: String(value) },
|
|
58
|
+
key,
|
|
59
|
+
),
|
|
58
60
|
union: (context, expected, discriminator, key) =>
|
|
59
61
|
record(context, 'union', { expected, discriminator }, key),
|
|
60
62
|
reference: (context, entity, key) => record(context, 'reference', { entity }, key),
|
package/src/kinds.js
CHANGED
|
@@ -22,8 +22,11 @@ const projection = (kind, meta, root) => {
|
|
|
22
22
|
}
|
|
23
23
|
const parent = schema;
|
|
24
24
|
const metadata = { ...meta, kind, scope, store, allow, parent };
|
|
25
|
+
// The projection itself is not built yet, so its own name is no parent.
|
|
25
26
|
const entity = root.findReference(schema);
|
|
26
|
-
if (!entity
|
|
27
|
+
if (!entity || entity === root) {
|
|
28
|
+
throw projectionError(root.name, `parent "${schema}" is not found`);
|
|
29
|
+
}
|
|
27
30
|
const defs = Object.create(null);
|
|
28
31
|
for (const key of fields) {
|
|
29
32
|
const field = entity.fields[key];
|
|
@@ -33,12 +36,21 @@ const projection = (kind, meta, root) => {
|
|
|
33
36
|
return { defs, metadata };
|
|
34
37
|
};
|
|
35
38
|
|
|
39
|
+
// The key of the id field a stored kind adds: named after the entity
|
|
40
|
+
// (`orderId`), `id` for an anonymous schema.
|
|
41
|
+
const idKeyOf = (name) => (name ? `${toLowerCamel(name)}Id` : 'id');
|
|
42
|
+
|
|
43
|
+
// The id field of a built schema: the key above for a stored kind, null for
|
|
44
|
+
// a memory kind. The one rule, read by the derive, mongodb and generators
|
|
45
|
+
// subpaths (which each add what `_id` means to them).
|
|
46
|
+
const idFieldOf = (schema) => (KIND_STORED.includes(schema.kind) ? idKeyOf(schema.name) : null);
|
|
47
|
+
|
|
36
48
|
// The metadata of a kind over the defaults of its scope and store; a stored
|
|
37
49
|
// kind adds the optional id field named after the entity.
|
|
38
50
|
const kindOf = (defaultScope, defaultStore, stored) => (kind, meta, root) => {
|
|
39
51
|
const { scope = defaultScope, store = defaultStore, allow = 'write' } = meta;
|
|
40
52
|
const defs = Object.create(null);
|
|
41
|
-
if (stored) defs[
|
|
53
|
+
if (stored) defs[idKeyOf(root.name)] = '?string';
|
|
42
54
|
return { defs, metadata: { ...meta, kind, scope, store, allow } };
|
|
43
55
|
};
|
|
44
56
|
|
|
@@ -62,4 +74,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
|
|
|
62
74
|
|
|
63
75
|
const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
|
|
64
76
|
|
|
65
|
-
module.exports = { constants, getKindMetadata };
|
|
77
|
+
module.exports = { constants, getKindMetadata, idFieldOf };
|
package/src/lint.js
CHANGED
|
@@ -3,9 +3,26 @@
|
|
|
3
3
|
// (an enum without values, a min above max) is a SchemaDefinitionError at
|
|
4
4
|
// build time; these are warnings, as `Warning [code]: text` strings.
|
|
5
5
|
const { hasBrand } = require('./util.js');
|
|
6
|
+
const { embeds } = require('./prototypes/reference.js');
|
|
6
7
|
|
|
7
8
|
const warning = (code, text) => `Warning [${code}]: ${text}`;
|
|
8
9
|
|
|
10
|
+
// The types no converter of coercion exists for: a value of them is taken
|
|
11
|
+
// as it is.
|
|
12
|
+
const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null', 'flags']);
|
|
13
|
+
|
|
14
|
+
// A `coerce` key where no conversion can happen: a reference checked as an
|
|
15
|
+
// id (the record it names is never entered), a type that takes any value.
|
|
16
|
+
const deadCoerce = (field) => {
|
|
17
|
+
const name = field.one || field.many;
|
|
18
|
+
if (name !== undefined) {
|
|
19
|
+
const target = field.root.findReference(name);
|
|
20
|
+
if (target !== null && embeds(target, field.embed, 'kind')) return '';
|
|
21
|
+
return 'a reference checked as an id';
|
|
22
|
+
}
|
|
23
|
+
return NEVER_CONVERTED.has(field.type) ? `a value of type "${field.type}"` : '';
|
|
24
|
+
};
|
|
25
|
+
|
|
9
26
|
// A field lints by its definition keys: the keys every type knows, the
|
|
10
27
|
// annotations that any field may carry for code that reads the schema, and
|
|
11
28
|
// the options of its own type. A custom type with its own construct owns
|
|
@@ -15,6 +32,7 @@ const KNOWN = new Set([
|
|
|
15
32
|
'type',
|
|
16
33
|
'required',
|
|
17
34
|
'nullable',
|
|
35
|
+
'coerce',
|
|
18
36
|
'validate',
|
|
19
37
|
'parse',
|
|
20
38
|
'serialize',
|
|
@@ -52,6 +70,26 @@ const lintField = (field, path, warnings, element = false, member = false) => {
|
|
|
52
70
|
const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
|
|
53
71
|
warnings.push(warning('unbounded-pattern', text));
|
|
54
72
|
}
|
|
73
|
+
if (field.decimals !== undefined) {
|
|
74
|
+
// The check tells a decimal too many apart below 2⁴³ units of the last
|
|
75
|
+
// decimal (ULPS of checks.js); a bound past it lets any number through.
|
|
76
|
+
// A side without a bound counts as 1.
|
|
77
|
+
const bound = Math.max(Math.abs(field.min ?? 1), Math.abs(field.max ?? 1));
|
|
78
|
+
const limit = 2 ** 43 / 10 ** field.decimals;
|
|
79
|
+
if (bound >= limit) {
|
|
80
|
+
const below = Number(limit.toPrecision(2));
|
|
81
|
+
const text =
|
|
82
|
+
`"${path}" has ${field.decimals} decimals, ` +
|
|
83
|
+
`which the check tells apart only below ${below}`;
|
|
84
|
+
warnings.push(warning('unenforceable-decimals', text));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (field.coerce !== undefined) {
|
|
88
|
+
const dead = deadCoerce(field);
|
|
89
|
+
if (dead !== '') {
|
|
90
|
+
warnings.push(warning('dead-coerce', `"${path}" has coerce, but ${dead} is never converted`));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
55
93
|
if (field.schema !== undefined) lintStruct(field.schema, path, warnings);
|
|
56
94
|
const { value, union } = field;
|
|
57
95
|
if (value !== undefined) {
|
package/src/locales/en.js
CHANGED
|
@@ -36,6 +36,11 @@ const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
|
|
|
36
36
|
|
|
37
37
|
const format = ({ format: name }) => `is not a valid ${name}`;
|
|
38
38
|
|
|
39
|
+
const decimals = ({ decimals: count, received }) =>
|
|
40
|
+
received === undefined
|
|
41
|
+
? `has more than ${count} decimals`
|
|
42
|
+
: `is ${received}, not a finite number`;
|
|
43
|
+
|
|
39
44
|
const union = ({ expected, discriminator }) =>
|
|
40
45
|
discriminator === undefined
|
|
41
46
|
? `does not match any of: ${expected.join(', ')}`
|
|
@@ -61,6 +66,7 @@ module.exports = {
|
|
|
61
66
|
range,
|
|
62
67
|
pattern,
|
|
63
68
|
format,
|
|
69
|
+
decimals,
|
|
64
70
|
union,
|
|
65
71
|
reference,
|
|
66
72
|
circular,
|
package/src/locales/uk.js
CHANGED
|
@@ -34,6 +34,11 @@ const pattern = ({ pattern: source }) => `не відповідає шаблон
|
|
|
34
34
|
|
|
35
35
|
const format = ({ format: name }) => `не є коректним ${name}`;
|
|
36
36
|
|
|
37
|
+
const decimals = ({ decimals: count, received }) =>
|
|
38
|
+
received === undefined
|
|
39
|
+
? `має більше знаків після коми, ніж ${count}`
|
|
40
|
+
: `дорівнює ${received} і не є скінченним числом`;
|
|
41
|
+
|
|
37
42
|
const union = ({ expected, discriminator }) =>
|
|
38
43
|
discriminator === undefined
|
|
39
44
|
? `не відповідає жодному з: ${expected.join(', ')}`
|
|
@@ -59,6 +64,7 @@ module.exports = {
|
|
|
59
64
|
range,
|
|
60
65
|
pattern,
|
|
61
66
|
format,
|
|
67
|
+
decimals,
|
|
62
68
|
union,
|
|
63
69
|
reference,
|
|
64
70
|
circular,
|
package/src/metadata.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
const { getKindMetadata } = require('./kinds.js');
|
|
2
|
-
const {
|
|
3
|
-
const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
|
|
4
|
-
const { isThenable } = require('./issues.js');
|
|
5
|
-
const { safeString } = require('./util.js');
|
|
2
|
+
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
3
|
|
|
7
4
|
// The functions of a schema definition that are the schema's own: its
|
|
8
5
|
// validate, its decoder, its serializer and `format`.
|
|
@@ -61,6 +58,10 @@ class SchemaMetadata {
|
|
|
61
58
|
|
|
62
59
|
#setMany(values) {
|
|
63
60
|
const { kind, scope, store, allow, parent, unknown, ...custom } = values;
|
|
61
|
+
if (custom.coerce !== undefined && typeof custom.coerce !== 'boolean') {
|
|
62
|
+
const reason = `Schema metadata "coerce" must be a boolean, got ${JSON.stringify(custom.coerce)}`;
|
|
63
|
+
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
64
|
+
}
|
|
64
65
|
this.kind = kind || this.kind;
|
|
65
66
|
this.scope = scope || this.scope;
|
|
66
67
|
this.store = store || this.store;
|
|
@@ -91,25 +92,6 @@ class SchemaMetadata {
|
|
|
91
92
|
}
|
|
92
93
|
return fields;
|
|
93
94
|
}
|
|
94
|
-
|
|
95
|
-
// Runs only the schema-level validate function, as a result of its own; a
|
|
96
|
-
// function that returns a promise is an error here, as in check.
|
|
97
|
-
validate(value, path = '') {
|
|
98
|
-
if (!this.options.validate) return null;
|
|
99
|
-
const result = new ValidationResult();
|
|
100
|
-
try {
|
|
101
|
-
const output = this.options.validate.call(this, value, path);
|
|
102
|
-
if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
|
|
103
|
-
return result.add(output);
|
|
104
|
-
} catch (error) {
|
|
105
|
-
if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
|
|
106
|
-
return result.add({
|
|
107
|
-
code: 'exception',
|
|
108
|
-
message: `validation failed ${safeString(error)}`,
|
|
109
|
-
params: { error },
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
95
|
}
|
|
114
96
|
|
|
115
|
-
module.exports = {
|
|
97
|
+
module.exports = { SchemaMetadata };
|
package/src/model/data.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// snapshot is input (a file, a registry, another program), so what it says
|
|
4
4
|
// is checked before it is read, and every error is ERR_INVALID_SNAPSHOT
|
|
5
5
|
// located in the entity, never a bare SyntaxError or TypeError.
|
|
6
|
-
const { hasBrand, define } = require('../util.js');
|
|
6
|
+
const { hasBrand, define, isDate, isRegExp } = require('../util.js');
|
|
7
7
|
const { FORMAT } = require('../snapshot.js');
|
|
8
8
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
9
9
|
const { isStruct } = require('../struct.js');
|
|
@@ -32,12 +32,24 @@ const isSnapshot = (value) =>
|
|
|
32
32
|
isObject(value.entities) &&
|
|
33
33
|
(value.types === undefined || isObject(value.types));
|
|
34
34
|
|
|
35
|
-
// The snapshot of
|
|
36
|
-
|
|
35
|
+
// The entity a snapshot of one schema is about, when it names one: a key
|
|
36
|
+
// format 1 gained in 3.4, read by nothing else.
|
|
37
|
+
const checkRoot = (snapshot) => {
|
|
38
|
+
const { root } = snapshot;
|
|
39
|
+
if (root === undefined) return;
|
|
40
|
+
if (typeof root !== 'string' || !Object.hasOwn(snapshot.entities, root)) {
|
|
41
|
+
throw invalidSnapshot('The root of a snapshot must name one of its entities');
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// The snapshot of a model, or the snapshot given, read as one (the writer of
|
|
46
|
+
// the core is `snapshotOf` of snapshot.js).
|
|
47
|
+
const readSnapshot = (target) => {
|
|
37
48
|
if (hasBrand(target, 'Model')) return target.toJSON();
|
|
38
49
|
if (!isSnapshot(target)) {
|
|
39
50
|
throw invalidSnapshot(`A Model or a snapshot of format ${FORMAT} with entities is expected`);
|
|
40
51
|
}
|
|
52
|
+
checkRoot(target);
|
|
41
53
|
return target;
|
|
42
54
|
};
|
|
43
55
|
|
|
@@ -49,12 +61,12 @@ const same = (a, b, depth = 0) => {
|
|
|
49
61
|
if (a === b) return true;
|
|
50
62
|
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
|
|
51
63
|
if (depth > DEPTH) throw tooDeep();
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
64
|
+
// By their shape, which a value of JSON cannot fake: `{ constructor: {
|
|
65
|
+
// name: 'Date' } }` of a snapshot is data.
|
|
66
|
+
const regExp = isRegExp(a);
|
|
67
|
+
if (regExp || isRegExp(b) || isDate(a) || isDate(b)) {
|
|
68
|
+
if (regExp) return isRegExp(b) && a.source === b.source && a.flags === b.flags;
|
|
69
|
+
return isDate(a) && isDate(b) && a.getTime() === b.getTime();
|
|
58
70
|
}
|
|
59
71
|
if (Array.isArray(a)) {
|
|
60
72
|
if (!Array.isArray(b) || a.length !== b.length) return false;
|
|
@@ -106,6 +118,47 @@ const structDefinitionOf = (fields) => {
|
|
|
106
118
|
return def;
|
|
107
119
|
};
|
|
108
120
|
|
|
121
|
+
// The kind metadata of a built schema, as its definition gave it.
|
|
122
|
+
const metadataOf = (schema) => {
|
|
123
|
+
const { kind, scope, store, allow, unknown, custom } = schema;
|
|
124
|
+
return { kind, scope, store, allow, unknown, ...custom };
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// A struct definition: the kind of `base` (unless `metadata` names one) as
|
|
128
|
+
// its first key, so the fields after it read as a struct whatever their names.
|
|
129
|
+
const structDefinition = (base, metadata, fields) => {
|
|
130
|
+
const { kind = base.kind, ...rest } = { ...base, ...metadata };
|
|
131
|
+
const definition = { [capitalize(kind)]: rest };
|
|
132
|
+
for (const key of Object.keys(fields)) define(definition, key, fields[key]);
|
|
133
|
+
return definition;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// The namespaces of a schema built from schemas: theirs, and for a schema
|
|
137
|
+
// that names itself without a model holding it (`parent: '?Category'`
|
|
138
|
+
// resolves to the schema itself), one that holds it, so that what is built
|
|
139
|
+
// from it, under its name or another, reaches the schema it was built from
|
|
140
|
+
// as it did.
|
|
141
|
+
const namespacesOf = (schemas) => {
|
|
142
|
+
const namespaces = new Set();
|
|
143
|
+
for (const schema of schemas) {
|
|
144
|
+
const { name } = schema;
|
|
145
|
+
let held = false;
|
|
146
|
+
for (const ns of schema.namespaces) {
|
|
147
|
+
namespaces.add(ns);
|
|
148
|
+
if (ns.entities.get(name) !== undefined) held = true;
|
|
149
|
+
}
|
|
150
|
+
if (name !== '' && !held && schema.references.has(name)) {
|
|
151
|
+
namespaces.add({
|
|
152
|
+
entities: new Map([[name, schema]]),
|
|
153
|
+
get types() {
|
|
154
|
+
return schema.types;
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return Array.from(namespaces);
|
|
160
|
+
};
|
|
161
|
+
|
|
109
162
|
module.exports = {
|
|
110
163
|
DEPTH,
|
|
111
164
|
invalidSnapshot,
|
|
@@ -113,10 +166,14 @@ module.exports = {
|
|
|
113
166
|
atSchema,
|
|
114
167
|
isObject,
|
|
115
168
|
isSnapshot,
|
|
116
|
-
|
|
169
|
+
checkRoot,
|
|
170
|
+
readSnapshot,
|
|
117
171
|
same,
|
|
118
172
|
isFunctionMarker,
|
|
119
173
|
capitalize,
|
|
120
174
|
definitionOf,
|
|
121
175
|
structDefinitionOf,
|
|
176
|
+
metadataOf,
|
|
177
|
+
structDefinition,
|
|
178
|
+
namespacesOf,
|
|
122
179
|
};
|
package/src/model/diff.js
CHANGED
|
@@ -15,7 +15,7 @@ const {
|
|
|
15
15
|
invalidSnapshot,
|
|
16
16
|
atSchema,
|
|
17
17
|
isObject,
|
|
18
|
-
|
|
18
|
+
readSnapshot,
|
|
19
19
|
same,
|
|
20
20
|
isFunctionMarker,
|
|
21
21
|
} = require('./data.js');
|
|
@@ -188,8 +188,8 @@ const diffEntity = (name, old, current, changes) => {
|
|
|
188
188
|
// entities of `next` in their order (added, or their changes), the entities
|
|
189
189
|
// that are gone, then the types.
|
|
190
190
|
const diff = (prev, next) => {
|
|
191
|
-
const old =
|
|
192
|
-
const current =
|
|
191
|
+
const old = readSnapshot(prev);
|
|
192
|
+
const current = readSnapshot(next);
|
|
193
193
|
const changes = [];
|
|
194
194
|
for (const name of Object.keys(current.entities)) {
|
|
195
195
|
const to = current.entities[name];
|
|
@@ -243,7 +243,8 @@ const includes = (list, value) => {
|
|
|
243
243
|
return false;
|
|
244
244
|
};
|
|
245
245
|
|
|
246
|
-
// Values added accept more (backward), values removed accept less (forward)
|
|
246
|
+
// Values added accept more (backward), values removed accept less (forward);
|
|
247
|
+
// the names of flags the same way.
|
|
247
248
|
const enumLevel = (from, to) => {
|
|
248
249
|
let level = FULL;
|
|
249
250
|
for (const value of to) if (!includes(from, value)) level &= BACKWARD;
|
|
@@ -325,11 +326,13 @@ const keyLevel = (key, from, to, field) => {
|
|
|
325
326
|
case 'min':
|
|
326
327
|
return boundLevel(from, to, true);
|
|
327
328
|
case 'max':
|
|
329
|
+
case 'decimals':
|
|
328
330
|
return boundLevel(from, to, false);
|
|
329
331
|
case 'pattern':
|
|
330
332
|
case 'format':
|
|
331
333
|
return from === undefined ? FORWARD : to === undefined ? BACKWARD : NONE;
|
|
332
334
|
case 'enum':
|
|
335
|
+
case 'flags':
|
|
333
336
|
return Array.isArray(from) && Array.isArray(to) ? enumLevel(from, to) : NONE;
|
|
334
337
|
case 'validate':
|
|
335
338
|
case 'parse':
|
package/src/model/index.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// program that only validates does not carry them. The functions take
|
|
7
7
|
// Models, Schemas, snapshots or samples; `register()` installs them as
|
|
8
8
|
// members of the classes for the programs that want the methods.
|
|
9
|
-
const { Schema } = require('../
|
|
9
|
+
const { Schema } = require('../validation.js');
|
|
10
10
|
const { Model } = require('../model.js');
|
|
11
11
|
const { fromJSON } = require('./restore.js');
|
|
12
12
|
const { diff, compatibility, compatibilityOf } = require('./diff.js');
|