@alexify/metaschema 3.4.1 → 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 +162 -1
  2. package/README.md +22 -7
  3. package/SECURITY.md +5 -4
  4. package/index.d.ts +856 -460
  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 +14 -11
  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 +18 -16
  30. package/src/lint.js +15 -18
  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 +17 -20
  35. package/src/model/diff.js +29 -24
  36. package/src/model/index.d.ts +51 -35
  37. package/src/model/infer.js +69 -60
  38. package/src/model/merge.js +29 -18
  39. package/src/model/pattern.js +105 -102
  40. package/src/model/restore.js +24 -19
  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 +13 -13
  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 +6 -5
  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 +15 -13
  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 +28 -22
  65. package/src/util.js +65 -64
  66. package/src/validation.js +10 -13
package/src/errors.js CHANGED
@@ -1,61 +1,29 @@
1
- // A broken definition is a programming error, so it throws instead of being
2
- // collected like a validation error. The throw sites (type parsing, custom type
3
- // registration, projections) rarely know which entity and field they are
4
- // parsing; the struct that owns the field does, and calls `locate` on the way
5
- // up, so the message ends with `in "Entity.field"`.
6
- class SchemaDefinitionError extends TypeError {
7
- #reason;
8
-
9
- constructor(code, reason) {
10
- super(reason);
11
- this.code = code;
12
- this.schema = '';
13
- this.field = '';
14
- this.#reason = reason;
15
- }
16
-
17
- locate(schema, field) {
18
- this.schema = schema;
19
- this.field = this.field ? `${field}.${this.field}` : field;
20
- const location = schema ? `${schema}.${this.field}` : this.field;
21
- this.message = `${this.#reason} in "${location}"`;
22
- return this;
23
- }
24
- }
25
-
26
- SchemaDefinitionError.prototype.name = 'SchemaDefinitionError';
1
+ // The mark the validation half leaves on the process when it is installed
2
+ // (`validation.js`): a schema whose classes have no validation where the
3
+ // mark is there is one of another copy of the package.
4
+ const VALIDATION = Symbol.for('alexify.metaschema.validation');
27
5
 
28
6
  // A validator, a custom checkType or a decoder returned a promise to a
29
7
  // synchronous check or parse: a programming error of the call, not of the
30
8
  // value, so it throws with a code of its own and names the method to use.
31
- const asyncReturn = (what, where, method) => {
32
- const error = new TypeError(`The ${what} of "${where}" returned a promise; use ${method}`);
33
- error.code = 'ERR_ASYNC_VALIDATOR';
34
- return error;
35
- };
9
+ const asyncReturn = (what, where, method) =>
10
+ new SchemaUsageError(`The ${what} of "${where}" returned a promise; use ${method}`, {
11
+ code: 'ALX_ERR_ASYNC_VALIDATOR',
12
+ });
36
13
 
37
14
  // A function of a subpath was given something other than what it takes (a
38
15
  // Schema, a Model, a snapshot, a list of changes): the call is wrong, not a
39
- // definition, so a plain TypeError with a code of its own, like asyncReturn.
40
- const invalidTarget = (message) => {
41
- const error = new TypeError(message);
42
- error.code = 'ERR_INVALID_TARGET';
43
- return error;
44
- };
16
+ // definition.
17
+ const invalidTarget = (message) =>
18
+ new SchemaUsageError(message, { code: 'ALX_ERR_INVALID_TARGET' });
45
19
 
46
20
  // A call that needs what `register()` of a subpath installs (the converters
47
21
  // of coercion, the module of the mongodb driver) before that ran: the
48
22
  // program is wired wrong, not a value or a definition.
49
- const notRegistered = (what, where) => {
50
- const error = new TypeError(`${what} needs register() of @alexify/metaschema/${where} first`);
51
- error.code = 'ERR_NOT_REGISTERED';
52
- return error;
53
- };
54
-
55
- // The mark the validation half leaves on the process when it is installed
56
- // (`validation.js`): a schema whose classes have no validation where the
57
- // mark is there is one of another copy of the package.
58
- const VALIDATION = Symbol.for('alexify.metaschema.validation');
23
+ const notRegistered = (what, where) =>
24
+ new SchemaUsageError(`${what} needs register() of @alexify/metaschema/${where} first`, {
25
+ code: 'ALX_ERR_NOT_REGISTERED',
26
+ });
59
27
 
