@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +307 -1
  2. package/README.md +173 -89
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +601 -29
  5. package/package.json +28 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +201 -46
  8. package/src/coerce/index.d.ts +34 -0
  9. package/src/coerce/index.js +385 -0
  10. package/src/compile/emit.js +87 -28
  11. package/src/compile/index.js +9 -4
  12. package/src/context.js +6 -1
  13. package/src/definition/index.d.ts +19 -0
  14. package/src/definition/index.js +27 -0
  15. package/src/derive/index.d.ts +86 -0
  16. package/src/derive/index.js +273 -0
  17. package/src/errors.js +46 -4
  18. package/src/formats/index.d.ts +20 -8
  19. package/src/formats/index.js +450 -39
  20. package/src/generators/fromjsonschema.js +21 -2
  21. package/src/generators/index.js +1 -1
  22. package/src/generators/jsonschema.js +90 -21
  23. package/src/generators/typescript.js +11 -0
  24. package/src/index.js +3 -2
  25. package/src/issues.js +9 -7
  26. package/src/kinds.js +15 -3
  27. package/src/lint.js +38 -0
  28. package/src/locales/en.js +6 -0
  29. package/src/locales/uk.js +6 -0
  30. package/src/metadata.js +6 -24
  31. package/src/model/data.js +67 -10
  32. package/src/model/diff.js +7 -4
  33. package/src/model/index.js +1 -1
  34. package/src/model/infer.js +10 -3
  35. package/src/model/merge.js +16 -9
  36. package/src/model/restore.js +52 -7
  37. package/src/model/sample.js +28 -4
  38. package/src/model.js +54 -56
  39. package/src/mongodb/bson.js +130 -0
  40. package/src/mongodb/document.js +217 -0
  41. package/src/mongodb/index.d.ts +133 -0
  42. package/src/mongodb/index.js +24 -0
  43. package/src/mongodb/indexes.js +79 -0
  44. package/src/mongodb/update.js +258 -0
  45. package/src/preprocessor.js +1 -2
  46. package/src/prototypes/abstract.js +41 -67
  47. package/src/prototypes/collections.js +3 -90
  48. package/src/prototypes/flags.js +34 -0
  49. package/src/prototypes/json.js +0 -11
  50. package/src/prototypes/reference.js +0 -76
  51. package/src/prototypes/scalars.js +17 -96
  52. package/src/prototypes/schema.js +1 -10
  53. package/src/prototypes/tuple.js +0 -26
  54. package/src/prototypes/union.js +12 -82
  55. package/src/rules.js +33 -157
  56. package/src/schema.js +105 -220
  57. package/src/snapshot.js +216 -41
  58. package/src/stream/index.js +1 -1
  59. package/src/struct.js +6 -91
  60. package/src/types.js +43 -6
  61. package/src/util.js +43 -0
  62. package/src/validation.js +313 -0
@@ -1,26 +1,57 @@
1
1
  // The `./formats` subpath: the formats a string field may name
2
2
  // (`{ type: 'string', format: 'email' }`). The core knows the rule and keeps
3
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
4
+ // formats below and with the program's own, so that a program that
5
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).
6
+ // function over a string, a few `examples` for `sample`, whether `infer` may
7
+ // read it out of data (a format ordinary words pass, like a hostname or a
8
+ // slug, says not to), and for some a `pattern` the JSON Schema export
9
+ // writes beside the name, a shape that never rejects what the test accepts.
9
10
  //
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).
11
+ // The expressions are copied, with the attribution the project gives for a
12
+ // helper it carries instead of a dependency, from:
13
+ // - ajv-formats 3.0.1 (MIT, Copyright (c) 2020 Evgeny Poberezkin): email,
14
+ // uuid, uri, hostname, ipv4 and ipv6 of its fast mode, duration,
15
+ // uri-template, json-pointer and relative-json-pointer of its full mode,
16
+ // uri-reference of its fast mode, the shape of base64 (`byte`);
17
+ // - zod 4.6 (MIT, Copyright (c) 2025 Colin McDonnell): ulid, nanoid, e164,
18
+ // hex, emoji, the cidr prefixes, the shapes of a card number and an IBAN,
19
+ // the reading of base64, base64url and a JWT (without `atob` on the
20
+ // payload, and an `alg` that is a string);
21
+ // - valibot 1.5 (MIT, Copyright (c) Fabian Hiller): cuid2, slug, hex-color
22
+ // and the MAC-48 forms;
23
+ // - semver.org (CC BY 3.0): the expression of a semantic version.
24
+ // They are anchored and linear, every repetition bounded or separated by a
25
+ // character its class excludes. A repeated group with an alternative in it
26
+ // (`(?:a|bc)*`) is linear in time but not in the stack of the engine, which
27
+ // overflows on a string of megabytes: the forms that had one (an email's
28
+ // domain, a JSON pointer, a URI template, a slug, a semantic version) are
29
+ // read by a scanner over the string instead, with the same verdicts, and
30
+ // the expression stays as the `pattern` of the export where there is one.
31
+ // The date and time forms are RFC 3339 with the ranges checked (a 31st of
32
+ // February is not a date), and `url` is an http or https address whose host
33
+ // is a hostname or an address.
16
34
  const { FORMATS } = require('../rules.js');
