@alexify/metaschema 3.1.0 → 3.3.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 +314 -1
- package/README.md +535 -20
- package/SECURITY.md +26 -7
- package/index.d.ts +496 -2
- package/package.json +53 -5
- package/src/codec.js +239 -74
- package/src/coerce/index.d.ts +34 -0
- package/src/coerce/index.js +352 -0
- package/src/compile/code.js +1 -1
- package/src/compile/emit.js +32 -7
- package/src/compile/index.d.ts +6 -0
- package/src/compile/index.js +12 -1
- package/src/context.js +11 -10
- package/src/derive/index.d.ts +86 -0
- package/src/derive/index.js +266 -0
- package/src/errors.js +28 -1
- package/src/formats/index.d.ts +31 -0
- package/src/formats/index.js +557 -0
- package/src/generators/fromjsonschema.js +16 -14
- package/src/generators/index.js +2 -1
- package/src/generators/jsonschema.js +47 -13
- package/src/issues.js +37 -20
- package/src/kinds.js +11 -2
- package/src/lint.js +24 -0
- package/src/locales/en.js +11 -2
- package/src/locales/uk.js +10 -2
- package/src/metadata.js +7 -2
- package/src/model/data.js +17 -0
- package/src/model/diff.js +1 -0
- package/src/model/index.d.ts +14 -2
- package/src/model/index.js +13 -10
- package/src/model/infer.js +483 -0
- package/src/model/merge.js +10 -6
- package/src/model/restore.js +3 -3
- package/src/model/sample.js +8 -5
- package/src/model.js +34 -4
- package/src/mongodb/bson.js +118 -0
- package/src/mongodb/document.js +209 -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 -0
- package/src/prototypes/abstract.js +9 -3
- package/src/prototypes/collections.js +4 -3
- package/src/prototypes/scalars.js +4 -4
- package/src/prototypes/union.js +2 -2
- package/src/result.js +6 -0
- package/src/rules.js +53 -4
- package/src/schema.js +53 -28
- package/src/snapshot.js +1 -1
- package/src/stream/index.d.ts +68 -0
- package/src/stream/index.js +247 -0
- package/src/struct.js +1 -1
- package/src/types.js +33 -1
- package/src/util.js +18 -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,
|
|
@@ -295,11 +309,12 @@ const reference = (field, context) => {
|
|
|
295
309
|
const name = field.type;
|
|
296
310
|
const target = field.root.findReference(name);
|
|
297
311
|
let json;
|
|
312
|
+
const id = context.objectIds ? { bsonType: 'objectId' } : typed('string', context);
|
|
298
313
|
if (target === null) {
|
|
299
314
|
if (field.embed === true) json = unrepresentable(context, `Reference "${name}" (embed)`);
|
|
300
|
-
else json =
|
|
315
|
+
else json = id;
|
|
301
316
|
} else if (!embeds(target, field.embed, context.references)) {
|
|
302
|
-
json =
|
|
317
|
+
json = id;
|
|
303
318
|
} else {
|
|
304
319
|
json = definition(target, context);
|
|
305
320
|
}
|
|
@@ -331,7 +346,16 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
331
346
|
const json = typed('string', context);
|
|
332
347
|
if (context.strict) return json;
|
|
333
348
|
bounds(json, field.length, 'minLength', 'maxLength');
|
|
349
|
+
// A format a validator may not know (`ulid`, `iban`) is asserted by its
|
|
350
|
+
// shape too, where the field has no pattern of its own.
|
|
351
|
+
const shape = field.format === undefined ? undefined : FORMATS[field.format]?.pattern;
|
|
334
352
|
if (field.pattern !== undefined) json.pattern = field.pattern.source;
|
|
353
|
+
else if (shape !== undefined) json.pattern = shape;
|
|
354
|
+
// The names are those of JSON Schema; a $jsonSchema has no `format`.
|
|
355
|
+
if (field.format !== undefined && !context.mongo) {
|
|
356
|
+
const byte = field.format === 'base64' && context.target.byte === true;
|
|
357
|
+
json.format = byte ? 'byte' : field.format;
|
|
358
|
+
}
|
|
335
359
|
return json;
|
|
336
360
|
},
|
|
337
361
|
number: (field, context) => ranged(typed('number', context), field, context),
|
|
@@ -371,12 +395,7 @@ const RENDER = Object.assign(Object.create(null), {
|
|
|
371
395
|
|
|
372
396
|
// The built-in type a field validates as: its own, or the one its alias
|
|
373
397
|
// chain ends in.
|
|
374
|
-
const baseOf = (field) =>
|
|
375
|
-
const { types } = field.root;
|
|
376
|
-
let Type = field.constructor;
|
|
377
|
-
while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
|
|
378
|
-
return Type.type;
|
|
379
|
-
};
|
|
398
|
+
const baseOf = (field) => baseTypeOf(field).type;
|
|
380
399
|
|
|
381
400
|
// The schema of the type of a field: the metadata of a custom type when it
|
|
382
401
|
// says (`jsonSchema`, or `bson` for mongodb), else the built-in it is or
|
|
@@ -405,14 +424,20 @@ const render = (field, context) => {
|
|
|
405
424
|
// A struct: its validated fields as properties (a calculated field is a
|
|
406
425
|
// function and has no schema), the required ones listed, no other keys
|
|
407
426
|
// unless the schema ignores them. The strict profile lists every property.
|
|
408
|
-
const struct = (fields, context) => {
|
|
427
|
+
const struct = (fields, context, id = null, root = false) => {
|
|
409
428
|
const properties = {};
|
|
410
429
|
const required = [];
|
|
430
|
+
// The id field of a stored record is `_id` in the document, the first key;
|
|
431
|
+
// the database gives one to a record inserted without it.
|
|
432
|
+
if (id !== null) {
|
|
433
|
+
properties[ID] = { bsonType: 'objectId' };
|
|
434
|
+
if (root) required.push(ID);
|
|
435
|
+
}
|
|
411
436
|
// A struct is a null-prototype dictionary: its own keys, in order; a key
|
|
412
437
|
// such as `__proto__` is defined as data on the document.
|
|
413
438
|
for (const key in fields) {
|
|
414
439
|
const field = fields[key];
|
|
415
|
-
if (!hasBrand(field, 'Type')) continue;
|
|
440
|
+
if (key === id || !hasBrand(field, 'Type')) continue;
|
|
416
441
|
try {
|
|
417
442
|
define(properties, key, render(field, context));
|
|
418
443
|
} catch (error) {
|
|
@@ -428,14 +453,23 @@ const struct = (fields, context) => {
|
|
|
428
453
|
return json;
|
|
429
454
|
};
|
|
430
455
|
|
|
456
|
+
// The id field a stored kind adds, which `ids: 'objectId'` writes as `_id`,
|
|
457
|
+
// unless the schema has an `_id` of its own.
|
|
458
|
+
const idOf = (schema, context) => {
|
|
459
|
+
if (!context.objectIds) return null;
|
|
460
|
+
const id = idFieldOf(schema);
|
|
461
|
+
return id === null || ID in schema.fields ? null : id;
|
|
462
|
+
};
|
|
463
|
+
|
|
431
464
|
// The schema being rendered owns the location of an error met in it, and
|
|
432
465
|
// is restored when the rendering leaves it, thrown out of or not.
|
|
433
|
-
const renderSchema = (schema, context) => {
|
|
466
|
+
const renderSchema = (schema, context, root = false) => {
|
|
434
467
|
const { owner } = context;
|
|
435
468
|
const { fields } = schema;
|
|
436
469
|
context.owner = schema.name;
|
|
437
470
|
try {
|
|
438
|
-
|
|
471
|
+
if (!isStruct(fields)) return render(fields, context);
|
|
472
|
+
return struct(fields, context, idOf(schema, context), root);
|
|
439
473
|
} finally {
|
|
440
474
|
context.owner = owner;
|
|
441
475
|
}
|
|
@@ -450,7 +484,7 @@ const renderRoot = (schema, context) => {
|
|
|
450
484
|
`Profile "strict" needs a struct at the root, got "${schema.fields.type}"`,
|
|
451
485
|
);
|
|
452
486
|
}
|
|
453
|
-
const json = renderSchema(schema, context);
|
|
487
|
+
const json = renderSchema(schema, context, true);
|
|
454
488
|
// Every stored document has an `_id`; a closed mongodb root must let it in.
|
|
455
489
|
if (context.mongo && json.additionalProperties === false && json.properties[ID] === undefined) {
|
|
456
490
|
json.properties[ID] = {};
|
package/src/issues.js
CHANGED
|
@@ -54,6 +54,7 @@ const issues = {
|
|
|
54
54
|
length: (context, min, max, actual, key) => record(context, 'length', { min, max, actual }, key),
|
|
55
55
|
range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
|
|
56
56
|
pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
|
|
57
|
+
format: (context, format, key) => record(context, 'format', { format }, key),
|
|
57
58
|
union: (context, expected, discriminator, key) =>
|
|
58
59
|
record(context, 'union', { expected, discriminator }, key),
|
|
59
60
|
reference: (context, entity, key) => record(context, 'reference', { entity }, key),
|
|
@@ -173,6 +174,16 @@ const abandon = (thenable) => {
|
|
|
173
174
|
Promise.resolve(thenable).then(undefined, swallow);
|
|
174
175
|
};
|
|
175
176
|
|
|
177
|
+
// Drops the entries of a list of pending validators from `from` on (a failed
|
|
178
|
+
// branch of a union, a trial of parse, a settle stopped by the error limit):
|
|
179
|
+
// their promises are observed, never awaited.
|
|
180
|
+
const release = (list, from) => {
|
|
181
|
+
for (let index = from; index < list.length; index += 1) {
|
|
182
|
+
if (list[index].promise !== null) abandon(list[index].promise);
|
|
183
|
+
}
|
|
184
|
+
list.length = from;
|
|
185
|
+
};
|
|
186
|
+
|
|
176
187
|
// The params of a bare `false`: for a checkType the type it expected and what
|
|
177
188
|
// it got, built only now that there is something to record.
|
|
178
189
|
const fallbackOf = (code, owner, value) =>
|
|
@@ -185,20 +196,32 @@ const conclude = (context, output, code, owner, value) => {
|
|
|
185
196
|
absorb(context, output, code, bare ? fallbackOf(code, owner, value) : EMPTY);
|
|
186
197
|
};
|
|
187
198
|
|
|
199
|
+
// Whether a path lies under a prefix: the prefix itself, or a key below it.
|
|
200
|
+
const under = (prefix, path) => {
|
|
201
|
+
if (path.length < prefix.length) return false;
|
|
202
|
+
for (let index = 0; index < prefix.length; index += 1) {
|
|
203
|
+
if (path[index] !== prefix[index]) return false;
|
|
204
|
+
}
|
|
205
|
+
return true;
|
|
206
|
+
};
|
|
207
|
+
|
|
188
208
|
// Where user code runs (a validator, a custom checkType; the decoders have
|
|
189
209
|
// their own place in codec.js): an exception is reported as an issue, not
|
|
190
210
|
// thrown, and the function gets the value and the dotted path of the field,
|
|
191
211
|
// called on its owner here rather than through a closure made per call. In
|
|
192
212
|
// an async check (`context.async` is a list) a promise is kept with the path
|
|
193
|
-
// it was met at, and
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
//
|
|
213
|
+
// it was met at, and a validator met later is kept too, uncalled, when a
|
|
214
|
+
// promise is pending under its path (the fields of the value it validates
|
|
215
|
+
// were met before it, so their entries are the end of the list), so that the
|
|
216
|
+
// rule "a validator runs only when nothing under it failed" holds over the
|
|
217
|
+
// promises as well; every other validator runs at once, as in check, and
|
|
218
|
+
// its promise is in flight with the rest. `settle` runs the list after the
|
|
219
|
+
// walk, in field order. In a synchronous check a promise is an error of the
|
|
220
|
+
// call.
|
|
198
221
|
const guarded = (context, code, owner, fn, value) => {
|
|
199
222
|
const pending = context.async;
|
|
200
223
|
const { path, count } = context;
|
|
201
|
-
if (pending !== null && pending.length > 0) {
|
|
224
|
+
if (pending !== null && pending.length > 0 && under(path, pending[pending.length - 1].path)) {
|
|
202
225
|
pending.push({ owner, fn, value, promise: null, path: path.slice(), code, count });
|
|
203
226
|
return;
|
|
204
227
|
}
|
|
@@ -224,29 +247,22 @@ const guarded = (context, code, owner, fn, value) => {
|
|
|
224
247
|
// path: the fields of the value it validates were checked before it.
|
|
225
248
|
const failedUnder = (context, entry) => {
|
|
226
249
|
const { issues: list } = context;
|
|
227
|
-
const { path } = entry;
|
|
228
250
|
for (let index = entry.count; index < list.length; index += 1) {
|
|
229
|
-
|
|
230
|
-
if (recorded.length < path.length) continue;
|
|
231
|
-
let under = true;
|
|
232
|
-
for (let depth = 0; depth < path.length && under; depth += 1) {
|
|
233
|
-
under = recorded[depth] === path[depth];
|
|
234
|
-
}
|
|
235
|
-
if (under) return true;
|
|
251
|
+
if (under(entry.path, list[index].path)) return true;
|
|
236
252
|
}
|
|
237
253
|
return false;
|
|
238
254
|
};
|
|
239
255
|
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
//
|
|
256
|
+
// Settles the entries an async check kept, in the order they were met: a
|
|
257
|
+
// promise is awaited (it has been in flight since the walk), a validator kept
|
|
258
|
+
// uncalled is called once the promises under it have settled, each recording
|
|
259
|
+
// under the path it was met at; the error limit stops the list as it stops
|
|
260
|
+
// the walk.
|
|
243
261
|
const settle = async (context) => {
|
|
244
262
|
const pending = context.async;
|
|
245
263
|
for (let index = 0; index < pending.length; index += 1) {
|
|
246
264
|
if (context.count >= context.limit) {
|
|
247
|
-
|
|
248
|
-
if (pending[index].promise !== null) abandon(pending[index].promise);
|
|
249
|
-
}
|
|
265
|
+
release(pending, index);
|
|
250
266
|
break;
|
|
251
267
|
}
|
|
252
268
|
const entry = pending[index];
|
|
@@ -285,6 +301,7 @@ module.exports = {
|
|
|
285
301
|
describe,
|
|
286
302
|
isThenable,
|
|
287
303
|
abandon,
|
|
304
|
+
release,
|
|
288
305
|
runValidate,
|
|
289
306
|
runCheckType,
|
|
290
307
|
settle,
|
package/src/kinds.js
CHANGED
|
@@ -33,12 +33,21 @@ const projection = (kind, meta, root) => {
|
|
|
33
33
|
return { defs, metadata };
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
+
// The key of the id field a stored kind adds: named after the entity
|
|
37
|
+
// (`orderId`), `id` for an anonymous schema.
|
|
38
|
+
const idKeyOf = (name) => (name ? `${toLowerCamel(name)}Id` : 'id');
|
|
39
|
+
|
|
40
|
+
// The id field of a built schema: the key above for a stored kind, null for
|
|
41
|
+
// a memory kind. The one rule, read by the derive, mongodb and generators
|
|
42
|
+
// subpaths (which each add what `_id` means to them).
|
|
43
|
+
const idFieldOf = (schema) => (KIND_STORED.includes(schema.kind) ? idKeyOf(schema.name) : null);
|
|
44
|
+
|
|
36
45
|
// The metadata of a kind over the defaults of its scope and store; a stored
|
|
37
46
|
// kind adds the optional id field named after the entity.
|
|
38
47
|
const kindOf = (defaultScope, defaultStore, stored) => (kind, meta, root) => {
|
|
39
48
|
const { scope = defaultScope, store = defaultStore, allow = 'write' } = meta;
|
|
40
49
|
const defs = Object.create(null);
|
|
41
|
-
if (stored) defs[
|
|
50
|
+
if (stored) defs[idKeyOf(root.name)] = '?string';
|
|
42
51
|
return { defs, metadata: { ...meta, kind, scope, store, allow } };
|
|
43
52
|
};
|
|
44
53
|
|
|
@@ -62,4 +71,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
|
|
|
62
71
|
|
|
63
72
|
const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
|
|
64
73
|
|
|
65
|
-
module.exports = { constants, getKindMetadata };
|
|
74
|
+
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']);
|
|
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,12 @@ 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.coerce !== undefined) {
|
|
74
|
+
const dead = deadCoerce(field);
|
|
75
|
+
if (dead !== '') {
|
|
76
|
+
warnings.push(warning('dead-coerce', `"${path}" has coerce, but ${dead} is never converted`));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
55
79
|
if (field.schema !== undefined) lintStruct(field.schema, path, warnings);
|
|
56
80
|
const { value, union } = field;
|
|
57
81
|
if (value !== undefined) {
|
package/src/locales/en.js
CHANGED
|
@@ -10,10 +10,16 @@ const required = () => 'is required';
|
|
|
10
10
|
const type = ({ expected, key }) =>
|
|
11
11
|
key === undefined ? `not of expected type: ${expected}` : `keys must be of type ${expected}`;
|
|
12
12
|
|
|
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
|
+
|
|
13
18
|
const list = (keys) => {
|
|
19
|
+
const count = Math.min(keys.length, SHOWN);
|
|
14
20
|
let text = shorten(keys[0]);
|
|
15
|
-
for (let index = 1; index <
|
|
16
|
-
return text;
|
|
21
|
+
for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
|
|
22
|
+
return keys.length > SHOWN ? `${text} and ${keys.length - SHOWN} more` : text;
|
|
17
23
|
};
|
|
18
24
|
|
|
19
25
|
const unexpected = ({ keys }) => `has unexpected keys: ${list(keys)}`;
|
|
@@ -28,6 +34,8 @@ const range = ({ min, max, actual }) =>
|
|
|
28
34
|
|
|
29
35
|
const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
|
|
30
36
|
|
|
37
|
+
const format = ({ format: name }) => `is not a valid ${name}`;
|
|
38
|
+
|
|
31
39
|
const union = ({ expected, discriminator }) =>
|
|
32
40
|
discriminator === undefined
|
|
33
41
|
? `does not match any of: ${expected.join(', ')}`
|
|
@@ -52,6 +60,7 @@ module.exports = {
|
|
|
52
60
|
length,
|
|
53
61
|
range,
|
|
54
62
|
pattern,
|
|
63
|
+
format,
|
|
55
64
|
union,
|
|
56
65
|
reference,
|
|
57
66
|
circular,
|
package/src/locales/uk.js
CHANGED
|
@@ -9,10 +9,15 @@ const required = () => 'є обовʼязковим';
|
|
|
9
9
|
const type = ({ expected, key }) =>
|
|
10
10
|
key === undefined ? `не відповідає типу: ${expected}` : `ключі мають бути типу ${expected}`;
|
|
11
11
|
|
|
12
|
+
// Перші ключі списку і скільки їх ще: значення з мільйоном невідомих ключів
|
|
13
|
+
// є одним issue, і його повідомлення не є цим мільйоном.
|
|
14
|
+
const SHOWN = 10;
|
|
15
|
+
|
|
12
16
|
const list = (keys) => {
|
|
17
|
+
const count = Math.min(keys.length, SHOWN);
|
|
13
18
|
let text = shorten(keys[0]);
|
|
14
|
-
for (let index = 1; index <
|
|
15
|
-
return text;
|
|
19
|
+
for (let index = 1; index < count; index += 1) text += `, ${shorten(keys[index])}`;
|
|
20
|
+
return keys.length > SHOWN ? `${text} і ще ${keys.length - SHOWN}` : text;
|
|
16
21
|
};
|
|
17
22
|
|
|
18
23
|
const unexpected = ({ keys }) => `має неочікувані ключі: ${list(keys)}`;
|
|
@@ -27,6 +32,8 @@ const range = ({ min, max, actual }) =>
|
|
|
27
32
|
|
|
28
33
|
const pattern = ({ pattern: source }) => `не відповідає шаблону ${source}`;
|
|
29
34
|
|
|
35
|
+
const format = ({ format: name }) => `не є коректним ${name}`;
|
|
36
|
+
|
|
30
37
|
const union = ({ expected, discriminator }) =>
|
|
31
38
|
discriminator === undefined
|
|
32
39
|
? `не відповідає жодному з: ${expected.join(', ')}`
|
|
@@ -51,6 +58,7 @@ module.exports = {
|
|
|
51
58
|
length,
|
|
52
59
|
range,
|
|
53
60
|
pattern,
|
|
61
|
+
format,
|
|
54
62
|
union,
|
|
55
63
|
reference,
|
|
56
64
|
circular,
|
package/src/metadata.js
CHANGED
|
@@ -2,6 +2,7 @@ const { getKindMetadata } = require('./kinds.js');
|
|
|
2
2
|
const { ValidationResult } = require('./result.js');
|
|
3
3
|
const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
|
|
4
4
|
const { isThenable } = require('./issues.js');
|
|
5
|
+
const { safeString } = require('./util.js');
|
|
5
6
|
|
|
6
7
|
// The functions of a schema definition that are the schema's own: its
|
|
7
8
|
// validate, its decoder, its serializer and `format`.
|
|
@@ -60,6 +61,10 @@ class SchemaMetadata {
|
|
|
60
61
|
|
|
61
62
|
#setMany(values) {
|
|
62
63
|
const { kind, scope, store, allow, parent, unknown, ...custom } = values;
|
|
64
|
+
if (custom.coerce !== undefined && typeof custom.coerce !== 'boolean') {
|
|
65
|
+
const reason = `Schema metadata "coerce" must be a boolean, got ${JSON.stringify(custom.coerce)}`;
|
|
66
|
+
throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
67
|
+
}
|
|
63
68
|
this.kind = kind || this.kind;
|
|
64
69
|
this.scope = scope || this.scope;
|
|
65
70
|
this.store = store || this.store;
|
|
@@ -101,10 +106,10 @@ class SchemaMetadata {
|
|
|
101
106
|
if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
|
|
102
107
|
return result.add(output);
|
|
103
108
|
} catch (error) {
|
|
104
|
-
if (error
|
|
109
|
+
if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
|
|
105
110
|
return result.add({
|
|
106
111
|
code: 'exception',
|
|
107
|
-
message: `validation failed ${error}`,
|
|
112
|
+
message: `validation failed ${safeString(error)}`,
|
|
108
113
|
params: { error },
|
|
109
114
|
});
|
|
110
115
|
}
|
package/src/model/data.js
CHANGED
|
@@ -106,6 +106,21 @@ const structDefinitionOf = (fields) => {
|
|
|
106
106
|
return def;
|
|
107
107
|
};
|
|
108
108
|
|
|
109
|
+
// The kind metadata of a built schema, as its definition gave it.
|
|
110
|
+
const metadataOf = (schema) => {
|
|
111
|
+
const { kind, scope, store, allow, unknown, custom } = schema;
|
|
112
|
+
return { kind, scope, store, allow, unknown, ...custom };
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// A struct definition: the kind of `base` (unless `metadata` names one) as
|
|
116
|
+
// its first key, so the fields after it read as a struct whatever their names.
|
|
117
|
+
const structDefinition = (base, metadata, fields) => {
|
|
118
|
+
const { kind = base.kind, ...rest } = { ...base, ...metadata };
|
|
119
|
+
const definition = { [capitalize(kind)]: rest };
|
|
120
|
+
for (const key of Object.keys(fields)) define(definition, key, fields[key]);
|
|
121
|
+
return definition;
|
|
122
|
+
};
|
|
123
|
+
|
|
109
124
|
module.exports = {
|
|
110
125
|
DEPTH,
|
|
111
126
|
invalidSnapshot,
|
|
@@ -119,4 +134,6 @@ module.exports = {
|
|
|
119
134
|
capitalize,
|
|
120
135
|
definitionOf,
|
|
121
136
|
structDefinitionOf,
|
|
137
|
+
metadataOf,
|
|
138
|
+
structDefinition,
|
|
122
139
|
};
|
package/src/model/diff.js
CHANGED
|
@@ -327,6 +327,7 @@ const keyLevel = (key, from, to, field) => {
|
|
|
327
327
|
case 'max':
|
|
328
328
|
return boundLevel(from, to, false);
|
|
329
329
|
case 'pattern':
|
|
330
|
+
case 'format':
|
|
330
331
|
return from === undefined ? FORWARD : to === undefined ? BACKWARD : NONE;
|
|
331
332
|
case 'enum':
|
|
332
333
|
return Array.isArray(from) && Array.isArray(to) ? enumLevel(from, to) : NONE;
|
package/src/model/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
Compatibility,
|
|
3
3
|
Infer,
|
|
4
|
+
InferOptions,
|
|
4
5
|
MergeOptions,
|
|
5
6
|
Model,
|
|
6
7
|
ModelSnapshot,
|
|
@@ -50,7 +51,18 @@ export function sample<D extends string | object>(
|
|
|
50
51
|
// and the name are the first schema's unless the options say otherwise.
|
|
51
52
|
export function merge(a: Schema, b: Schema, options?: MergeOptions): Schema;
|
|
52
53
|
|
|
54
|
+
// A definition (or a Schema, with `as: 'schema'`) that accepts every sample:
|
|
55
|
+
// the kinds seen at every place, the records of a place fused into one
|
|
56
|
+
// struct with optional keys, a string field of few values as an enum,
|
|
57
|
+
// records of many sparse keys as a dictionary, whole numbers as `integer`.
|
|
58
|
+
// The samples are input: the walk is bounded (`ERR_INFER_DEPTH`), and the
|
|
59
|
+
// definition is checked against every sample before it is returned
|
|
60
|
+
// (`ERR_INFER_MISMATCH` is a bug to report). An argument that is not a
|
|
61
|
+
// non-empty iterable is a `TypeError` with the code `ERR_INVALID_TARGET`.
|
|
62
|
+
export function infer(samples: Iterable<unknown>, options: InferOptions & { as: 'schema' }): Schema;
|
|
63
|
+
export function infer(samples: Iterable<unknown>, options?: InferOptions): object | string;
|
|
64
|
+
|
|
53
65
|
// Installs `Model.fromJSON`, `Model.diff`, `Model.compatibility`,
|
|
54
|
-
// `Model.compatibilityOf`, `Schema.merge
|
|
55
|
-
// process; later calls do nothing.
|
|
66
|
+
// `Model.compatibilityOf`, `Schema.merge`, `Schema.infer` and
|
|
67
|
+
// `schema.sample`. Once per process; later calls do nothing.
|
|
56
68
|
export function register(): void;
|
package/src/model/index.js
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
// The `./model` subpath: the model as the source of truth. A model restored
|
|
2
2
|
// from its snapshot (`fromJSON`), the changes between two versions and their
|
|
3
3
|
// compatibility class (`diff`, `compatibility`, `compatibilityOf`), a value
|
|
4
|
-
// a schema accepts (`sample`), two schemas as one (`merge`),
|
|
5
|
-
// the core entry so
|
|
6
|
-
//
|
|
7
|
-
// Models, Schemas or
|
|
8
|
-
// classes for the programs that want the methods.
|
|
4
|
+
// a schema accepts (`sample`), two schemas as one (`merge`), a definition
|
|
5
|
+
// from the values that exist (`infer`), kept out of the core entry so that a
|
|
6
|
+
// program that only validates does not carry them. The functions take
|
|
7
|
+
// Models, Schemas, snapshots or samples; `register()` installs them as
|
|
8
|
+
// members of the classes for the programs that want the methods.
|
|
9
9
|
const { Schema } = require('../schema.js');
|
|
10
10
|
const { Model } = require('../model.js');
|
|
11
11
|
const { fromJSON } = require('./restore.js');
|
|
12
12
|
const { diff, compatibility, compatibilityOf } = require('./diff.js');
|
|
13
13
|
const { sample } = require('./sample.js');
|
|
14
14
|
const { merge } = require('./merge.js');
|
|
15
|
+
const { infer } = require('./infer.js');
|
|
15
16
|
|
|
16
|
-
// Installed like class members: not enumerable.
|
|
17
|
+
// Installed like class members: not enumerable. A copy per subpath rather
|
|
18
|
+
// than a helper of the core: the core is measured on its own, the subpaths
|
|
19
|
+
// on top of it.
|
|
17
20
|
const install = (target, members) => {
|
|
18
21
|
const descriptors = Object.getOwnPropertyDescriptors(members);
|
|
19
22
|
for (const name in descriptors) {
|
|
@@ -25,13 +28,13 @@ const install = (target, members) => {
|
|
|
25
28
|
let registered = false;
|
|
26
29
|
|
|
27
30
|
// Adds `Model.fromJSON`, `Model.diff`, `Model.compatibility` and
|
|
28
|
-
// `Model.compatibilityOf`, `Schema.merge` and
|
|
29
|
-
// Once per process.
|
|
31
|
+
// `Model.compatibilityOf`, `Schema.merge`, `Schema.infer` and
|
|
32
|
+
// `schema.sample(options)`. Once per process.
|
|
30
33
|
const register = () => {
|
|
31
34
|
if (registered) return;
|
|
32
35
|
registered = true;
|
|
33
36
|
install(Model, { fromJSON, diff, compatibility, compatibilityOf });
|
|
34
|
-
install(Schema, { merge });
|
|
37
|
+
install(Schema, { merge, infer });
|
|
35
38
|
install(Schema.prototype, {
|
|
36
39
|
sample(options) {
|
|
37
40
|
return sample(this, options);
|
|
@@ -39,4 +42,4 @@ const register = () => {
|
|
|
39
42
|
});
|
|
40
43
|
};
|
|
41
44
|
|
|
42
|
-
module.exports = { fromJSON, diff, compatibility, compatibilityOf, sample, merge, register };
|
|
45
|
+
module.exports = { fromJSON, diff, compatibility, compatibilityOf, sample, merge, infer, register };
|