@alexify/metaschema 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,8 +8,8 @@
8
8
  // Generated code names three things: `v` the value, `c` the context and `k`
9
9
  // the key the root was called with. Every other identifier is fresh.
10
10
  const { ENUM_SET_SIZE } = require('../util.js');
11
- const { issues, runValidate } = require('../issues.js');
12
- const { codePoints, lengthOf, ruleNames } = require('../rules.js');
11
+ const { issues, runValidate, release } = require('../issues.js');
12
+ const { FORMATS, codePoints, lengthOf, ruleNames, patternLimit } = require('../rules.js');
13
13
  const { STRUCT, isStruct } = require('../struct.js');
14
14
  const scalars = require('../prototypes/scalars.js');
15
15
  const collections = require('../prototypes/collections.js');
@@ -53,6 +53,14 @@ const typeIssue = (state, expected, x, key) =>
53
53
 
54
54
  const notObject = (x) => `${x} === null || typeof ${x} !== "object" || Array.isArray(${x})`;
55
55
 
56
+ // A built-in by the name of its constructor and by its shape, as util.js
57
+ // tests it: the name alone is what a value parsed from JSON can carry.
58
+ const isDateCode = (x) =>
59
+ `${x}?.constructor?.name === "Date" && typeof ${x}.getTime === "function"`;
60
+
61
+ const isIterableCode = (x, name) =>
62
+ `${x}?.constructor?.name === ${quote(name)} && typeof ${x}[Symbol.iterator] === "function"`;
63
+
56
64
  // The conditions of the bounds a field has.