17
35
  const { SchemaDefinitionError } = require('../errors.js');
18
36
 
19
37
  const invalidFormat = (name, reason) =>
20
38
  new SchemaDefinitionError('ERR_INVALID_FORMAT', `Format "${name}" ${reason}`);
21
39
 
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;
40
+ // ajv-formats' fast email: a local part of its characters, an `@`, and
41
+ // labels of at most 63 characters joined by dots.
42
+ const LOCAL = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i;
43
+
44
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
45
+
46
+ const isEmail = (text) => {
47
+ const at = text.indexOf('@');
48
+ if (at < 1 || !LOCAL.test(text.slice(0, at))) return false;
49
+ const labels = text.slice(at + 1).split('.');
50
+ for (let index = 0; index < labels.length; index += 1) {
51
+ if (!LABEL.test(labels[index])) return false;
52
+ }
53
+ return true;
54
+ };
24
55
 
25
56
  const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
26
57
 
@@ -49,59 +80,413 @@ const isDate = (text) => {
49
80
  return Number(match[3]) <= DAYS[month] + (leap ? 1 : 0);
50
81
  };
51
82
 
83
+ // A partial-time with or without its offset: `time` needs one, as the RFC
84
+ // says, `iso-time` does not (ajv-formats' names); a leap second is allowed.
52
85
  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))?)$/;
86
+ /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d|60)(?:\.\d+)?(?:([zZ])|([+-])([01]\d|2[0-3])(?::?([0-5]\d))?)?$/;
54
87
 
55
88
  // A leap second is the one of 23:59:60 UTC, whatever the offset says.