60
28
  // A schema of `./definition` asked to validate before the core entry was
61
29
  // loaded: the half of the core that validates is not installed into its
@@ -67,30 +35,87 @@ const noValidation = (what) => {
67
35
  ? 'the core entry loaded is another copy of the package than the one that built the ' +
68
36
  'schema (deduplicate @alexify/metaschema)'
69
37
  : './definition alone does not validate';
70
- const error = new TypeError(`${what} needs the core entry @alexify/metaschema: ${reason}`);
71
- error.code = 'ERR_NOT_REGISTERED';
72
- error.method = what;
73
- return error;
38
+ const message = `${what} needs the core entry @alexify/metaschema: ${reason}`;
39
+ return new SchemaUsageError(message, { code: 'ALX_ERR_NOT_REGISTERED', method: what });
74
40
  };
75
41
 
42
+ // A symbol has no JSON, and a template literal throws on it.
76
43
  const shown = (value) =>
77
44
  typeof value === 'bigint' ? `${value}n` : (JSON.stringify(value) ?? String(value));
78
45
 
79
46
  // An option of a call that is not what it must be (`maxErrors`, the options
80
- // of the stream subpath): a TypeError naming it, with a code of its own, as
81
- // invalidTarget is.
82
- const invalidOption = (name, expected, value) => {
83
- const error = new TypeError(`${name} must be ${expected}, got ${shown(value)}`);
84
- error.code = 'ERR_INVALID_OPTION';
85
- return error;
86
- };
47
+ // of the stream subpath): an error naming it, with a code of its own.
48
+ const invalidOption = (name, expected, value) =>
49
+ new SchemaUsageError(`${name} must be ${expected}, got ${shown(value)}`, {
50
+ code: 'ALX_ERR_INVALID_OPTION',
51
+ });
52
+
53
+ // A broken definition is a programming error, so it throws instead of being
54
+ // collected like a validation error. The throw sites (type parsing, custom type
55
+ // registration, projections) rarely know which entity and field they are
56
+ // parsing; the struct that owns the field does, and calls `locate` on the way
57
+ // up, so the message ends with `in "Entity.field"`. Its constructor is
58
+ // Error's, `(message, options = {})`: `options` holds the code, the cause, the
59
+ // place it is at (`schema`, `field`, which `locate` writes into the message)
60
+ // and the fields some codes carry (`index`, the sample infer could not
61
+ // accept; `seed`, the draw nothing satisfies), and goes to `super` whole, so
62
+ // `cause` is set only when given. Every field is set here, none afterwards.
63
+ class SchemaDefinitionError extends TypeError {
64
+ #reason;
65
+
66
+ constructor(message, options = {}) {
67
+ super(message, options);
68
+ const { code = 'ALX_ERR_INVALID_DEFINITION', schema = '', field = '', index, seed } = options;
69
+ this.code = code;
70
+ this.schema = schema;
71
+ this.field = field;
72
+ this.#reason = message;
73
+ if (index !== undefined) this.index = index;
74
+ if (seed !== undefined) this.seed = seed;
75
+ }
76
+
77
+ // A `field` of '' locates an error of the schema as a whole at the schema.
78
+ locate(schema, field) {
79
+ this.schema = schema;
80
+ if (field !== '') this.field = this.field ? `${field}.${this.field}` : field;
81
+ let location = this.field;
82
+ if (schema !== '') location = this.field === '' ? schema : `${schema}.${this.field}`;
83
+ this.message = `${this.#reason} in "${location}"`;
84
+ return this;
85
+ }
86
+ }
87
+
88
+ SchemaDefinitionError.prototype.name = 'SchemaDefinitionError';
89
+
90
+ // A call that is wrong, where a definition is not: a target or an option
91
+ // it does not take, a method that needs what a `register()` installs, a
92
+ // promise where the call is synchronous, an invalid record a stream was
93
+ // not told to drop. A TypeError, as it was a plain one until 4.0, made as
94
+ // SchemaDefinitionError is: `(message, options = {})`, with the code, the
95
+ // cause and the fields some codes carry in `options` (the record of a stream,
96
+ // its position and its result; the method a schema of `./definition` was
97
+ // asked for).
98
+ class SchemaUsageError extends TypeError {
99
+ constructor(message, options = {}) {
100
+ super(message, options);
101
+ const { code = 'ALX_ERR_INVALID_TARGET', index, record, result, method } = options;
102
+ this.code = code;
103
+ if (index !== undefined) this.index = index;
104
+ if (record !== undefined) this.record = record;
105
+ if (result !== undefined) this.result = result;
106
+ if (method !== undefined) this.method = method;
107
+ }
108
+ }
109
+
110
+ SchemaUsageError.prototype.name = 'SchemaUsageError';
87
111
 
