@alexify/metaschema 3.4.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +227 -1
  2. package/README.md +29 -11
  3. package/SECURITY.md +5 -4
  4. package/index.d.ts +912 -480
  5. package/package.json +8 -6
  6. package/src/checks.js +72 -107
  7. package/src/codec.js +67 -58
  8. package/src/coerce/index.d.ts +31 -21
  9. package/src/coerce/index.js +64 -47
  10. package/src/compile/code.js +2 -2
  11. package/src/compile/emit.js +20 -31
  12. package/src/compile/index.d.ts +41 -25
  13. package/src/compile/index.js +45 -32
  14. package/src/context.js +10 -10
  15. package/src/definition/index.d.ts +10 -7
  16. package/src/definition/index.js +2 -1
  17. package/src/derive/index.d.ts +25 -17
  18. package/src/derive/index.js +21 -15
  19. package/src/errors.js +84 -59
  20. package/src/formats/index.d.ts +27 -21
  21. package/src/formats/index.js +15 -13
  22. package/src/generators/{fromjsonschema.js → from-json-schema.js} +170 -127
  23. package/src/generators/index.d.ts +23 -15
  24. package/src/generators/index.js +2 -2
  25. package/src/generators/{jsonschema.js → json-schema.js} +37 -43
  26. package/src/generators/typescript.js +9 -6
  27. package/src/index.js +2 -1
  28. package/src/issues.js +41 -42
  29. package/src/kinds.js +31 -10
  30. package/src/lint.js +64 -19
  31. package/src/locales/en.js +7 -7
  32. package/src/locales/uk.js +6 -6
  33. package/src/metadata.js +2 -2
  34. package/src/model/data.js +34 -20
  35. package/src/model/diff.js +29 -24
  36. package/src/model/index.d.ts +51 -35
  37. package/src/model/infer.js +70 -61
  38. package/src/model/merge.js +29 -18
  39. package/src/model/pattern.js +105 -102
  40. package/src/model/restore.js +33 -21
  41. package/src/model/sample.js +90 -100
  42. package/src/model.js +4 -2
  43. package/src/mongodb/bson.js +12 -12
  44. package/src/mongodb/document.js +7 -6
  45. package/src/mongodb/index.d.ts +54 -31
  46. package/src/mongodb/update.js +12 -9
  47. package/src/preprocessor.js +25 -15
  48. package/src/prototypes/abstract.js +8 -8
  49. package/src/prototypes/collections.js +7 -7
  50. package/src/prototypes/flags.js +1 -1
  51. package/src/prototypes/reference.js +3 -4
  52. package/src/prototypes/scalars.js +1 -1
  53. package/src/prototypes/schema.js +5 -6
  54. package/src/prototypes/tuple.js +11 -10
  55. package/src/prototypes/union.js +5 -4
  56. package/src/rules.js +23 -20
  57. package/src/runtime/browser.js +6 -1
  58. package/src/runtime/node.js +19 -2
  59. package/src/schema.js +19 -14
  60. package/src/snapshot.js +14 -12
  61. package/src/stream/index.d.ts +33 -21
  62. package/src/stream/index.js +37 -20
  63. package/src/struct.js +6 -6
  64. package/src/types.js +35 -26
  65. package/src/util.js +70 -64
  66. package/src/validation.js +10 -13
@@ -10,16 +10,12 @@
10
10
  // what no type describes is `any` rather than an error.
11
11
  const { define, IDENTIFIER, shorten, isBytes } = require('../util.js');
12
12
  const { Schema } = require('../validation.js');
13
- const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
13
+ const { SchemaDefinitionError, SchemaUsageError, invalidTarget } = require('../errors.js');
14
14
  const { readsAsStruct } = require('../types.js');
15
15
  const { FORMATS } = require('../rules.js');
16
16
  const { toDotPath, finalize } = require('../issues.js');
17
17
  const en = require('../locales/en.js');
18
- const { DEPTH, capitalize } = require('./data.js');
19
-
20
- const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
21
-
22
- const invalidOptions = (reason) => invalid('ERR_INVALID_OPTIONS', reason);
18
+ const { MAX_DEPTH, kindKeyOf } = require('./data.js');
23
19
 
24
20
  // The kinds a place may hold, a bit each: a place that held values of
25
21
  // several kinds is a union of them, and null and undefined decide presence.
@@ -43,12 +39,25 @@ const BYTES = 16384;
43
39
 
44
40
  const PRESENCE = NULL | UNDEF;
45
41
 