56
- const isTime = (text) => {
89
+ const timeOf = (zoned) => (text) => {
57
90
  const match = TIME.exec(text);
58
91
  if (match === null) return false;
92
+ if (zoned && match[4] === undefined && match[5] === undefined) return false;
59
93
  if (match[3] !== '60') return true;
60
- const sign = match[4] === '-' ? -1 : 1;
94
+ const sign = match[5] === '-' ? -1 : 1;
61
95
  const offset =
62
- match[4] === undefined ? 0 : sign * (Number(match[5]) * 60 + Number(match[6] ?? 0));
96
+ match[5] === undefined ? 0 : sign * (Number(match[6]) * 60 + Number(match[7] ?? 0));
63
97
  const minutes = (Number(match[1]) * 60 + Number(match[2]) - offset + 1440) % 1440;
64
98
  return minutes === 23 * 60 + 59;
65
99
  };
66
100
 
101
+ const isTime = timeOf(true);
102
+
103
+ const isIsoTime = timeOf(false);
104
+
67
105
  // A date-time is the two joined by `T` (or, as the RFC allows for
68
106
  // readability, a space).
69
- const isDateTime = (text) =>
107
+ const dateTimeOf = (time) => (text) =>
70
108
  text.length > 11 &&
71
109
  (text[10] === 'T' || text[10] === 't' || text[10] === ' ') &&
72
110
  isDate(text.slice(0, 10)) &&
73
- isTime(text.slice(11));
111
+ time(text.slice(11));
112
+
113
+ const DURATION = /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/;
114
+
115
+ const URI_REFERENCE = /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i;
116
+
117
+ // Every character from `from` to `to` is one `allowed` accepts or a
118
+ // percent-encoded byte.
119
+ const HEX2 = /^[0-9a-f]{2}$/i;
120
+
121
+ const encoded = (text, from, to, allowed) => {
122
+ let index = from;
123
+ while (index < to) {
124
+ if (text[index] === '%') {
125
+ if (index + 3 > to || !HEX2.test(text.slice(index + 1, index + 3))) return false;
126
+ index += 3;
127
+ } else {
128
+ if (!allowed.test(text[index])) return false;
129
+ index += 1;
130
+ }
131
+ }
132
+ return true;
133
+ };
134
+
135
+ // A URI template of RFC 6570 as ajv-formats reads it: literals outside the
136
+ // braces, and in each pair of braces an optional operator and a list of
137
+ // variable names, each with an optional prefix (`:1` to `:9999`) or `*`.
138
+ // oxlint-disable-next-line no-control-regex
139
+ const LITERAL = /[^\x00-\x20"'<>%\\^`{|}]/;
140
+
141
+ const VARCHAR = /[a-z0-9_]/i;
142
+
143
+ const OPERATOR = /[+#./;?&=,!@|]/;
144
+
145
+ const MODIFIER = /^:[1-9][0-9]{0,3}$/;
146
+
147
+ const isVariable = (spec) => {
148
+ let name = spec;
149
+ if (spec.endsWith('*')) name = spec.slice(0, -1);
150
+ else {
151
+ const colon = spec.indexOf(':');
152
+ if (colon !== -1) {
153
+ if (!MODIFIER.test(spec.slice(colon))) return false;
154
+ name = spec.slice(0, colon);
155
+ }
156
+ }
157
+ return name !== '' && encoded(name, 0, name.length, VARCHAR);
158
+ };
159
+
160
+ const isExpression = (expression) => {
161
+ const body = OPERATOR.test(expression[0] ?? '') ? expression.slice(1) : expression;
162
+ if (body === '') return false;
163
+ const specs = body.split(',');
164
+ for (let index = 0; index < specs.length; index += 1) {
165
+ if (!isVariable(specs[index])) return false;
166
+ }
167
+ return true;
168
+ };
169
+
170
+ const isTemplate = (text) => {
171
+ let index = 0;
172
+ for (;;) {
173
+ const open = text.indexOf('{', index);
174
+ if (!encoded(text, index, open === -1 ? text.length : open, LITERAL)) return false;
175
+ if (open === -1) return true;
176
+ const close = text.indexOf('}', open + 1);
177
+ if (close === -1 || !isExpression(text.slice(open + 1, close))) return false;
178
+ index = close + 1;
179
+ }
180
+ };
181
+
182
+ // A JSON pointer of RFC 6901: empty, or segments led by `/` in which a `~`
183
+ // escapes a `0` or a `1` and nothing else.
184
+ const isPointer = (text) => {
185
+ if (text === '') return true;
186
+ if (text[0] !== '/') return false;
187
+ for (let at = text.indexOf('~'); at !== -1; at = text.indexOf('~', at + 2)) {
188
+ const next = text[at + 1];
189
+ if (next !== '0' && next !== '1') return false;
190
+ }
191
+ return true;
192
+ };
193
+
194
+ const RELATIVE = /^(?:0|[1-9][0-9]*)/;
195
+
196
+ const isRelativePointer = (text) => {
197
+ const match = RELATIVE.exec(text);
198
+ if (match === null) return false;
199
+ const rest = text.slice(match[0].length);
200
+ return rest === '#' || isPointer(rest);
201
+ };
202
+
203
+ // A pattern of JSON Schema 2020-12 is an ECMA-262 expression in unicode
204
+ // mode. Compiling one costs memory in proportion to its text (a property
205
+ // escape expands as it is parsed), so a text longer than any pattern a
206
+ // program writes is not one; `length.max` on the field bounds it further.
207
+ const REGEX_MAX = 4096;
208
+
209
+ const isRegex = (text) => {
210
+ if (text.length > REGEX_MAX) return false;
211
+ try {
212
+ return RegExp(text, 'u') instanceof RegExp;
213
+ } catch {
214
+ return false;
215
+ }
216
+ };
217
+
218
+ const ULID = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
219
+
220
+ const NANOID = /^[\w-]{21}$/;
221
+
222
+ const CUID2 = /^[a-z][0-9a-z]{1,31}$/;
223
+
224
+ const E164 = /^\+[1-9]\d{6,14}$/;
225
+
226
+ const HEX = /^[0-9a-fA-F]*$/;
227
+
228
+ const HEX_COLOR = /^#(?:[\da-fA-F]{3,4}|[\da-fA-F]{6}|[\da-fA-F]{8})$/;
229
+
230
+ // Words of digits and lowercase letters joined by single dashes or
231
+ // underscores (valibot's slug); the expression is the pattern of the export.
232
+ const SLUG = /^[\da-z]+(?:[-_][\da-z]+)*$/;
233
+
234
+ const SLUG_CHARS = /^[\da-z](?:[\da-z_-]*[\da-z])?$/;
235
+
236
+ const SEPARATORS = /[-_]{2}/;
237
+
238
+ const isSlug = (text) => SLUG_CHARS.test(text) && !SEPARATORS.test(text);
239
+
240
+ const MAC =
241
+ /^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$|^(?:[\da-fA-F]{2}-){5}[\da-fA-F]{2}$|^(?:[\da-fA-F]{4}\.){2}[\da-fA-F]{4}$/;
242
+
243
+ // semver.org's expression, the pattern of the export; the test reads the
244
+ // three parts (the core, the pre-release after the first `-`, the build
245
+ // after the `+`) and their dot-separated identifiers one by one.
246
+ const SEMVER =
247
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/;
248
+
249
+ const CORE = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/;
250
+
251
+ const PRERELEASE = /^(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)$/;
252
+
253
+ const BUILD = /^[\dA-Za-z-]+$/;
254
+
255
+ const identifiers = (text, form) => {
256
+ const parts = text.split('.');
257
+ for (let index = 0; index < parts.length; index += 1) {
258
+ if (!form.test(parts[index])) return false;
259
+ }
260
+ return true;
261
+ };
262
+
263
+ const isSemver = (text) => {
264
+ const plus = text.indexOf('+');
265
+ const version = plus === -1 ? text : text.slice(0, plus);
266
+ if (plus !== -1 && !identifiers(text.slice(plus + 1), BUILD)) return false;
267
+ const dash = version.indexOf('-');
268
+ if (dash === -1) return CORE.test(version);
269
+ return CORE.test(version.slice(0, dash)) && identifiers(version.slice(dash + 1), PRERELEASE);
270
+ };
271
+
272
+ const EMOJI =
273
+ /^(?=[\s\S]*[\p{Extended_Pictographic}\p{Regional_Indicator}\u20E3])[\p{Extended_Pictographic}\p{Emoji_Component}]+$/u;
274
+
275
+ // A charset and a length instead of the quantified forms, which overflow the
276
+ // stack of the engine on a string of megabytes.
277
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
278
+
279
+ const BYTE = '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$';
280
+
281
+ const isBase64 = (text) => text.length % 4 === 0 && BASE64.test(text);
282
+
283
+ const BASE64URL = /^[\w-]*$/;
284
+
285
+ const isBase64url = (text) => text.length % 4 !== 1 && BASE64URL.test(text);
286
+
287
+ // A JWT is three parts of base64url, the first a JSON object that names its
288
+ // algorithm; the signature is not verified, and the payload not read.
289
+ const JWT = /^([\w-]+)\.[\w-]*\.[\w-]*$/;
290
+
291
+ const isJwt = (text) => {
292
+ const match = JWT.exec(text);
293
+ if (match === null || match[1].length % 4 === 1) return false;
294
+ try {
295
+ const header = JSON.parse(atob(match[1].replaceAll('-', '+').replaceAll('_', '/')));
296
+ return header !== null && typeof header === 'object' && typeof header.alg === 'string';
297
+ } catch {
298
+ return false;
299
+ }
300
+ };
301
+
302
+ const PREFIX4 = /^(?:3[0-2]|[12]?\d)$/;
303
+
304
+ const PREFIX6 = /^(?:12[0-8]|1[01]\d|[1-9]?\d)$/;
305
+
306
+ const cidrOf = (address, prefix) => (text) => {
307
+ const at = text.indexOf('/');
308
+ return at > 0 && prefix.test(text.slice(at + 1)) && address.test(text.slice(0, at));
309
+ };
310
+
311
+ // An http or https address, stricter than what a browser reads: the host is
312
+ // a hostname, an IPv4 address (a host that ends in a number is one) or an
313
+ // IPv6 address in brackets, and the port fits in 16 bits.
314
+ const URL_FORM =
315
+ /^https?:\/\/(?:[^\s/?#@]*@)?(\[[^\s/?#\]]*\]|[^\s/?#:@[\]]+)(?::(\d{1,5}))?(?:[/?#][^\s\\]*)?$/i;
316
+
317
+ const NUMERIC = /(?:^|\.)\d+\.?$/;
318
+
319
+ const isUrl = (text) => {
320
+ const match = URL_FORM.exec(text);
321
+ if (match === null || Number(match[2] ?? 0) > 65535) return false;
322
+ const host = match[1];
323
+ if (host[0] === '[') return IPV6.test(host.slice(1, -1));
324
+ return NUMERIC.test(host) ? IPV4.test(host) : HOSTNAME.test(host);
325
+ };
326
+
327
+ // A card number of 12 to 19 digits (spaces or dashes between them) whose
328
+ // Luhn sum holds; a valid sum is not a card that exists.
329
+ const CARD = /^\d(?:[ -]?\d){11,18}$/;
330
+
331
+ const isCard = (text) => {
332
+ if (!CARD.test(text)) return false;
333
+ let sum = 0;
334
+ let double = false;
335
+ for (let index = text.length - 1; index >= 0; index -= 1) {
336
+ let digit = text.charCodeAt(index) - 48;
337
+ if (digit < 0 || digit > 9) continue;
338
+ if (double) digit = digit > 4 ? digit * 2 - 9 : digit * 2;
339
+ sum += digit;
340
+ double = !double;
341
+ }
342
+ return sum % 10 === 0;
343
+ };
344
+
345
+ // An IBAN whose check digits hold (ISO 7064 mod 97-10, the letters read as
346
+ // 10 to 35, the remainder kept small instead of a bigint).
347
+ const IBAN = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z\d]{11,30}$/;
348
+
349
+ const isIban = (text) => {
350
+ if (!IBAN.test(text)) return false;
351
+ const moved = text.slice(4) + text.slice(0, 4);
352
+ let rest = 0;
353
+ for (let index = 0; index < moved.length; index += 1) {
354
+ const code = moved.charCodeAt(index);
355
+ rest = code >= 65 ? (rest * 100 + code - 55) % 97 : (rest * 10 + code - 48) % 97;
356
+ }
357
+ return rest === 1;
358
+ };
74
359
 
75
360
  const tested = (expression) => (text) => expression.test(text);
76
361
 
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.
362
+ // In the order `infer` tries them: the specific forms first (a uuid, a
363
+ // date, an address are also hostnames), a date-time with its zone before
364
+ // one without, an http address before any URI; the forms ordinary words or
365
+ // numbers pass (a hostname, a slug, a JSON pointer, `1.2.3` as a version, a
366
+ // Luhn sum one number in ten passes) are never inferred.
80
367
  const BUILT_IN = {
81
368
  uuid: {
82
369
  test: tested(UUID),
83
370
  examples: ['550e8400-e29b-41d4-a716-446655440000', '123e4567-e89b-12d3-a456-426614174000'],
84
371
  },
85
- email: { test: tested(EMAIL), examples: ['ann@example.com', 'ann.lee@mail.example.org'] },
372
+ ulid: {
373
+ test: tested(ULID),
374
+ examples: ['01ARZ3NDEKTSV4RRFFQ69G5FAV', '01HZX8Q4N0J5W6Y2T9K3M7P1RB'],
375
+ pattern: ULID.source,
376
+ },
377
+ jwt: {
378
+ test: isJwt,
379
+ examples: [
380
+ 'eyJhbGciOiJub25lIn0.e30.',
381
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl',
382
+ ],
383
+ pattern: '^[\\w-]+\\.[\\w-]*\\.[\\w-]*$',
384
+ },
385
+ email: { test: isEmail, examples: ['ann@example.com', 'ann.lee@mail.example.org'] },
86
386
  'date-time': {
87
- test: isDateTime,
387
+ test: dateTimeOf(isTime),
88
388
  examples: ['2026-10-11T12:00:00Z', '2026-10-11T12:00:00.000+02:00'],
89
389
  },
390
+ 'iso-date-time': {
391
+ test: dateTimeOf(isIsoTime),
392
+ examples: ['2026-10-11T12:00:00', '2026-10-11 12:00:00.5'],
393
+ },
90
394
  date: { test: isDate, examples: ['2026-10-11', '2000-02-29'] },
91
395
  time: { test: isTime, examples: ['12:00:00Z', '23:59:59.999+02:00'] },
396
+ 'iso-time': { test: isIsoTime, examples: ['12:00:00', '23:59:59.999+02:00'] },
397
+ duration: { test: tested(DURATION), examples: ['P1Y2M3DT4H5M6S', 'PT15M'] },
92
398
  ipv4: { test: tested(IPV4), examples: ['192.168.0.1', '10.0.0.255'] },
399
+ cidrv4: { test: cidrOf(IPV4, PREFIX4), examples: ['192.168.0.0/24', '10.0.0.0/8'] },
93
400
  ipv6: { test: tested(IPV6), examples: ['::1', '2001:db8::ff00:42:8329'] },
401
+ cidrv6: { test: cidrOf(IPV6, PREFIX6), examples: ['2001:db8::/32', 'fe80::/10'] },
402
+ mac: {
403
+ test: tested(MAC),
404
+ examples: ['00:1a:2b:3c:4d:5e', '00-1A-2B-3C-4D-5E'],
405
+ pattern: MAC.source,
406
+ },
407
+ e164: { test: tested(E164), examples: ['+380501234567', '+14155552671'], pattern: E164.source },
408
+ iban: {
409
+ test: isIban,
410
+ examples: ['DE89370400440532013000', 'GB82WEST12345698765432'],
411
+ pattern: IBAN.source,
412
+ },
413
+ 'hex-color': {
414
+ test: tested(HEX_COLOR),
415
+ examples: ['#7c5cff', '#fff'],
416
+ pattern: HEX_COLOR.source,
417
+ },
418
+ url: { test: isUrl, examples: ['https://example.com/path?q=1', 'http://localhost:3000/'] },
94
419
  uri: { test: tested(URI), examples: ['https://example.com/path?q=1', 'mailto:ann@example.com'] },
95
420
  hostname: { test: tested(HOSTNAME), examples: ['example.com', 'api.example.org'], infer: false },
421
+ 'uri-reference': {
422
+ test: tested(URI_REFERENCE),
423
+ examples: ['/users/42?tab=info', '../up#top'],
424
+ infer: false,
425
+ },
426
+ 'uri-template': {
427
+ test: isTemplate,
428
+ examples: ['https://example.com/users/{id}', '/search{?q,page}'],
429
+ infer: false,
430
+ },
431
+ 'json-pointer': {
432
+ test: isPointer,
433
+ examples: ['/users/0/name', '/a~1b'],
434
+ infer: false,
435
+ },
436
+ 'relative-json-pointer': {
437
+ test: isRelativePointer,
438
+ examples: ['1/name', '0#'],
439
+ infer: false,
440
+ },
441
+ regex: { test: isRegex, examples: ['^[a-z]+$', '\\d{3}-\\d{4}'], infer: false },
442
+ nanoid: {
443
+ test: tested(NANOID),
444
+ examples: ['V1StGXR8_Z5jdHi6B-myT', 'a3Fk9_LmQz-7xYpR2tWn0'],
445
+ infer: false,
446
+ pattern: NANOID.source,
447
+ },
448
+ cuid2: {
449
+ test: tested(CUID2),
450
+ examples: ['tz4a98xxat96iws9zmbrgj3a', 'pfh0haxfpzowht3oi213cqos'],
451
+ infer: false,
452
+ pattern: CUID2.source,
453
+ },
454
+ base64: { test: isBase64, examples: ['aGVsbG8=', 'TWFu'], infer: false, pattern: BYTE },
455
+ base64url: {
456
+ test: isBase64url,
457
+ examples: ['aGVsbG8', 'PDw_Pz8-'],
458
+ infer: false,
459
+ pattern: '^(?:[\\w-]{4})*(?:[\\w-]{2,3})?$',
460
+ },
461
+ hex: { test: tested(HEX), examples: ['deadbeef', '0A1B2C'], infer: false, pattern: HEX.source },
462
+ emoji: { test: tested(EMOJI), examples: ['👍', '🇺🇦'], infer: false },
463
+ semver: {
464
+ test: isSemver,
465
+ examples: ['1.0.0', '2.1.3-beta.1+build.5'],
466
+ infer: false,
467
+ pattern: SEMVER.source,
468
+ },
469
+ slug: {
470
+ test: isSlug,
471
+ examples: ['hello-world', 'metaschema-3-3'],
472
+ infer: false,
473
+ pattern: SLUG.source,
474
+ },
475
+ 'credit-card': {
476
+ test: isCard,
477
+ examples: ['4111111111111111', '5555 5555 5555 4444'],
478
+ infer: false,
479
+ pattern: CARD.source,
480
+ },
96
481
  };
97
482
 
98
- // An entry as the table keeps it: the test, a copy of the examples, and
99
- // whether infer may read it, frozen.
483
+ // An entry as the table keeps it: the test, a copy of the examples, whether
484
+ // infer may read it and the pattern of the export, frozen.
100
485
  const entryOf = (name, entry) => {
101
486
  if (entry === null || typeof entry !== 'object') {
102
487
  throw invalidFormat(name, 'needs { test, examples }');
103
488
  }
104
- const { test, examples, infer } = entry;
489
+ const { test, examples, infer, pattern } = entry;
105
490
  if (typeof test !== 'function') throw invalidFormat(name, 'needs a test function');
106
491
  const listed = Array.isArray(examples) && examples.length > 0;
107
492
  if (!listed) throw invalidFormat(name, 'needs a list of example strings');
@@ -113,34 +498,60 @@ const entryOf = (name, entry) => {
113
498
  if (infer !== undefined && typeof infer !== 'boolean') {
114
499
  throw invalidFormat(name, 'needs a boolean infer');
115
500
  }
116
- return Object.freeze({ test, examples: Object.freeze(examples.slice()), infer: infer !== false });
501
+ if (pattern !== undefined && (typeof pattern !== 'string' || !isRegex(pattern))) {
502
+ throw invalidFormat(name, 'needs a pattern string that compiles under the u flag');
503
+ }
504
+ const copy = { test, examples: Object.freeze(examples.slice()), infer: infer !== false };
505
+ if (pattern !== undefined) copy.pattern = pattern;
506
+ return Object.freeze(copy);
117
507
  };
118
508
 
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) => {
509
+ const registered = (name) =>
510
+ new SchemaDefinitionError(
511
+ 'ERR_FORMAT_REGISTERED',
512
+ `Format "${name}" is already registered with another test`,
513
+ );
514
+
515
+ // A name is registered once: the same test again is nothing, and another
516
+ // test under a registered name is an error, since the schemas built so far
517
+ // hold the first one. The one exception is the program's own format under
518
+ // the name of a built-in: it takes the built-in's place (and its position in
519
+ // the order infer reads them), so that a format a program registered before
520
+ // the name was built in keeps working; the schemas built before it keep the
521
+ // built-in test.
522
+ const add = (name, entry, own) => {
123
523
  if (name === '') throw invalidFormat(name, 'needs a name');
124
524
  const known = FORMATS[name];
525
+ let replaced = false;
125
526
  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
- );
527
+ if (known.test === entry.test) return false;
528
+ if (!own) return false;
529
+ replaced = Object.hasOwn(BUILT_IN, name) && known.test === BUILT_IN[name].test;
530
+ if (!replaced) throw registered(name);
131
531
  }
132
532
  FORMATS[name] = entryOf(name, entry);
533
+ return replaced;
133
534
  };
134
535
 
135
536
  // Registers the built-in formats and the program's own
136
537
  // (`{ phone: { test, examples } }`); once per name, process-wide, like the
137
- // type registry. Importing the subpath registers nothing.
538
+ // type registry. Importing the subpath registers nothing. Returns the names
539
+ // of the built-in formats the call replaced with the program's own (the
540
+ // schemas built before keep the built-in test), so that a program can log
541
+ // what it overrode; an empty list otherwise.
138
542
  const register = (custom = {}) => {
139
543
  if (custom === null || typeof custom !== 'object') {
140
544
  throw new SchemaDefinitionError('ERR_INVALID_FORMAT', 'Formats must be an object of entries');
141
545
  }
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]);
546
+ const replaced = [];
547
+ for (const name of Object.keys(BUILT_IN)) {
548
+ const own = Object.hasOwn(custom, name);
549
+ if (add(name, own ? custom[name] : BUILT_IN[name], own)) replaced.push(name);
550
+ }
551
+ for (const name of Object.keys(custom)) {
552
+ if (!Object.hasOwn(BUILT_IN, name)) add(name, custom[name], true);
553
+ }
554
+ return replaced;
144
555
  };
145
556
 
146
557
  module.exports = { FORMATS, register };
@@ -55,6 +55,10 @@ const KNOWN = new Set([
55
55
  'json',
56
56
  ]);
57
57
 
58
+ // The steps `multipleOf` writes for a number of 0 to 15 decimals, by count.
59
+ const DECIMALS = [];
60
+ for (let count = 0; count <= 15; count += 1) DECIMALS.push(10 ** -count);
61
+
58
62
  // How deep a document may nest: past it the conversion stops whatever the
59
63
  // mode, since a lenient conversion must not recurse without end either.
60
64
  const MAX_DEPTH = 128;
@@ -257,9 +261,19 @@ const typed = (context, node, type, used) => {
257
261
  }
258
262
  }