57
65
  const outside = (state, x, min, max) => {
58
66
  const parts = [];
@@ -77,14 +85,30 @@ const emitLength = (type, x, key, state) => {
77
85
  code.push('}');
78
86
  };
79
87
 
88
+ // The condition that keeps a pattern or a format off a string past
89
+ // length.max, as the closures do.
90
+ const withinLength = (type, x, code) => {
91
+ const limit = patternLimit(type);
92
+ return limit === Infinity ? '' : `${x}.length <= ${code.value(limit)} && `;
93
+ };
94
+
80
95
  const emitPattern = (type, x, key, state) => {
81
96
  const { code } = state;
82
97
  const { pattern } = type;
83
- code.push(`if (!${code.ref(pattern)}.test(${x})) {`);
98
+ code.push(`if (${withinLength(type, x, code)}!${code.ref(pattern)}.test(${x})) {`);
84
99
  record(state, issue(state, 'pattern', `${quote(pattern.source)}, ${keyOf(key)}`));
85
100
  code.push('}');
86
101
  };
87
102
 
103
+ const emitFormat = (type, x, key, state) => {
104
+ const { code } = state;
105
+ const { format } = type;
106
+ const { test } = FORMATS[format];
107
+ code.push(`if (${withinLength(type, x, code)}!${code.ref(test)}(${x})) {`);
108
+ record(state, issue(state, 'format', `${quote(format)}, ${keyOf(key)}`));
109
+ code.push('}');
110
+ };
111
+
88
112
  const emitRange = (type, x, key, state) => {
89
113
  const { code } = state;
90
114
  const { min, max } = type;
@@ -97,6 +121,7 @@ const emitRange = (type, x, key, state) => {
97
121
  const RULES = Object.assign(Object.create(null), {
98
122
  length: emitLength,
99
123
  pattern: emitPattern,
124
+ format: emitFormat,
100
125
  range: emitRange,
101
126
  });
102
127
 
@@ -155,7 +180,7 @@ const emitInteger = (type, x, key, state) =>
155
180
  typed(type, x, key, state, `!Number.isInteger(${x})`, typeIssue(state, 'integer', x, key));
156
181
 
157
182
  const emitDate = (type, x, key, state) => {
158
- const fails = `!(${x}?.constructor?.name === "Date" && !Number.isNaN(${x}.getTime()))`;
183
+ const fails = `!(${isDateCode(x)} && !Number.isNaN(${x}.getTime()))`;
159
184
  typed(type, x, key, state, fails, typeIssue(state, 'date', x, key));
160
185
  };
161
186
 
@@ -228,7 +253,7 @@ const emitObject = (type, x, key, state) => {
228
253
  const emitMap = (type, x, key, state) => {
229
254
  const { code } = state;
230
255
  const failure = typeIssue(state, type.type, x, key);
231
- typed(type, x, key, state, `${x}?.constructor?.name !== "Map"`, failure, () => {
256
+ typed(type, x, key, state, `!(${isIterableCode(x, 'Map')})`, failure, () => {
232
257
  if (type.required) {
233
258
  code.push(`if (${x}.size === 0) {`);
234
259
  record(state, issue(state, 'required', keyOf(key)));
@@ -258,7 +283,7 @@ const emitMap = (type, x, key, state) => {
258
283
  const emitList = (type, x, key, state) => {
259
284
  const { code } = state;
260
285
  const set = type.isInstance === collections.set.isInstance;
261
- const fails = set ? `${x}?.constructor?.name !== "Set"` : `!Array.isArray(${x})`;
286
+ const fails = set ? `!(${isIterableCode(x, 'Set')})` : `!Array.isArray(${x})`;
262
287
  typed(type, x, key, state, fails, typeIssue(state, type.type, x, key), () => {
263
288
  const children = inside(state, key);
264
289
  const index = code.name('i');
@@ -413,7 +438,7 @@ const emitUnion = (type, x, key, state) => {
413
438
  code.push('}');
414
439
  code.push(`if (c.count === ${before}) break ${label};`);
415
440
  code.push(`c.issues.length = ${before}; c.count = ${before};`);
416
- code.push(`if (c.async !== null) c.async.length = ${pending};`);
441
+ code.push(`if (c.async !== null) ${code.ref(release)}(c.async, ${pending});`);
417
442
  }
418
443
  const names = [];
419
444
  for (let index = 0; index < branches.length; index += 1) names.push(nameOf(branches[index]));
@@ -36,3 +36,9 @@ export function register(options?: CompileOptions): void;
36
36
 
37
37
  // Whether this environment allows code generation from strings; probed once.
38
38
  export function canEval(): boolean;
39
+
40
+ // Whether the check of a schema (of every entity of a model) runs generated
41
+ // code now: what `compile` reported, asked later. False for a schema built
42
+ // before `register()` and after `{ jit: false }`; a target that is neither
43
+ // a Schema nor a Model is a `TypeError`.
44
+ export function compiled(target: Schema | Model): boolean;
@@ -153,6 +153,17 @@ const compile = (target, options = {}) => {
153
153
  return error === undefined ? { accelerated: true } : { accelerated: false, error };
154
154
  };
155
155
 
156
+ // Whether the check of a schema (of every entity of a model) runs the
157
+ // generated code now: what `compile` reported, asked later.
158
+ const compiled = (target) => {
159
+ const schemas = schemasOf(target);
160
+ for (let index = 0; index < schemas.length; index += 1) {
161
+ const schema = schemas[index];
162
+ if (!ORIGINAL.has(schema) || schema[RUN] === ORIGINAL.get(schema)) return false;
163
+ }
164
+ return true;
165
+ };
166
+
156
167
  // Compiles every schema built from now on, with these options; a later call
157
168
  // replaces them, and `{ jit: false }` stops it. A schema built before the
158
169
  // call is not touched. In the default mode `onFallback` is told of every
@@ -173,4 +184,4 @@ const register = (options = {}) => {
173
184
  };
174
185
  };
175
186
 
176
- module.exports = { compile, register, canEval };
187
+ module.exports = { compile, compiled, register, canEval };
package/src/context.js CHANGED
@@ -5,17 +5,12 @@
5
5
  const en = require('./locales/en.js');
6
6
 
7
7
  const { NONE } = require('./issues.js');
8
+ const { invalidOption: invalid } = require('./errors.js');
8
9
 
9
10
  // The limit when there is none: the largest small integer, so the comparison
10
11
  // with the count on every field stays an integer comparison.
11
12
  const UNLIMITED = 2 ** 30 - 1;
12
13
 
13
- const shown = (value) =>
14
- typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
15
-
16
- const invalid = (name, expected, value) =>
17
- new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
18
-
19
14
  // A whole number of issues, or no limit at all.
20
15
  const maxErrorsOf = (maxErrors) => {
21
16
  const valid = (Number.isInteger(maxErrors) || maxErrors === Infinity) && maxErrors >= 1;
@@ -126,9 +121,10 @@ const createContext = (options, name = '', unknown = 'reject', parsing = false)
126
121
  references: 'kind',
127
122
  root: name,
128
123
  messages: en,
129
- // The validators that returned a promise, in field order, settled after
130
- // the walk by checkAsync and parseAsync; null in a synchronous check,
131
- // where such a promise is an error.
124
+ // The validators that returned a promise, in field order, and the ones
125
+ // kept uncalled over them, settled after the walk by checkAsync and
126
+ // parseAsync; null in a synchronous check, where such a promise is an
127
+ // error.
132
128
  async: null,
133
129
  // The context parse tries the branches of a plain union in, made at the
134
130
  // first such union of a pass and reused for the rest; null in a check.
package/src/errors.js CHANGED
@@ -43,4 +43,12 @@ const invalidTarget = (message) => {
43
43
  return error;
44
44
  };
45
45
 
46
- module.exports = { SchemaDefinitionError, asyncReturn, invalidTarget };
46
+ const shown = (value) =>
47
+ typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
48
+
49
+ // An option of a call that is not what it must be (`maxErrors`, the options
50
+ // of the stream subpath): a TypeError naming it, as invalidTarget is.
51
+ const invalidOption = (name, expected, value) =>
52
+ new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
53
+
54
+ module.exports = { SchemaDefinitionError, asyncReturn, invalidTarget, invalidOption };
@@ -0,0 +1,19 @@
1
+ // A format a string field may name: a test over the string, the examples
2
+ // `sample` draws, and whether `infer` may read the format out of data (true
3
+ // unless said otherwise; a format every word passes says false).
4
+ export interface FormatDefinition {
5
+ test: (value: string) => boolean;
6
+ examples: readonly string[];
7
+ infer?: boolean;
8
+ }
9
+
10
+ // The formats registered so far, by name: empty until `register()` ran. Read
11
+ // it; `register()` writes it.
12
+ export const FORMATS: { readonly [name: string]: Readonly<FormatDefinition> | undefined };
13
+
14
+ // Registers the built-in formats (`email`, `uuid`, `uri`, `hostname`, `ipv4`,
15
+ // `ipv6`, `date`, `time`, `date-time`) and the program's own, once per name
16
+ // and process-wide, like the type registry: a name registered again with the
17
+ // same test is nothing, with another test `ERR_FORMAT_REGISTERED`, and an
18
+ // entry that is not a format `ERR_INVALID_FORMAT`.
19
+ export function register(custom?: Record<string, FormatDefinition>): void;
@@ -0,0 +1,146 @@
1
+ // The `./formats` subpath: the formats a string field may name
2
+ // (`{ type: 'string', format: 'email' }`). The core knows the rule and keeps
3
+ // an empty table (`FORMATS` in rules.js); `register()` fills it with the
4
+ // nine formats below and with the program's own, so that a program that
5
+ // validates no email carries no email expression. Each format is a `test`
6
+ // function over a string, a few `examples` for `sample`, and whether `infer`
7
+ // may read it out of data (a format every word passes, like a hostname,
8
+ // says not to).
9
+ //
10
+ // The expressions of email, uuid, uri, hostname, ipv4 and ipv6 are those of
11
+ // the fast mode of ajv-formats 3.0.1 (MIT, Copyright (c) 2020 Evgeny
12
+ // Poberezkin), copied with the attribution the project gives for a helper
13
+ // it carries instead of a dependency; they are anchored and linear, with
14
+ // every repetition bounded. The date and time forms are RFC 3339 with the
15
+ // ranges checked (a 31st of February is not a date).
16
+ const { FORMATS } = require('../rules.js');
17
+ const { SchemaDefinitionError } = require('../errors.js');
18
+
19
+ const invalidFormat = (name, reason) =>
20
+ new SchemaDefinitionError('ERR_INVALID_FORMAT', `Format "${name}" ${reason}`);
21
+
22
+ const EMAIL =
23
+ /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;
24
+
25
+ const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
26
+
27
+ const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i;
28
+
29
+ const HOSTNAME =
30
+ /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
31
+
32
+ const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
33
+
34
+ const IPV6 =
35
+ /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i;
36
+
37
+ // A full-date of RFC 3339 with the day within its month, and a full-time
38
+ // (an offset is required, as the RFC says; a leap second is allowed).
39
+ const DATE = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
40
+
41
+ const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
42
+
43
+ const isDate = (text) => {
44
+ const match = DATE.exec(text);
45
+ if (match === null) return false;
46
+ const year = Number(match[1]);
47
+ const month = Number(match[2]);
48
+ const leap = month === 2 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
49
+ return Number(match[3]) <= DAYS[month] + (leap ? 1 : 0);
50
+ };
51
+
52
+ const TIME =
53
+ /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d|60)(?:\.\d+)?(?:[zZ]|([+-])([01]\d|2[0-3])(?::?([0-5]\d))?)$/;
54
+
55
+ // A leap second is the one of 23:59:60 UTC, whatever the offset says.
56
+ const isTime = (text) => {
57
+ const match = TIME.exec(text);
58
+ if (match === null) return false;
59
+ if (match[3] !== '60') return true;
60
+ const sign = match[4] === '-' ? -1 : 1;
61
+ const offset =
62
+ match[4] === undefined ? 0 : sign * (Number(match[5]) * 60 + Number(match[6] ?? 0));
63
+ const minutes = (Number(match[1]) * 60 + Number(match[2]) - offset + 1440) % 1440;
64
+ return minutes === 23 * 60 + 59;
65
+ };
66
+
67
+ // A date-time is the two joined by `T` (or, as the RFC allows for
68
+ // readability, a space).
69
+ const isDateTime = (text) =>
70
+ text.length > 11 &&
71
+ (text[10] === 'T' || text[10] === 't' || text[10] === ' ') &&
72
+ isDate(text.slice(0, 10)) &&
73
+ isTime(text.slice(11));
74
+
75
+ const tested = (expression) => (text) => expression.test(text);
76
+
77
+ // In the order `infer` tries them: a form that is also a hostname (a uuid,
78
+ // a date, an address) comes before it, and a hostname is never inferred,
79
+ // since every word is one.
80
+ const BUILT_IN = {
81
+ uuid: {
82
+ test: tested(UUID),
83
+ examples: ['550e8400-e29b-41d4-a716-446655440000', '123e4567-e89b-12d3-a456-426614174000'],
84
+ },
85
+ email: { test: tested(EMAIL), examples: ['ann@example.com', 'ann.lee@mail.example.org'] },
86
+ 'date-time': {
87
+ test: isDateTime,
88
+ examples: ['2026-10-11T12:00:00Z', '2026-10-11T12:00:00.000+02:00'],
89
+ },
90
+ date: { test: isDate, examples: ['2026-10-11', '2000-02-29'] },
91
+ time: { test: isTime, examples: ['12:00:00Z', '23:59:59.999+02:00'] },
92
+ ipv4: { test: tested(IPV4), examples: ['192.168.0.1', '10.0.0.255'] },
93
+ ipv6: { test: tested(IPV6), examples: ['::1', '2001:db8::ff00:42:8329'] },
94
+ uri: { test: tested(URI), examples: ['https://example.com/path?q=1', 'mailto:ann@example.com'] },
95
+ hostname: { test: tested(HOSTNAME), examples: ['example.com', 'api.example.org'], infer: false },
96
+ };
97
+
98
+ // An entry as the table keeps it: the test, a copy of the examples, and
99
+ // whether infer may read it, frozen.
100
+ const entryOf = (name, entry) => {
101
+ if (entry === null || typeof entry !== 'object') {
102
+ throw invalidFormat(name, 'needs { test, examples }');
103
+ }
104
+ const { test, examples, infer } = entry;
105
+ if (typeof test !== 'function') throw invalidFormat(name, 'needs a test function');
106
+ const listed = Array.isArray(examples) && examples.length > 0;
107
+ if (!listed) throw invalidFormat(name, 'needs a list of example strings');
108
+ for (let index = 0; index < examples.length; index += 1) {
109
+ if (typeof examples[index] !== 'string') {
110
+ throw invalidFormat(name, 'needs a list of example strings');
111
+ }
112
+ }
113
+ if (infer !== undefined && typeof infer !== 'boolean') {
114
+ throw invalidFormat(name, 'needs a boolean infer');
115
+ }
116
+ return Object.freeze({ test, examples: Object.freeze(examples.slice()), infer: infer !== false });
117
+ };
118
+
119
+ // A name is registered once: the same test again is nothing, another test
120
+ // under a registered name is an error, since the schemas built so far hold
121
+ // the first one.
122
+ const add = (name, entry) => {
123
+ if (name === '') throw invalidFormat(name, 'needs a name');
124
+ const known = FORMATS[name];
125
+ if (known !== undefined) {
126
+ if (known.test === entry.test) return;
127
+ throw new SchemaDefinitionError(
128
+ 'ERR_FORMAT_REGISTERED',
129
+ `Format "${name}" is already registered with another test`,
130
+ );
131
+ }
132
+ FORMATS[name] = entryOf(name, entry);
133
+ };
134
+
135
+ // Registers the built-in formats and the program's own
136
+ // (`{ phone: { test, examples } }`); once per name, process-wide, like the
137
+ // type registry. Importing the subpath registers nothing.
138
+ const register = (custom = {}) => {
139
+ if (custom === null || typeof custom !== 'object') {
140
+ throw new SchemaDefinitionError('ERR_INVALID_FORMAT', 'Formats must be an object of entries');
141
+ }
142
+ for (const name of Object.keys(BUILT_IN)) add(name, BUILT_IN[name]);
143
+ for (const name of Object.keys(custom)) add(name, custom[name]);
144
+ };
145
+
146
+ module.exports = { FORMATS, register };
@@ -9,9 +9,10 @@
9
9
  // The document is untrusted input: a pointer reads own keys only, a `$ref` is
10
10
  // converted once per pointer, and the nesting is bounded.
11
11
  const { isFirstUpper } = require('../metautil.js');
12
- const { define } = require('../util.js');
12
+ const { define, shorten } = require('../util.js');
13
13
  const { Schema } = require('../schema.js');
14
- const { TYPES } = require('../types.js');
14
+ const { readsAsStruct } = require('../types.js');
15
+ const { FORMATS } = require('../rules.js');
15
16
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
16
17
 
17
18
  const invalidOptions = (reason) => new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
@@ -99,11 +100,12 @@ const createContext = (document, options) => {
99
100
  };
100
101
  };
101
102
 
102
- // The place in the document as a JSON pointer (RFC 6901).
103
+ // The place in the document as a JSON pointer (RFC 6901); a key of the
104
+ // document may be huge, a message must not be.
103
105
  const pointerOf = (path) => {
104
106
  let pointer = '';
105
107
  for (const segment of path) {
106
- pointer += `/${String(segment).replace(/~/g, '~0').replace(/\//g, '~1')}`;
108
+ pointer += `/${shorten(segment).replace(/~/g, '~0').replace(/\//g, '~1')}`;
107
109
  }
108
110
  return pointer;
109
111
  };
@@ -134,15 +136,6 @@ const compilesWithU = (pattern) => {
134
136
  }
135
137
  };
136
138
 
137
- // A struct key that the first-key rule reads as something else needs the
138
- // `schema` shorthand around the struct.
139
- const safeFirstKey = (fields) => {
140
- const first = Object.keys(fields)[0];
141
- if (first === undefined) return true;
142
- const key = first.endsWith('?') ? first.slice(0, -1) : first;
143
- return key !== 'type' && TYPES[key] === undefined && !isFirstUpper(key);
144
- };
145
-
146
139
  // A definition of a type with no other key is its name.
147
140
  const compact = (def, required) => {
148
141
  const keys = Object.keys(def);
@@ -263,6 +256,10 @@ const typed = (context, node, type, used) => {
263
256
  unsupported(context, `The pattern ${shown} (not a valid pattern under the u flag)`);
264
257
  }
265
258
  }
259
+ // A format the formats subpath registered is the rule; any other stays
260
+ // the annotation JSON Schema says it is.
261
+ const format = take('format');
262
+ if (typeof format === 'string' && FORMATS[format] !== undefined) def.format = format;
266
263
  return def;
267
264
  }
268
265
  if (type === 'number' || type === 'integer') {
@@ -490,7 +487,7 @@ const compactDef = (def, required) => {
490
487
  if (def.nullable === true && !required) delete def.nullable;
491
488
  if (def.type === 'schema' && Object.keys(def).length === 2) {
492
489
  const { schema } = def;
493
- if (safeFirstKey(schema)) return required ? schema : { schema, required: false };
490
+ if (readsAsStruct(schema)) return required ? schema : { schema, required: false };
494
491
  return required ? { schema } : { schema, required: false };
495
492
  }
496
493
  return compact(def, required);
@@ -60,7 +60,8 @@ const modelMethods = {
60
60
  };
61
61
 
62
62
  // Installed like class members: not enumerable, so a loop over a schema
63
- // never sees them.
63
+ // never sees them. A copy per subpath rather than a helper of the core: the
64
+ // core is measured on its own, the subpaths on top of it.
64
65
  const install = (prototype, members) => {
65
66
  const descriptors = Object.getOwnPropertyDescriptors(members);
66
67
  for (const name in descriptors) {
@@ -332,6 +332,8 @@ const RENDER = Object.assign(Object.create(null), {
332
332
  if (context.strict) return json;
333
333
  bounds(json, field.length, 'minLength', 'maxLength');
334
334
  if (field.pattern !== undefined) json.pattern = field.pattern.source;
335
+ // The names are those of JSON Schema; a $jsonSchema has no `format`.
336
+ if (field.format !== undefined && !context.mongo) json.format = field.format;
335
337
  return json;
336
338
  },
337
339
  number: (field, context) => ranged(typed('number', context), field, context),
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 every validator after it is kept too, with what it needs
194
- // to be called, so that the rule "a validator runs only when nothing before
195
- // it failed" holds over the promises as well; `settle` runs the list after
196
- // the walk, in field order. In a synchronous check a promise is an error of
197
- // the call.
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
- const recorded = list[index].path;
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
- // Runs the validators an async check kept, one after the other in the order
241
- // they were met, each recording under the path it was met at; the error
242
- // limit stops the list as it stops the walk.
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
- for (; index < pending.length; index += 1) {
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/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 < keys.length; index += 1) text += `, ${shorten(keys[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 < keys.length; index += 1) text += `, ${shorten(keys[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`.
@@ -101,10 +102,10 @@ class SchemaMetadata {
101
102
  if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
102
103
  return result.add(output);
103
104
  } catch (error) {
104
- if (error.code === 'ERR_ASYNC_VALIDATOR') throw error;
105
+ if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
105
106
  return result.add({
106
107
  code: 'exception',
107
- message: `validation failed ${error}`,
108
+ message: `validation failed ${safeString(error)}`,
108
109
  params: { error },
109
110
  });
110
111
  }
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;