42
+ // The bit of the type of a key of a Map.
43
+ const KEY_BITS = { string: STRING, number: FLOAT };
44
+
46
45
  // How a key is written: a field, its presence (absent, undefined or null
47
46
  // among its values) written as the language writes it.
48
47
  const REQUIRED = 0;
49
48
  const OPTIONAL = 1;
50
49
  const NULLABLE = 2;
51
50
 
51
+ // A place in the samples, for the errors: the keys of records, `[]` for
52
+ // the elements of a list or the entries of a Map.
53
+ const ITEM = Symbol('item');
54
+
55
+ // A key a program would write as a field: a letter, a digit after it.
56
+ const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
57
+
58
+ // An option of the call that is not what it must be: the call is wrong.
59
+ const wrongOption = (reason) => new SchemaUsageError(reason, { code: 'ALX_ERR_INVALID_OPTION' });
60
+
52
61
  // The summary of one place: one shape for every node. `strings` is the
53
62
  // distinct strings while there are few enough for an enum (undefined before
54
63
  // the first, null once there are too many), `texts` how many strings there
@@ -68,10 +77,6 @@ const node = () => ({
68
77
  formats: undefined,
69
78
  });
70
79
 
71
- // A place in the samples, for the errors: the keys of records, `[]` for
72
- // the elements of a list or the entries of a Map.
73
- const ITEM = Symbol('item');
74
-
75
80
  const where = (state) => {
76
81
  let text = '';
77
82
  for (let index = 0; index < state.path.length; index += 1) {
@@ -83,11 +88,11 @@ const where = (state) => {
83
88
  return text;
84
89
  };
85
90
 
86
- const tooDeep = (state) =>
87
- invalid(
88
- 'ERR_INFER_DEPTH',
89
- `Sample ${state.index} nests deeper than ${state.maxDepth} levels at "${where(state)}" (a cycle?)`,
90
- );
91
+ const tooDeep = (state) => {
92
+ const levels = `${state.maxDepth} levels at "${where(state)}"`;
93
+ const message = `Sample ${state.index} nests deeper than ${levels} (a cycle?)`;
94
+ return new SchemaDefinitionError(message, { code: 'ALX_ERR_INFER_DEPTH' });
95
+ };
91
96
 
92
97
  // The formats of a place narrow with every string: the candidates are the
93
98
  // registered formats that infer (a format every word passes says not to),
@@ -148,8 +153,7 @@ const add = (target, value, state, depth) => {
148
153
  const type = typeof value;
149
154
  if (type === 'string') {
150
155
  target.bits |= STRING;
151
- addString(target, value, state);
152
- return;
156
+ return void addString(target, value, state);
153
157
  }
154
158
  if (type === 'number') {
155
159
  target.bits |= Number.isInteger(value) ? INTEGER : FLOAT;
@@ -179,8 +183,7 @@ const add = (target, value, state, depth) => {
179
183
  }
180
184
  if (Array.isArray(value)) {
181
185
  target.bits |= LIST;
182
- addItems(target, value, state, depth);
183
- return;
186
+ return void addItems(target, value, state, depth);
184
187
  }
185
188
  if (isBytes(value)) {
186
189
  target.bits |= BYTES;
@@ -189,8 +192,7 @@ const add = (target, value, state, depth) => {
189
192
  const iterable = typeof value[Symbol.iterator] === 'function';
190
193
  if (name === 'Set' && iterable) {
191
194
  target.bits |= SET;
192
- addItems(target, value, state, depth);
193
- return;
195
+ return void addItems(target, value, state, depth);
194
196
  }
195
197
  if (name === 'Map' && iterable) {
196
198
  target.bits |= MAP;
@@ -200,11 +202,10 @@ const add = (target, value, state, depth) => {
200
202
  state.path.push(ITEM);
201
203
  for (const pair of value) {
202
204
  const key = typeof pair[0];
203
- target.names.bits |= key === 'string' ? STRING : key === 'number' ? FLOAT : ANY;
205
+ target.names.bits |= KEY_BITS[key] ?? ANY;
204
206
  add(target.entries, pair[1], state, depth + 1);
205
207
  }
206
- state.path.pop();
207
- return;
208
+ return void state.path.pop();
208
209
  }
209
210
  target.bits |= RECORD;
210
211
  target.records += 1;
@@ -248,9 +249,6 @@ const fuse = (into, from, cap) => {
248
249
  return into;
249
250
  };
250
251
 
251
- // A key a program would write as a field: a letter, a digit after it.
252
- const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
253
-
254
252
  // Whether the records of a place are a dictionary rather than a struct: no
255
253
  // key is a name (ids, dates, codes as keys, from one sample on), or there
256
254
  // are more keys than `map` across several records, every key is missing
@@ -297,7 +295,10 @@ const written = (form, presence) => {
297
295
  };
298
296
 
299
297
  // A place that held nothing but null or undefined.
300
- const bareOf = (bits, absent) => (bits & NULL ? (absent ? '?null' : 'null') : '?unknown');
298
+ const bareOf = (bits, absent) => {
299
+ if ((bits & NULL) === 0) return '?unknown';
300
+ return absent ? '?null' : 'null';
301
+ };
301
302
 
302
303
  // The element of a list, the value of a dictionary: `?type` when null or
303
304
  // undefined was among them.
@@ -312,10 +313,12 @@ const itemOf = (target, state) => {
312
313
  // string of the place passed, else a string.
313
314
  const stringOf = (target, state) => {
314
315
  const { strings, texts, formats } = target;
315
- if (strings != null && texts >= 4 && texts >= 2 * strings.size) {
316
+ const counted = strings !== undefined && strings !== null;
317
+ if (counted && texts >= 4 && texts >= 2 * strings.size) {
316
318
  return { def: { enum: Array.from(strings) } };
317
319
  }
318
- if (formats != null && formats.length > 0) return { def: { type: 'string', format: formats[0] } };
320
+ const formatted = formats !== undefined && formats !== null && formats.length > 0;
321
+ if (formatted) return { def: { type: 'string', format: formats[0] } };
319
322
  return { def: 'string' };
320
323
  };
321
324
 
@@ -335,13 +338,18 @@ const mapOf = (target, state) => {
335
338
  // as an optional key, so it is written with one more.
336
339
  const nameOf = (key) => (key.endsWith('?') ? `${key}?` : key);
337
340
 
341
+ const presenceOf = (absent, nul) => {
342
+ if (absent) return OPTIONAL;
343
+ return nul ? NULLABLE : REQUIRED;
344
+ };
345
+
338
346
  // A key of a struct: optional when some record lacks it or holds undefined,
339
347
  // nullable when every record has it and some hold null.
340
348
  const keyOf = (child, records, state) => {
341
349
  const absent = child.count < records || (child.bits & UNDEF) !== 0;
342
350
  const nul = (child.bits & NULL) !== 0;
343
351
  if ((child.bits & ~PRESENCE) === 0) return bareOf(child.bits, absent);
344
- return written(formOf(child, state), absent ? OPTIONAL : nul ? NULLABLE : REQUIRED);
352
+ return written(formOf(child, state), presenceOf(absent, nul));
345
353
  };
346
354
 
347
355
  const recordOf = (target, state) => {
@@ -390,19 +398,15 @@ const formOf = (target, state) => {
390
398
  const mismatch = (state, index, issue) => {
391
399
  finalize([issue], en);
392
400
  const at = toDotPath(issue.path, state.name);
393
- const error = invalid(
394
- 'ERR_INFER_MISMATCH',
395
- `The inferred definition rejects sample ${index} at "${at}": ${issue.message}`,
396
- );
397
- error.index = index;
398
- return error;
401
+ const message = `The inferred definition rejects sample ${index} at "${at}": ${issue.message}`;
402
+ return new SchemaDefinitionError(message, { code: 'ALX_ERR_INFER_MISMATCH', index });
399
403
  };
400
404
 
401
- const option = (name, expected) => invalidOptions(`Infer option "${name}" must be ${expected}`);
405
+ const option = (name, expected) => wrongOption(`Infer option "${name}" must be ${expected}`);
402
406
 
403
407
  const optionsOf = (options) => {
404
408
  if (options === null || typeof options !== 'object') {
405
- throw invalidOptions('Infer options must be an object');
409
+ throw wrongOption('Infer options must be an object');
406
410
  }
407
411
  const {
408
412
  as = 'definition',
@@ -411,12 +415,12 @@ const optionsOf = (options) => {
411
415
  enum: cap = 8,
412
416
  integer = true,
413
417
  map = 16,
414
- maxDepth = DEPTH,
418
+ maxDepth = MAX_DEPTH,
415
419
  formats = true,
416
420
  } = options;
417
421
  if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
418
422
  if (typeof name !== 'string') throw option('name', 'a string');
419
- if (typeof kind !== 'string' || kind === '') throw option('kind', 'the name of a kind');
423
+ if (kindKeyOf(kind) === null) throw option('kind', 'the name of a kind');
420
424
  if (cap !== false && (!Number.isInteger(cap) || cap < 0)) {
421
425
  throw option('enum', 'an integer of at least 0, or false');
422
426
  }
@@ -424,8 +428,8 @@ const optionsOf = (options) => {
424
428
  if (map !== false && (!Number.isInteger(map) || map < 1)) {
425
429
  throw option('map', 'an integer of at least 1, or false');
426
430
  }
427
- if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > DEPTH) {
428
- throw option('maxDepth', `an integer from 1 to ${DEPTH}`);
431
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > MAX_DEPTH) {
432
+ throw option('maxDepth', `an integer from 1 to ${MAX_DEPTH}`);
429
433
  }
430
434
  if (typeof formats !== 'boolean') throw option('formats', 'a boolean');
431
435
  const state = { as, name, kind, enum: cap === false ? 0 : cap, integer, map, maxDepth };
@@ -442,17 +446,33 @@ const optionsOf = (options) => {
442
446
  // The samples as a list, read twice (the summary, then the self-check). A
443
447
  // string is iterable, over its characters, and surely a mistake.
444
448
  const listOf = (samples) => {
445
- const iterable =
446
- samples !== null &&
447
- samples !== undefined &&
448
- typeof samples !== 'string' &&
449
- typeof samples[Symbol.iterator] === 'function';
450
- if (!iterable) throw invalidTarget('An iterable of samples is expected');
449
+ const ruledOut = samples === undefined || samples === null || typeof samples === 'string';
450
+ if (ruledOut || typeof samples[Symbol.iterator] !== 'function') {
451
+ throw invalidTarget('An iterable of samples is expected');
452
+ }
451
453
  const list = Array.isArray(samples) ? samples : Array.from(samples);
452
454
  if (list.length === 0) throw invalidTarget('At least one sample is expected');
453
455
  return list;
454
456
  };
455
457
 
458
+ // The definition of the root. A root of records is a struct with its kind;
459
+ // a root of records and null or undefined is a union of that one struct,
460
+ // since the `schema` shorthand at the root is the struct itself and cannot
461
+ // be optional.
462
+ const rootDefinition = (root, state) => {
463
+ const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
464
+ const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
465
+ if (form === null) return bareOf(root.bits, (root.bits & UNDEF) !== 0);
466
+ if (form.struct === undefined) return written(form, presence);
467
+ if (presence !== REQUIRED) {
468
+ const union = { def: { union: [written(form, REQUIRED)] } };
469
+ return written(union, presence);
470
+ }
471
+ const definition = { [kindKeyOf(state.kind)]: {} };
472
+ for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
473
+ return definition;
474
+ };
475
+
456
476
  // A definition (or a Schema, with `as: 'schema'`) that accepts every
457
477
  // sample. `options`: `as`, `name`, `kind` (the kind of a root that is a
458
478
  // struct, 'struct'), `enum` (the most distinct strings of a place for an
@@ -466,18 +486,7 @@ const infer = (samples, options = {}) => {
466
486
  state.index = index;
467
487
  add(root, list[index], state, 0);
468
488
  }
469
- // A root of records is a struct with its kind; a root of records and
470
- // null or undefined is a union of that one struct, since the `schema`
471
- // shorthand at the root is the struct itself and cannot be optional.
472
- let definition;
473
- const presence = root.bits & PRESENCE ? OPTIONAL : REQUIRED;
474
- const form = (root.bits & ~PRESENCE) === 0 ? null : formOf(root, state);
475
- if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
476
- else if (form.struct === undefined) definition = written(form, presence);
477
- else if (presence === REQUIRED) {
478
- definition = { [capitalize(state.kind)]: {} };
479
- for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
480
- } else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
489
+ const definition = rootDefinition(root, state);
481
490
  const schema = new Schema(state.name, definition);
482
491
  const check = { unknown: 'reject', maxErrors: 1 };
483
492
  for (let index = 0; index < list.length; index += 1) {
@@ -2,20 +2,19 @@
2
2
  // constraints of both (the length and the bounds that satisfy both, the
3
3
  // values both enums hold, the validate functions of both), a field in one
4
4
  // comes as it is, and what no value can satisfy (two types, two patterns,
5
- // bounds with nothing in common, two defaults) is ERR_MERGE_CONFLICT with
5
+ // bounds with nothing in common, two defaults) is ALX_ERR_MERGE_CONFLICT with
6
6
  // the field. CUE composes definitions this way, instead of inheritance.
7
7
  const { hasBrand, define } = require('../util.js');
8
8
  const { Schema } = require('../schema.js');
9
9
  const { isStruct } = require('../struct.js');
10
- const { isThenable } = require('../issues.js');
11
- const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
10
+ const { isThenable, observe } = require('../issues.js');
11
+ const { SchemaDefinitionError, SchemaUsageError, invalidTarget } = require('../errors.js');
12
12
  const {
13
13
  same,
14
14
  definitionOf,
15
15
  structDefinitionOf,
16
16
  metadataOf,
17
17
  structDefinition,
18
- atSchema,
19
18
  namespacesOf,
20
19
  } = require('./data.js');
21
20
 
@@ -26,24 +25,33 @@ const BOOLEANS = new Set(['unique', 'index', 'primary', 'deprecated']);
26
25
  // A conflict carries the path of the field it is at; `merge` locates it in
27
26
  // the schema on the way out, as a struct does with a definition error.
28
27
  const conflict = (reason, path = '') => {
29
- const error = new SchemaDefinitionError('ERR_MERGE_CONFLICT', reason);
30
- error.field = path;
31
- return error;
28
+ return new SchemaDefinitionError(reason, { code: 'ALX_ERR_MERGE_CONFLICT', field: path });
32
29
  };
33
30
 
34
31
  // Both validate functions, as one that returns what both returned (an
35
32
  // array of returns is one the check reads), awaited when either is async.
33
+ // The promise of the first is observed before the second runs: a second that
34
+ // throws leaves it behind, and it must not reject unhandled.
36
35
  const compose = (first, second) =>
37
36
  function validate(value, path) {
38
- const a = first.call(this, value, path);
37
+ const returned = first.call(this, value, path);
38
+ const a = isThenable(returned) ? observe(returned) : returned;
39
39
  const b = second.call(this, value, path);
40
40
  if (isThenable(a) || isThenable(b)) return Promise.all([a, b]);
41
41
  return [a, b];
42
42
  };
43
43
 
44
- const lower = (a, b) => (a === undefined ? b : b === undefined ? a : a > b ? a : b);
44
+ const lower = (a, b) => {
45
+ if (a === undefined) return b;
46
+ if (b === undefined) return a;
47
+ return a > b ? a : b;
48
+ };
45
49
 
46
- const upper = (a, b) => (a === undefined ? b : b === undefined ? a : a < b ? a : b);
50
+ const upper = (a, b) => {
51
+ if (a === undefined) return b;
52
+ if (b === undefined) return a;
53
+ return a < b ? a : b;
54
+ };
47
55
 
48
56
  // The length both rules allow: the greater of the minimums, the lesser of
49
57
  // the maximums.
@@ -153,7 +161,9 @@ const mergeFields = (x, y, path) => {
153
161
  const b = typeof y === 'string' ? { type: y } : y;
154
162
  const type = mergeType(a.type, b.type, path);
155
163
  // The side whose type the result has sets the keys of its type.
156
- const [first, second] = type === b.type && type !== a.type ? [b, a] : [a, b];
164
+ const swapped = type === b.type && type !== a.type;
165
+ const first = swapped ? b : a;
166
+ const second = swapped ? a : b;
157
167
  const def = { type };
158
168
  const keys = new Set(Object.keys(first));
159
169
  for (const key of Object.keys(second)) keys.add(key);
@@ -212,7 +222,9 @@ const merge = (a, b, options = {}) => {
212
222
  throw invalidTarget('Two Schemas are expected');
213
223
  }
214
224
  if (options === null || typeof options !== 'object') {
215
- throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Merge options must be an object');
225
+ throw new SchemaUsageError('Merge options must be an object', {
226
+ code: 'ALX_ERR_INVALID_OPTION',
227
+ });
216
228
  }
217
229
  const { name = a.name, metadata = {} } = options;
218
230
  const namespaces = namespacesOf([a, b]);
@@ -249,12 +261,11 @@ const merge = (a, b, options = {}) => {
249
261
  }
250
262
  return new Schema(name, definition, namespaces);
251
263
  } catch (error) {
252
- if (error instanceof SchemaDefinitionError && error.code === 'ERR_MERGE_CONFLICT') {
253
- const { field } = error;
254
- error.field = '';
255
- if (field) error.locate(name, field);
256
- else atSchema(error, name);
257
- }
264
+ // A conflict carries its field from where it was found: located at the
265
+ // schema, its message names the place.
266
+ const isConflict =
267
+ error instanceof SchemaDefinitionError && error.code === 'ALX_ERR_MERGE_CONFLICT';
268
+ if (isConflict) error.locate(name, '');
258
269
  throw error;
259
270
  }
260
271
  };
@@ -3,12 +3,26 @@
3
3
  // random source of the sample. The subset is what a validation pattern is
4
4
  // made of: alternatives, groups, classes, escapes and quantifiers; what
5
5
  // generates no string (a lookaround, a back reference, a word boundary) is
6
- // ERR_SAMPLE_PATTERN. Nothing here reads a schema: `sample.js` hands over
6
+ // ALX_ERR_SAMPLE_PATTERN. Nothing here reads a schema: `sample.js` hands over
7
7
  // the RegExp and the random source, and the letters of the locale are read
8
8
  // at draw time, so the nodes serve every locale.
9
9
  const { SchemaDefinitionError } = require('../errors.js');
10
10
 
11
- const invalid = (reason) => new SchemaDefinitionError('ERR_SAMPLE_PATTERN', reason);
11
+ // How many times a quantifier may repeat, and how deep groups may nest: the
12
+ // bounds of what a draw allocates and of what the parser recurses into.
13
+ const MAX_REPEAT = 10_000;
14
+ const MAX_GROUP_DEPTH = 64;
15
+
16
+ const LETTER = /^[A-Za-z]$/;
17
+
18
+ const PATTERNS = new WeakMap();
19
+
20
+ // The pool a negated class draws from: the letters and digits that are not
21
+ // in it; a class that excludes the letters excludes every letter of the
22
+ // pool, since \P{L} matches no letter in any locale.
23
+ const POOL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_- ';
24
+
25
+ const invalid = (reason) => new SchemaDefinitionError(reason, { code: 'ALX_ERR_SAMPLE_PATTERN' });
12
26
 
13
27
  // A whole number in [0, max], and an element of a list, from the random
14
28
  // source of a sample.
@@ -22,32 +36,100 @@ const code = (char) => char.codePointAt(0);
22
36
 
23
37
  const range = (from, to) => [code(from), code(to)];
24
38
 
25
- // How many times a quantifier may repeat, and how deep groups may nest: the
26
- // bounds of what a draw allocates and of what the parser recurses into.
27
- const MAX_REPEAT = 10_000;
28
- const MAX_GROUPS = 64;
29
-
30
- const CLASSES = Object.assign(Object.create(null), {
39
+ const CLASSES = {
40
+ __proto__: null,
31
41
  d: [range('0', '9')],
32
42
  w: [range('0', '9'), range('A', 'Z'), range('a', 'z'), range('_', '_')],
33
43
  s: [range(' ', ' ')],
34
- });
44
+ };
35
45
 
36
46
  // The Unicode property escapes a validation pattern uses; the letters are
37
47
  // those of the locale, read when the string is drawn.
38
- const PROPERTIES = Object.assign(Object.create(null), {
48
+ const PROPERTIES = {
49
+ __proto__: null,
39
50
  L: 'letters',
40
51
  Letter: 'letters',
41
52
  Lu: [range('A', 'Z')],
42
53
  Ll: [range('a', 'z')],
43
54
  N: [range('0', '9')],
44
55
  Nd: [range('0', '9')],
45
- });
46
-
47
- const LETTER = /^[A-Za-z]$/;
56
+ };
48
57
 
49
58
  const classNode = (set, negate, letters) => ({ set, negate, letters });
50
59
 
60
+ // The fewest code points a string of the node has: a lower bound of its
61
+ // length however the length rule counts (a surrogate pair in the source is
62
+ // two text nodes and one code point).
63
+ const minLengthOf = (node) => {
64
+ if (node.text !== undefined) return /^[\uDC00-\uDFFF]$/.test(node.text) ? 0 : 1;
65
+ if (node.set !== undefined) return 1;
66
+ if (node.alt !== undefined) {
67
+ let least = Infinity;
68
+ for (const branch of node.alt) least = Math.min(least, minLengthOf(branch));
69
+ return least;
70
+ }
71
+ if (node.seq !== undefined) {
72
+ let total = 0;
73
+ for (const part of node.seq) total += minLengthOf(part);
74
+ return total;
75
+ }
76
+ return node.min * minLengthOf(node.node);
77
+ };
78
+
79
+ // The nodes of a RegExp and the minimal length of its strings, once per
80
+ // RegExp: the nodes carry nothing of a locale or a seed.
81
+ const patternOf = (pattern) => {
82
+ let entry = PATTERNS.get(pattern);
83
+ if (entry === undefined) {
84
+ const node = new PatternParser(pattern.source).parse();
85
+ entry = { node, minLength: minLengthOf(node) };
86
+ PATTERNS.set(pattern, entry);
87
+ }
88
+ return entry;
89
+ };
90
+
91
+ const inSet = (set, point) => {
92
+ for (const pair of set) if (point >= pair[0] && point <= pair[1]) return true;
93
+ return false;
94
+ };
95
+
96
+ // A character of a class: one of its ranges, or a letter of the locale
97
+ // where the class holds them.
98
+ const fromSet = (state, node) => {
99
+ if (node.negate) {
100
+ const out = [];
101
+ for (const char of POOL) {
102
+ if (!inSet(node.set, code(char)) && !(node.letters && LETTER.test(char))) out.push(char);
103
+ }
104
+ if (out.length === 0) throw invalid('A class excludes every character');
105
+ return pick(state, out);
106
+ }
107
+ const choices = node.set.length + (node.letters ? 1 : 0);
108
+ if (choices === 0) throw invalid('A class allows no character');
109
+ const index = int(state, choices - 1);
110
+ if (index === node.set.length) return pick(state, state.letters);
111
+ const pair = node.set[index];
112
+ return String.fromCodePoint(pair[0] + int(state, pair[1] - pair[0]));
113
+ };
114
+
115
+ // `extra` is how many repetitions an unbounded quantifier may add: the
116
+ // length the field asks for, when it does, else a few.
117
+ const fromPattern = (state, node, extra) => {
118
+ if (node.text !== undefined) return node.text;
119
+ if (node.set !== undefined) return fromSet(state, node);
120
+ if (node.alt !== undefined) return fromPattern(state, pick(state, node.alt), extra);
121
+ if (node.seq !== undefined) {
122
+ let text = '';
123
+ for (const part of node.seq) text += fromPattern(state, part, extra);
124
+ return text;
125
+ }
126
+ const max = node.max === Infinity ? node.min + extra : node.max;
127
+ const count = node.min + int(state, max - node.min);
128
+ let text = '';
129
+ for (let index = 0; index < count; index += 1) text += fromPattern(state, node.node, extra);
130
+ return text;
131
+ };
132
+
51
133
  // The nodes of a pattern: { alt }, { seq }, { set, negate, letters } for a
52
134
  // class (`letters`: the letters of the locale are in it), { text }, and
53
135
  // { node, min, max } for a repetition.
@@ -110,7 +192,9 @@ class PatternParser {
110
192
 
111
193
  group() {
112
194
  this.groups += 1;
113
- if (this.groups > MAX_GROUPS) throw this.fail(`groups nested deeper than ${MAX_GROUPS}`);
195
+ if (this.groups > MAX_GROUP_DEPTH) {
196
+ throw this.fail(`groups nested deeper than ${MAX_GROUP_DEPTH}`);
197
+ }
114
198
  if (this.peek() === '?') {
115
199
  this.next();
116
200
  const kind = this.next();
@@ -128,7 +212,7 @@ class PatternParser {
128
212
 
129
213
  // A class escape (\d, \w, \s, \p{..}) as ranges, the negated ones as
130
214
  // what they are not among the letters and digits, or one character.
131
- escape(inSet) {
215
+ escape(isInClass) {
132
216
  const char = this.next();
133
217
  if (char === undefined) throw this.fail('a trailing backslash');
134
218
  const lower = char.toLowerCase();
@@ -146,7 +230,7 @@ class PatternParser {
146
230
  const letters = property === 'letters';
147
231
  return classNode(letters ? [] : property, char !== lower, letters);
148
232
  }
149
- if (char === 'b' && !inSet) throw this.fail('a word boundary');
233
+ if (char === 'b' && !isInClass) throw this.fail('a word boundary');
150
234
  if (char === 'B' || char === 'k' || (char >= '1' && char <= '9')) {
151
235
  throw this.fail('a back reference');
152
236
  }
@@ -197,11 +281,8 @@ class PatternParser {
197
281
  }
198
282
  char = escaped.text;
199
283
  }
200
- if (
201
- this.peek() === '-' &&
202
- this.source[this.at + 1] !== ']' &&
203
- this.at + 1 < this.source.length
204
- ) {
284
+ const isRange = this.peek() === '-' && this.at + 1 < this.source.length;
285
+ if (isRange && this.source[this.at + 1] !== ']') {
205
286
  this.next();
206
287
  let to = this.next();
207
288
  if (to === '\\') to = this.escape(true).text;
@@ -227,7 +308,9 @@ class PatternParser {
227
308
  const match = /^\{(\d+)(,(\d*))?\}$/.exec(this.source.slice(this.at, close + 1));
228
309
  if (match === null) return node;
229
310
  min = Number(match[1]);
230
- max = match[2] === undefined ? min : match[3] === '' ? Infinity : Number(match[3]);
311
+ if (match[2] === undefined) max = min;
312
+ else if (match[3] === '') max = Infinity;
313
+ else max = Number(match[3]);
231
314
  if (min > MAX_REPEAT || (max !== Infinity && max > MAX_REPEAT)) {
232
315
  throw this.fail(`a repetition over ${MAX_REPEAT}`);
233
316
  }
@@ -239,84 +322,4 @@ class PatternParser {
239
322
  }
240
323
  }
241
324
 
242
- // The fewest code points a string of the node has: a lower bound of its
243
- // length however the length rule counts (a surrogate pair in the source is
244
- // two text nodes and one code point).
245
- const minLengthOf = (node) => {
246
- if (node.text !== undefined) return /^[\uDC00-\uDFFF]$/.test(node.text) ? 0 : 1;
247
- if (node.set !== undefined) return 1;
248
- if (node.alt !== undefined) {
249
- let least = Infinity;
250
- for (const branch of node.alt) least = Math.min(least, minLengthOf(branch));
251
- return least;
252
- }
253
- if (node.seq !== undefined) {
254
- let total = 0;
255
- for (const part of node.seq) total += minLengthOf(part);
256
- return total;
257
- }
258
- return node.min * minLengthOf(node.node);
259
- };
260
-
261
- const PATTERNS = new WeakMap();
262
-
263
- // The nodes of a RegExp and the minimal length of its strings, once per
264
- // RegExp: the nodes carry nothing of a locale or a seed.
265
- const patternOf = (pattern) => {
266
- let entry = PATTERNS.get(pattern);
267
- if (entry === undefined) {
268
- const node = new PatternParser(pattern.source).parse();
269
- entry = { node, minLength: minLengthOf(node) };
270
- PATTERNS.set(pattern, entry);
271
- }
272
- return entry;
273
- };
274
-
275
- // The pool a negated class draws from: the letters and digits that are not
276
- // in it; a class that excludes the letters excludes every letter of the
277
- // pool, since \P{L} matches no letter in any locale.
278
- const POOL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_- ';
279
-
280
- const inSet = (set, point) => {
281
- for (const pair of set) if (point >= pair[0] && point <= pair[1]) return true;
282
- return false;
283
- };
284
-
285
- // A character of a class: one of its ranges, or a letter of the locale
286
- // where the class holds them.
287
- const fromSet = (state, node) => {
288
- if (node.negate) {
289
- const out = [];
290
- for (const char of POOL) {
291
- if (!inSet(node.set, code(char)) && !(node.letters && LETTER.test(char))) out.push(char);
292
- }
293
- if (out.length === 0) throw invalid('A class excludes every character');
294
- return pick(state, out);
295
- }
296
- const choices = node.set.length + (node.letters ? 1 : 0);
297
- if (choices === 0) throw invalid('A class allows no character');
298
- const index = int(state, choices - 1);
299
- if (index === node.set.length) return pick(state, state.letters);
300
- const pair = node.set[index];
301
- return String.fromCodePoint(pair[0] + int(state, pair[1] - pair[0]));
302
- };
303
-
304
- // `extra` is how many repetitions an unbounded quantifier may add: the
305
- // length the field asks for, when it does, else a few.
306
- const fromPattern = (state, node, extra) => {
307
- if (node.text !== undefined) return node.text;
308
- if (node.set !== undefined) return fromSet(state, node);
309
- if (node.alt !== undefined) return fromPattern(state, pick(state, node.alt), extra);
310
- if (node.seq !== undefined) {
311
- let text = '';
312
- for (const part of node.seq) text += fromPattern(state, part, extra);
313
- return text;
314
- }
315
- const max = node.max === Infinity ? node.min + extra : node.max;
316
- const count = node.min + int(state, max - node.min);
317
- let text = '';
318
- for (let index = 0; index < count; index += 1) text += fromPattern(state, node.node, extra);
319
- return text;
320
- };
321
-
322
325
  module.exports = { int, pick, patternOf, fromPattern };