259
263
  // A format the formats subpath registered is the rule; any other stays
260
- // the annotation JSON Schema says it is.
264
+ // the annotation JSON Schema says it is. OpenAPI's `byte` is base64, and
265
+ // the shape the export writes beside a format is the format's own.
261
266
  const format = take('format');
262
- if (typeof format === 'string' && FORMATS[format] !== undefined) def.format = format;
267
+ const name = format === 'byte' && FORMATS.byte === undefined ? 'base64' : format;
268
+ if (typeof name === 'string' && FORMATS[name] !== undefined) {
269
+ def.format = name;
270
+ if (def.pattern === FORMATS[name].pattern) delete def.pattern;
271
+ }
272
+ // Base64 text (what `bytes` exports as) is the base64 format when the
273
+ // formats are registered, as OpenAPI's `byte` is.
274
+ if (def.format === undefined && node.contentEncoding === 'base64' && FORMATS.base64) {
275
+ def.format = 'base64';
276
+ }
263
277
  return def;
264
278
  }
265
279
  if (type === 'number' || type === 'integer') {
@@ -267,6 +281,11 @@ const typed = (context, node, type, used) => {
267
281
  const max = take('maximum');
268
282
  if (min !== undefined) def.min = min;
269
283
  if (max !== undefined) def.max = max;
284
+ // A multiple of 10⁻ⁿ is a number of n decimals and 1 says nothing more
285
+ // of an integer; any other step is a keyword outside the subset.
286
+ const decimals = DECIMALS.indexOf(node.multipleOf);
287
+ if (type === 'integer' ? node.multipleOf === 1 : decimals !== -1) take('multipleOf');
288
+ if (type === 'number' && decimals !== -1) def.decimals = decimals;
270
289
  return def;
271
290
  }
272
291
  if (type === 'array') {
@@ -6,7 +6,7 @@
6
6
  // programs that want the methods.
7
7
  const { hasBrand } = require('../util.js');
8
8
  const { invalidTarget } = require('../errors.js');
9
- const { Schema } = require('../schema.js');
9
+ const { Schema } = require('../validation.js');
10
10
  const { Model } = require('../model.js');
11
11
  const { writeFile } = require('../runtime/node.js');
12
12
  const generators = require('./jsonschema.js');