88
112
  module.exports = {
89
113
  SchemaDefinitionError,
114
+ SchemaUsageError,
115
+ VALIDATION,
90
116
  asyncReturn,
91
117
  invalidTarget,
92
118
  notRegistered,
93
119
  noValidation,
94
- VALIDATION,
95
120
  invalidOption,
96
121
  };
@@ -1,8 +1,10 @@
1
- // A format a string field may name: a test over the string, the examples
2
- // `sample` draws, whether `infer` may read the format out of data (true
3
- // unless said otherwise; a format ordinary words pass says false), and the
4
- // pattern the JSON Schema export writes beside the name (a string that
5
- // compiles in unicode mode, a shape that never rejects what `test` accepts).
1
+ /**
2
+ * A format a string field may name: a test over the string, the examples
3
+ * `sample` draws, whether `infer` may read the format out of data (true
4
+ * unless said otherwise; a format ordinary words pass says false), and the
5
+ * pattern the JSON Schema export writes beside the name (a string that
6
+ * compiles in unicode mode, a shape that never rejects what `test` accepts).
7
+ */
6
8
  export interface FormatDefinition {
7
9
  test: (value: string) => boolean;
8
10
  examples: readonly string[];
@@ -10,22 +12,26 @@ export interface FormatDefinition {
10
12
  pattern?: string;
11
13
  }
12
14
 
13
- // The formats registered so far, by name: empty until `register()` ran. Read
14
- // it; `register()` writes it.
15
+ /**
16
+ * The formats registered so far, by name: empty until `register()` ran. Read
17
+ * it; `register()` writes it.
18
+ */
15
19
  export const FORMATS: { readonly [name: string]: Readonly<FormatDefinition> | undefined };
16
20
 
17
- // Registers the 35 built-in formats (the identifiers `uuid`, `ulid`, `jwt`,
18
- // `nanoid`, `cuid2`; the dates and times `date-time`, `iso-date-time`,
19
- // `date`, `time`, `iso-time`, `duration`; the network forms `email`,
20
- // `ipv4`, `cidrv4`, `ipv6`, `cidrv6`, `mac`, `url`, `uri`, `hostname`; the
21
- // formats of JSON Schema `uri-reference`, `uri-template`, `json-pointer`,
22
- // `relative-json-pointer`, `regex`; and `e164`, `iban`, `hex-color`,
23
- // `base64`, `base64url`, `hex`, `emoji`, `semver`, `slug`, `credit-card`)
24
- // and the program's own, once per name and process-wide, like the type
25
- // registry: a name registered again with the same test is nothing, with
26
- // another test `ERR_FORMAT_REGISTERED`, and an entry that is not a format
27
- // `ERR_INVALID_FORMAT`. The program's own format under the name of a
28
- // built-in one takes its place, and the call returns the names of the
29
- // built-in formats it replaced (an empty list otherwise); the schemas built
30
- // before keep the built-in test.
21
+ /**
22
+ * Registers the 35 built-in formats (the identifiers `uuid`, `ulid`, `jwt`,
23
+ * `nanoid`, `cuid2`; the dates and times `date-time`, `iso-date-time`,
24
+ * `date`, `time`, `iso-time`, `duration`; the network forms `email`,
25
+ * `ipv4`, `cidrv4`, `ipv6`, `cidrv6`, `mac`, `url`, `uri`, `hostname`; the
26
+ * formats of JSON Schema `uri-reference`, `uri-template`, `json-pointer`,
27
+ * `relative-json-pointer`, `regex`; and `e164`, `iban`, `hex-color`,
28
+ * `base64`, `base64url`, `hex`, `emoji`, `semver`, `slug`, `credit-card`)
29
+ * and the program's own, once per name and process-wide, like the type
30
+ * registry: a name registered again with the same test is nothing, with
31
+ * another test `ALX_ERR_FORMAT_REGISTERED`, and an entry that is not a format
32
+ * `ALX_ERR_INVALID_FORMAT`. The program's own format under the name of a
33
+ * built-in one takes its place, and the call returns the names of the
34
+ * built-in formats it replaced (an empty list otherwise); the schemas built
35
+ * before keep the built-in test.
36
+ */
31
37
  export function register(custom?: Record<string, FormatDefinition>): string[];
@@ -35,7 +35,7 @@ const { FORMATS } = require('../rules.js');
35
35
  const { SchemaDefinitionError } = require('../errors.js');
36
36
 
37
37
  const invalidFormat = (name, reason) =>
38
- new SchemaDefinitionError('ERR_INVALID_FORMAT', `Format "${name}" ${reason}`);
38
+ new SchemaDefinitionError(`Format "${name}" ${reason}`, { code: 'ALX_ERR_INVALID_FORMAT' });
39
39
 
40
40
  // ajv-formats' fast email: a local part of its characters, an `@`, and
41
41
  // labels of at most 63 characters joined by dots.
@@ -104,11 +104,12 @@ const isIsoTime = timeOf(false);
104
104
 
105
105
  // A date-time is the two joined by `T` (or, as the RFC allows for
106
106
  // readability, a space).
107
- const dateTimeOf = (time) => (text) =>
108
- text.length > 11 &&
109
- (text[10] === 'T' || text[10] === 't' || text[10] === ' ') &&
110
- isDate(text.slice(0, 10)) &&
111
- time(text.slice(11));
107
+ const DATE_TIME_SEPARATORS = new Set(['T', 't', ' ']);
108
+
109
+ const dateTimeOf = (time) => (text) => {
110
+ if (text.length <= 11 || !DATE_TIME_SEPARATORS.has(text[10])) return false;
111
+ return isDate(text.slice(0, 10)) && time(text.slice(11));
112
+ };
112
113
 
113
114
  const DURATION = /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/;
114
115
 
@@ -204,10 +205,10 @@ const isRelativePointer = (text) => {
204
205
  // mode. Compiling one costs memory in proportion to its text (a property
205
206
  // escape expands as it is parsed), so a text longer than any pattern a
206
207
  // program writes is not one; `length.max` on the field bounds it further.
207
- const REGEX_MAX = 4096;
208
+ const REGEX_MAX_CHARS = 4096;
208
209
 
209
210
  const isRegex = (text) => {
210
- if (text.length > REGEX_MAX) return false;
211
+ if (text.length > REGEX_MAX_CHARS) return false;
211
212
  try {
212
213
  return RegExp(text, 'u') instanceof RegExp;
213
214
  } catch {
@@ -507,10 +508,9 @@ const entryOf = (name, entry) => {
507
508
  };
508
509
 
509
510
  const registered = (name) =>
510
- new SchemaDefinitionError(
511
- 'ERR_FORMAT_REGISTERED',
512
- `Format "${name}" is already registered with another test`,
513
- );
511
+ new SchemaDefinitionError(`Format "${name}" is already registered with another test`, {
512
+ code: 'ALX_ERR_FORMAT_REGISTERED',
513
+ });
514
514
 
515
515
  // A name is registered once: the same test again is nothing, and another
516
516
  // test under a registered name is an error, since the schemas built so far
@@ -541,7 +541,9 @@ const add = (name, entry, own) => {
541
541
  // what it overrode; an empty list otherwise.
542
542
  const register = (custom = {}) => {
543
543
  if (custom === null || typeof custom !== 'object') {
544
- throw new SchemaDefinitionError('ERR_INVALID_FORMAT', 'Formats must be an object of entries');
544
+ throw new SchemaDefinitionError('Formats must be an object of entries', {
545
+ code: 'ALX_ERR_INVALID_FORMAT',
546
+ });
545
547
  }
546
548
  const replaced = [];
547
549
  for (const name of Object.keys(BUILT_IN)) {