@alexify/metaschema 3.3.0 → 3.4.1

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 (53) hide show
  1. package/CHANGELOG.md +251 -1
  2. package/README.md +31 -20
  3. package/SECURITY.md +24 -1
  4. package/index.d.ts +280 -48
  5. package/package.json +13 -3
  6. package/src/checks.js +789 -0
  7. package/src/codec.js +37 -13
  8. package/src/coerce/index.js +34 -1
  9. package/src/compile/emit.js +87 -28
  10. package/src/compile/index.js +9 -4
  11. package/src/definition/index.d.ts +19 -0
  12. package/src/definition/index.js +27 -0
  13. package/src/derive/index.js +23 -13
  14. package/src/errors.js +23 -0
  15. package/src/generators/fromjsonschema.js +14 -0
  16. package/src/generators/index.js +1 -1
  17. package/src/generators/jsonschema.js +44 -7
  18. package/src/generators/typescript.js +11 -0
  19. package/src/index.js +3 -2
  20. package/src/issues.js +9 -7
  21. package/src/kinds.js +24 -2
  22. package/src/lint.js +64 -2
  23. package/src/locales/en.js +6 -0
  24. package/src/locales/uk.js +6 -0
  25. package/src/metadata.js +2 -24
  26. package/src/model/data.js +68 -11
  27. package/src/model/diff.js +7 -4
  28. package/src/model/index.js +1 -1
  29. package/src/model/infer.js +13 -6
  30. package/src/model/merge.js +7 -3
  31. package/src/model/restore.js +60 -8
  32. package/src/model/sample.js +26 -1
  33. package/src/model.js +25 -53
  34. package/src/mongodb/bson.js +15 -3
  35. package/src/mongodb/document.js +10 -2
  36. package/src/preprocessor.js +14 -5
  37. package/src/prototypes/abstract.js +32 -64
  38. package/src/prototypes/collections.js +3 -90
  39. package/src/prototypes/flags.js +34 -0
  40. package/src/prototypes/json.js +0 -11
  41. package/src/prototypes/reference.js +0 -76
  42. package/src/prototypes/scalars.js +17 -96
  43. package/src/prototypes/schema.js +1 -10
  44. package/src/prototypes/tuple.js +5 -31
  45. package/src/prototypes/union.js +12 -82
  46. package/src/rules.js +33 -157
  47. package/src/schema.js +108 -233
  48. package/src/snapshot.js +216 -41
  49. package/src/stream/index.js +1 -1
  50. package/src/struct.js +6 -91
  51. package/src/types.js +31 -10
  52. package/src/util.js +48 -0
  53. package/src/validation.js +313 -0
@@ -6,6 +6,7 @@ const { isFirstUpper } = require('../metautil.js');
6
6
  const { hasBrand, IDENTIFIER } = require('../util.js');
7
7
  const { SchemaDefinitionError } = require('../errors.js');
8
8
  const { embeds } = require('../prototypes/reference.js');
9
+ const { baseTypeOf } = require('../types.js');
9
10
 
10
11
  const TS_SCALARS = Object.assign(Object.create(null), {
11
12
  string: 'string',
@@ -13,6 +14,7 @@ const TS_SCALARS = Object.assign(Object.create(null), {
13
14
  boolean: 'boolean',
14
15
  bigint: 'bigint',
15
16
  date: 'Date',
17
+ bytes: 'Uint8Array',
16
18
  null: 'null',
17
19
  any: 'any',
18
20
  unknown: 'unknown',
@@ -118,6 +120,15 @@ const tsBase = (def, ts, name, target, top) => {
118
120
  ts.blocks.push(`type ${named} = ${text};`);
119
121
  return named;
120
122
  }
123
+ // By the type, as JSON Schema tells it: `flags` is an option name any type
124
+ // may carry (a pattern's, a custom type's).
125
+ if (baseTypeOf(def).type === 'flags') {
126
+ const names = [];
127
+ for (let index = 0; index < def.flags.length; index += 1) {
128
+ names.push(`${tsKey(def.flags[index])}?: boolean`);
129
+ }
130
+ return `{ ${names.join('; ')} }`;
131
+ }
121
132
  if (def.union) {
122
133
  const branches = [];
123
134
  for (let index = 0; index < def.union.length; index += 1) {
package/src/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  const { constants, getKindMetadata } = require('./kinds.js');
2
- const { Schema } = require('./schema.js');
2
+ // The core entry: the definition half (the classes) with the validation
3
+ // half installed into them (validation.js).
4
+ const { Schema, ValidationResult } = require('./validation.js');
3
5
  const { Model } = require('./model.js');
4
6
  const { SchemaDefinitionError } = require('./errors.js');
5
- const { ValidationResult } = require('./result.js');
6
7
 
7
8
  const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
8
9
 
package/src/issues.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // are rendered once, at the end of the check, through the locale of that check.
5
5
  // Every issue has the same keys in the same order, so loops over them see one
6
6
  // shape.
7
- const { hasBrand, shorten, safeString } = require('./util.js');
7
+ const { hasBrand, shorten, safeString, typeOf } = require('./util.js');
8
8
  const { asyncReturn } = require('./errors.js');
9
9
  const en = require('./locales/en.js');
10
10
 
@@ -37,12 +37,6 @@ const record = (context, code, params, key, message = '') => {
37
37
  push(context, { code, path: pathOf(context, key), message, params });
38
38
  };
39
39
 
40
- const typeOf = (value) => {
41
- if (value === null) return 'null';
42
- if (Array.isArray(value)) return 'array';
43
- return typeof value;
44
- };
45
-
46
40
  const issues = {
47
41
  required: (context, key) => record(context, 'required', EMPTY, key),
48
42
  type: (context, expected, value, key) =>
@@ -55,6 +49,14 @@ const issues = {
55
49
  range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
56
50
  pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
57
51
  format: (context, format, key) => record(context, 'format', { format }, key),
52
+ // NaN and the infinities have no decimals: the value is named then.
53
+ decimals: (context, decimals, value, key) =>
54
+ record(
55
+ context,
56
+ 'decimals',
57
+ Number.isFinite(value) ? { decimals } : { decimals, received: String(value) },
58
+ key,
59
+ ),
58
60
  union: (context, expected, discriminator, key) =>
59
61
  record(context, 'union', { expected, discriminator }, key),
60
62
  reference: (context, entity, key) => record(context, 'reference', { entity }, key),
package/src/kinds.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { toLowerCamel } = require('./metautil.js');
2
+ const { hasBrand } = require('./util.js');
2
3
  const { SchemaDefinitionError } = require('./errors.js');
3
4
 
4
5
  const projectionError = (name, reason) =>
@@ -10,6 +11,24 @@ const KIND_STORED = [...KIND_ENT, ...KIND_AUX];
10
11
  const KIND_MEMORY = ['struct', 'scalar', 'form', 'projection'];
11
12
  const KIND = [...KIND_MEMORY, ...KIND_STORED];
12
13
 
14
+ // A key is a kind when its name is one a kind may have (a capital letter,
15
+ // then letters and digits, one of them lowercase: `Entity`, `Settings`,
16
+ // never `PORT` or `DATABASE_URL`) and its value is the metadata of a kind:
17
+ // a plain object of any realm, not a string, a list, a function or anything
18
+ // built (a Schema, a field, a struct). Any other capitalized key is a field.
19
+ // The one rule: the preprocessor reads the first key by it, what writes a
20
+ // definition (derive, merge, fromJSON) holds a kind to it, and `KindKey` of
21
+ // the typings mirrors it.
22
+ const KIND_NAME = /^[A-Z][A-Z\d]*[a-z][A-Za-z\d]*$/;
23
+
24
+ const isMetadata = (value) => {
25
+ if (value === null || typeof value !== 'object' || hasBrand(value, 'Struct')) return false;
26
+ const proto = Object.getPrototypeOf(value);
27
+ return proto === null || Object.getPrototypeOf(proto) === null;
28
+ };
29
+
30
+ const isKindKey = (key, meta) => KIND_NAME.test(key) && isMetadata(meta);
31
+
13
32
  const SCOPE = ['application', 'global', 'local'];
14
33
  const STORE = ['persistent', 'memory'];
15
34
  const ALLOW = ['write', 'append', 'read'];
@@ -22,8 +41,11 @@ const projection = (kind, meta, root) => {
22
41
  }
23
42
  const parent = schema;
24
43
  const metadata = { ...meta, kind, scope, store, allow, parent };
44
+ // The projection itself is not built yet, so its own name is no parent.
25
45
  const entity = root.findReference(schema);
26
- if (!entity) throw projectionError(root.name, `parent "${schema}" is not found`);
46
+ if (!entity || entity === root) {
47
+ throw projectionError(root.name, `parent "${schema}" is not found`);
48
+ }
27
49
  const defs = Object.create(null);
28
50
  for (const key of fields) {
29
51
  const field = entity.fields[key];
@@ -71,4 +93,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
71
93
 
72
94
  const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
73
95
 
74
- module.exports = { constants, getKindMetadata, idFieldOf };
96
+ module.exports = { constants, getKindMetadata, idFieldOf, isKindKey };
package/src/lint.js CHANGED
@@ -2,14 +2,15 @@
2
2
  // what the author meant either. A contradiction that can never validate
3
3
  // (an enum without values, a min above max) is a SchemaDefinitionError at
4
4
  // build time; these are warnings, as `Warning [code]: text` strings.
5
- const { hasBrand } = require('./util.js');
5
+ const { hasBrand, formatters, KINDS } = require('./util.js');
6
+ const { firstKey } = require('./metautil.js');
6
7
  const { embeds } = require('./prototypes/reference.js');
7
8
 
8
9
  const warning = (code, text) => `Warning [${code}]: ${text}`;
9
10
 
10
11
  // The types no converter of coercion exists for: a value of them is taken
11
12
  // as it is.
12
- const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null']);
13
+ const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null', 'flags']);
13
14
 
14
15
  // A `coerce` key where no conversion can happen: a reference checked as an
15
16
  // id (the record it names is never entered), a type that takes any value.
@@ -70,6 +71,20 @@ const lintField = (field, path, warnings, element = false, member = false) => {
70
71
  const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
71
72
  warnings.push(warning('unbounded-pattern', text));
72
73
  }
74
+ if (field.decimals !== undefined) {
75
+ // The check tells a decimal too many apart below 2⁴³ units of the last
76
+ // decimal (ULPS of checks.js); a bound past it lets any number through.
77
+ // A side without a bound counts as 1.
78
+ const bound = Math.max(Math.abs(field.min ?? 1), Math.abs(field.max ?? 1));
79
+ const limit = 2 ** 43 / 10 ** field.decimals;
80
+ if (bound >= limit) {
81
+ const below = Number(limit.toPrecision(2));
82
+ const text =
83
+ `"${path}" has ${field.decimals} decimals, ` +
84
+ `which the check tells apart only below ${below}`;
85
+ warnings.push(warning('unenforceable-decimals', text));
86
+ }
87
+ }
73
88
  if (field.coerce !== undefined) {
74
89
  const dead = deadCoerce(field);
75
90
  if (dead !== '') {
@@ -120,11 +135,58 @@ const lintIndexes = (schema, warnings) => {
120
135
  }
121
136
  };
122
137
 
138
+ // Whether the first key of an object makes it the long form or the
139
+ // shorthand of a type.
140
+ const startsField = (def, types) => {
141
+ const first = firstKey(def);
142
+ if (first === undefined) return false;
143
+ const { field } = formatters.key(first);
144
+ return field === 'type' || types[field] !== undefined;
145
+ };
146
+
147
+ // Whether a value under a key reads as the definition of a field: the name
148
+ // of a type, or an object its first key makes one.
149
+ const readsAsField = (value, types) => {
150
+ if (typeof value === 'string') return types[formatters.type(value).type] !== undefined;
151
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
152
+ return startsField(value, types);
153
+ };
154
+
155
+ // A kind of the program's own (`{ Settings: { theme: 'dark' }, ... }`) whose
156
+ // metadata reads as a field or holds fields: most likely a field with a name
157
+ // like `Address`, first in its struct, that the first key made a kind, so
158
+ // the struct has no such field. The kinds are the ones the definition named
159
+ // at any depth, as the preprocessor kept them. `unknown` is a type name and
160
+ // a key of the metadata of every kind, where it is the policy.
161
+ const lintKinds = (schema, warnings) => {
162
+ const kinds = schema[KINDS];
163
+ if (!kinds) return;
164
+ const { name, types } = schema;
165
+ for (const pair of kinds) {
166
+ const key = pair[0];
167
+ const meta = pair[1];
168
+ let suspect = firstKey(meta) !== 'unknown' && startsField(meta, types);
169
+ if (!suspect) {
170
+ for (const option of Object.keys(meta)) {
171
+ if (!readsAsField(meta[option], types)) continue;
172
+ suspect = true;
173
+ break;
174
+ }
175
+ }
176
+ if (!suspect) continue;
177
+ const text =
178
+ `"${key}" of "${name}" is read as a kind, and its metadata reads as field definitions: ` +
179
+ `a field of that name needs a kind before it ({ Struct: {}, ${key}: ... })`;
180
+ warnings.push(warning('ambiguous-kind', text));
181
+ }
182
+ };
183
+
123
184
  // The warnings of one schema on its own: everything that needs no model.
124
185
  const lintSchema = (schema) => {
125
186
  const warnings = [];
126
187
  lintStruct(schema.fields, schema.name, warnings);
127
188
  lintIndexes(schema, warnings);
189
+ lintKinds(schema, warnings);
128
190
  return warnings;
129
191
  };
130
192
 
package/src/locales/en.js CHANGED
@@ -36,6 +36,11 @@ const pattern = ({ pattern: source }) => `does not match the pattern ${source}`;
36
36
 
37
37
  const format = ({ format: name }) => `is not a valid ${name}`;
38
38
 
39
+ const decimals = ({ decimals: count, received }) =>
40
+ received === undefined
41
+ ? `has more than ${count} decimals`
42
+ : `is ${received}, not a finite number`;
43
+
39
44
  const union = ({ expected, discriminator }) =>
40
45
  discriminator === undefined
41
46
  ? `does not match any of: ${expected.join(', ')}`
@@ -61,6 +66,7 @@ module.exports = {
61
66
  range,
62
67
  pattern,
63
68
  format,
69
+ decimals,
64
70
  union,
65
71
  reference,
66
72
  circular,
package/src/locales/uk.js CHANGED
@@ -34,6 +34,11 @@ const pattern = ({ pattern: source }) => `не відповідає шаблон
34
34
 
35
35
  const format = ({ format: name }) => `не є коректним ${name}`;
36
36
 
37
+ const decimals = ({ decimals: count, received }) =>
38
+ received === undefined
39
+ ? `має більше знаків після коми, ніж ${count}`
40
+ : `дорівнює ${received} і не є скінченним числом`;
41
+
37
42
  const union = ({ expected, discriminator }) =>
38
43
  discriminator === undefined
39
44
  ? `не відповідає жодному з: ${expected.join(', ')}`
@@ -59,6 +64,7 @@ module.exports = {
59
64
  range,
60
65
  pattern,
61
66
  format,
67
+ decimals,
62
68
  union,
63
69
  reference,
64
70
  circular,
package/src/metadata.js CHANGED
@@ -1,8 +1,5 @@
1
1
  const { getKindMetadata } = require('./kinds.js');
2
- const { ValidationResult } = require('./result.js');
3
- const { SchemaDefinitionError, asyncReturn } = require('./errors.js');
4
- const { isThenable } = require('./issues.js');
5
- const { safeString } = require('./util.js');
2
+ const { SchemaDefinitionError } = require('./errors.js');
6
3
 
7
4
  // The functions of a schema definition that are the schema's own: its
8
5
  // validate, its decoder, its serializer and `format`.
@@ -95,25 +92,6 @@ class SchemaMetadata {
95
92
  }
96
93
  return fields;
97
94
  }
98
-
99
- // Runs only the schema-level validate function, as a result of its own; a
100
- // function that returns a promise is an error here, as in check.
101
- validate(value, path = '') {
102
- if (!this.options.validate) return null;
103
- const result = new ValidationResult();
104
- try {
105
- const output = this.options.validate.call(this, value, path);
106
- if (isThenable(output)) throw asyncReturn('validator', path, 'checkAsync');
107
- return result.add(output);
108
- } catch (error) {
109
- if (error?.code === 'ERR_ASYNC_VALIDATOR') throw error;
110
- return result.add({
111
- code: 'exception',
112
- message: `validation failed ${safeString(error)}`,
113
- params: { error },
114
- });
115
- }
116
- }
117
95
  }
118
96
 
119
- module.exports = { ValidationResult, SchemaMetadata };
97
+ module.exports = { SchemaMetadata };
package/src/model/data.js CHANGED
@@ -3,10 +3,11 @@
3
3
  // snapshot is input (a file, a registry, another program), so what it says
4
4
  // is checked before it is read, and every error is ERR_INVALID_SNAPSHOT
5
5
  // located in the entity, never a bare SyntaxError or TypeError.
6
- const { hasBrand, define } = require('../util.js');
6
+ const { hasBrand, define, isDate, isRegExp } = require('../util.js');
7
7
  const { FORMAT } = require('../snapshot.js');
8
8
  const { SchemaDefinitionError } = require('../errors.js');
9
9
  const { isStruct } = require('../struct.js');
10
+ const { isKindKey } = require('../kinds.js');
10
11
 
11
12
  // How deep the walks over a snapshot go: a definition nested deeper is not
12
13
  // one a program wrote.
@@ -32,12 +33,24 @@ const isSnapshot = (value) =>
32
33
  isObject(value.entities) &&
33
34
  (value.types === undefined || isObject(value.types));
34
35
 
35
- // The snapshot of a model, or the snapshot given.
36
- const snapshotOf = (target) => {
36
+ // The entity a snapshot of one schema is about, when it names one: a key
37
+ // format 1 gained in 3.4, read by nothing else.
38
+ const checkRoot = (snapshot) => {
39
+ const { root } = snapshot;
40
+ if (root === undefined) return;
41
+ if (typeof root !== 'string' || !Object.hasOwn(snapshot.entities, root)) {
42
+ throw invalidSnapshot('The root of a snapshot must name one of its entities');
43
+ }
44
+ };
45
+
46
+ // The snapshot of a model, or the snapshot given, read as one (the writer of
47
+ // the core is `snapshotOf` of snapshot.js).
48
+ const readSnapshot = (target) => {
37
49
  if (hasBrand(target, 'Model')) return target.toJSON();
38
50
  if (!isSnapshot(target)) {
39
51
  throw invalidSnapshot(`A Model or a snapshot of format ${FORMAT} with entities is expected`);
40
52
  }
53
+ checkRoot(target);
41
54
  return target;
42
55
  };
43
56
 
@@ -49,12 +62,12 @@ const same = (a, b, depth = 0) => {
49
62
  if (a === b) return true;
50
63
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
51
64
  if (depth > DEPTH) throw tooDeep();
52
- const name = a.constructor?.name;
53
- if (name === 'RegExp' || name === 'Date') {
54
- if (name !== b.constructor?.name) return false;
55
- return name === 'Date'
56
- ? a.getTime() === b.getTime()
57
- : a.source === b.source && a.flags === b.flags;
65
+ // By their shape, which a value of JSON cannot fake: `{ constructor: {
66
+ // name: 'Date' } }` of a snapshot is data.
67
+ const regExp = isRegExp(a);
68
+ if (regExp || isRegExp(b) || isDate(a) || isDate(b)) {
69
+ if (regExp) return isRegExp(b) && a.source === b.source && a.flags === b.flags;
70
+ return isDate(a) && isDate(b) && a.getTime() === b.getTime();
58
71
  }
59
72
  if (Array.isArray(a)) {
60
73
  if (!Array.isArray(b) || a.length !== b.length) return false;
@@ -76,6 +89,16 @@ const isFunctionMarker = (value) => isObject(value) && value.$function === true;
76
89
 
77
90
  const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1);
78
91
 
92
+ // The key a kind is written under as the first key of a definition (`entity`
93
+ // is `Entity`), null for a name that key would not be read back as a kind
94
+ // from (`dTO`, `api_config`: `isKindKey` of kinds.js): the fields after it
95
+ // would read as something else.
96
+ const kindKeyOf = (kind) => {
97
+ if (typeof kind !== 'string' || kind === '') return null;
98
+ const key = capitalize(kind);
99
+ return isKindKey(key, {}) ? key : null;
100
+ };
101
+
79
102
  // The definition a built field was made from, with its nested fields as
80
103
  // definitions and its functions kept: what `merge` unifies and `Schema`
81
104
  // takes back.
@@ -116,11 +139,42 @@ const metadataOf = (schema) => {
116
139
  // its first key, so the fields after it read as a struct whatever their names.
117
140
  const structDefinition = (base, metadata, fields) => {
118
141
  const { kind = base.kind, ...rest } = { ...base, ...metadata };
119
- const definition = { [capitalize(kind)]: rest };
142
+ const kindKey = kindKeyOf(kind);
143
+ if (kindKey === null) {
144
+ const reason = `Metadata "kind" must be the name of a kind, got ${JSON.stringify(kind)}`;
145
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
146
+ }
147
+ const definition = { [kindKey]: rest };
120
148
  for (const key of Object.keys(fields)) define(definition, key, fields[key]);
121
149
  return definition;
122
150
  };
123
151
 
152
+ // The namespaces of a schema built from schemas: theirs, and for a schema
153
+ // that names itself without a model holding it (`parent: '?Category'`
154
+ // resolves to the schema itself), one that holds it, so that what is built
155
+ // from it, under its name or another, reaches the schema it was built from
156
+ // as it did.
157
+ const namespacesOf = (schemas) => {
158
+ const namespaces = new Set();
159
+ for (const schema of schemas) {
160
+ const { name } = schema;
161
+ let held = false;
162
+ for (const ns of schema.namespaces) {
163
+ namespaces.add(ns);
164
+ if (ns.entities.get(name) !== undefined) held = true;
165
+ }
166
+ if (name !== '' && !held && schema.references.has(name)) {
167
+ namespaces.add({
168
+ entities: new Map([[name, schema]]),
169
+ get types() {
170
+ return schema.types;
171
+ },
172
+ });
173
+ }
174
+ }
175
+ return Array.from(namespaces);
176
+ };
177
+
124
178
  module.exports = {
125
179
  DEPTH,
126
180
  invalidSnapshot,
@@ -128,12 +182,15 @@ module.exports = {
128
182
  atSchema,
129
183
  isObject,
130
184
  isSnapshot,
131
- snapshotOf,
185
+ checkRoot,
186
+ readSnapshot,
132
187
  same,
133
188
  isFunctionMarker,
134
189
  capitalize,
190
+ kindKeyOf,
135
191
  definitionOf,
136
192
  structDefinitionOf,
137
193
  metadataOf,
138
194
  structDefinition,
195
+ namespacesOf,
139
196
  };
package/src/model/diff.js CHANGED
@@ -15,7 +15,7 @@ const {
15
15
  invalidSnapshot,
16
16
  atSchema,
17
17
  isObject,
18
- snapshotOf,
18
+ readSnapshot,
19
19
  same,
20
20
  isFunctionMarker,
21
21
  } = require('./data.js');
@@ -188,8 +188,8 @@ const diffEntity = (name, old, current, changes) => {
188
188
  // entities of `next` in their order (added, or their changes), the entities
189
189
  // that are gone, then the types.
190
190
  const diff = (prev, next) => {
191
- const old = snapshotOf(prev);
192
- const current = snapshotOf(next);
191
+ const old = readSnapshot(prev);
192
+ const current = readSnapshot(next);
193
193
  const changes = [];
194
194
  for (const name of Object.keys(current.entities)) {
195
195
  const to = current.entities[name];
@@ -243,7 +243,8 @@ const includes = (list, value) => {
243
243
  return false;
244
244
  };
245
245
 
246
- // Values added accept more (backward), values removed accept less (forward).
246
+ // Values added accept more (backward), values removed accept less (forward);
247
+ // the names of flags the same way.
247
248
  const enumLevel = (from, to) => {
248
249
  let level = FULL;
249
250
  for (const value of to) if (!includes(from, value)) level &= BACKWARD;
@@ -325,11 +326,13 @@ const keyLevel = (key, from, to, field) => {
325
326
  case 'min':
326
327
  return boundLevel(from, to, true);
327
328
  case 'max':
329
+ case 'decimals':
328
330
  return boundLevel(from, to, false);
329
331
  case 'pattern':
330
332
  case 'format':
331
333
  return from === undefined ? FORWARD : to === undefined ? BACKWARD : NONE;
332
334
  case 'enum':
335
+ case 'flags':
333
336
  return Array.isArray(from) && Array.isArray(to) ? enumLevel(from, to) : NONE;
334
337
  case 'validate':
335
338
  case 'parse':
@@ -6,7 +6,7 @@
6
6
  // program that only validates does not carry them. The functions take
7
7
  // Models, Schemas, snapshots or samples; `register()` installs them as
8
8
  // members of the classes for the programs that want the methods.
9
- const { Schema } = require('../schema.js');
9
+ const { Schema } = require('../validation.js');
10
10
  const { Model } = require('../model.js');
11
11
  const { fromJSON } = require('./restore.js');
12
12
  const { diff, compatibility, compatibilityOf } = require('./diff.js');
@@ -8,14 +8,14 @@
8
8
  // against every sample, so that what comes back is a schema the samples
9
9
  // pass. The samples are input: the walk is bounded, no key is trusted, and
10
10
  // what no type describes is `any` rather than an error.
11
- const { define, IDENTIFIER, shorten } = require('../util.js');
12
- const { Schema } = require('../schema.js');
11
+ const { define, IDENTIFIER, shorten, isBytes } = require('../util.js');
12
+ const { Schema } = require('../validation.js');
13
13
  const { SchemaDefinitionError, 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');
18
+ const { DEPTH, kindKeyOf } = require('./data.js');
19
19
 
20
20
  const invalid = (code, reason) => new SchemaDefinitionError(code, reason);
21
21
 
@@ -39,6 +39,7 @@ const RECORD = 2048;
39
39
  const BLANK = 4096;
40
40
  // A value no type describes but `any`: a function, a symbol, an invalid Date.
41
41
  const ANY = 8192;
42
+ const BYTES = 16384;
42
43
 
43
44
  const PRESENCE = NULL | UNDEF;
44
45
 
@@ -136,7 +137,8 @@ const addItems = (target, items, state, depth) => {
136
137
  // One value into the summary of its place. The tests are the ones the
137
138
  // check makes (a Date by its constructor name and a valid time, a Set and a
138
139
  // Map by name, an integer by Number.isInteger, the keys of a record by
139
- // Object.keys), so what infer calls a date the check accepts as one.
140
+ // Object.keys, bytes by the view's own name), so what infer calls a date
141
+ // the check accepts as one.
140
142
  const add = (target, value, state, depth) => {
141
143
  target.count += 1;
142
144
  if (value === null) {
@@ -180,6 +182,10 @@ const add = (target, value, state, depth) => {
180
182
  addItems(target, value, state, depth);
181
183
  return;
182
184
  }
185
+ if (isBytes(value)) {
186
+ target.bits |= BYTES;
187
+ return;
188
+ }
183
189
  const iterable = typeof value[Symbol.iterator] === 'function';
184
190
  if (name === 'Set' && iterable) {
185
191
  target.bits |= SET;
@@ -369,6 +375,7 @@ const formOf = (target, state) => {
369
375
  if (bits & BIGINT) forms.push({ def: 'bigint' });
370
376
  if (bits & STRING) forms.push(stringOf(target, state));
371
377
  if (bits & DATE) forms.push({ def: 'date' });
378
+ if (bits & BYTES) forms.push({ def: 'bytes' });
372
379
  if (bits & LIST) forms.push({ def: { array: itemOf(target.item, state) } });
373
380
  if (bits & SET) forms.push({ def: { set: itemOf(target.item, state) } });
374
381
  if (bits & MAP) forms.push(mapOf(target, state));
@@ -409,7 +416,7 @@ const optionsOf = (options) => {
409
416
  } = options;
410
417
  if (as !== 'definition' && as !== 'schema') throw option('as', '"definition" or "schema"');
411
418
  if (typeof name !== 'string') throw option('name', 'a string');
412
- if (typeof kind !== 'string' || kind === '') throw option('kind', 'the name of a kind');
419
+ if (kindKeyOf(kind) === null) throw option('kind', 'the name of a kind');
413
420
  if (cap !== false && (!Number.isInteger(cap) || cap < 0)) {
414
421
  throw option('enum', 'an integer of at least 0, or false');
415
422
  }
@@ -468,7 +475,7 @@ const infer = (samples, options = {}) => {
468
475
  if (form === null) definition = bareOf(root.bits, (root.bits & UNDEF) !== 0);
469
476
  else if (form.struct === undefined) definition = written(form, presence);
470
477
  else if (presence === REQUIRED) {
471
- definition = { [capitalize(state.kind)]: {} };
478
+ definition = { [kindKeyOf(state.kind)]: {} };
472
479
  for (const key of Object.keys(form.struct)) define(definition, key, form.struct[key]);
473
480
  } else definition = written({ def: { union: [written(form, REQUIRED)] } }, presence);
474
481
  const schema = new Schema(state.name, definition);
@@ -16,6 +16,7 @@ const {
16
16
  metadataOf,
17
17
  structDefinition,
18
18
  atSchema,
19
+ namespacesOf,
19
20
  } = require('./data.js');
20
21
 
21
22
  // The keys a field definition settles by a rule of its own; every other key
@@ -58,7 +59,7 @@ const mergeLength = (a, b, path) => {
58
59
  return length;
59
60
  };
60
61
 
61
- const mergeEnum = (a, b, path) => {
62
+ const mergeEnum = (a, b, path, what = 'enums') => {
62
63
  const values = [];
63
64
  for (const value of a) {
64
65
  for (const other of b) {
@@ -68,7 +69,7 @@ const mergeEnum = (a, b, path) => {
68
69
  }
69
70
  }
70
71
  }
71
- if (values.length === 0) throw conflict('The enums have no value in common', path);
72
+ if (values.length === 0) throw conflict(`The ${what} have no value in common`, path);
72
73
  return values;
73
74
  };
74
75
 
@@ -97,9 +98,12 @@ const mergeKey = (key, a, b, path) => {
97
98
  case 'min':
98
99
  return a > b ? a : b;
99
100
  case 'max':
101
+ case 'decimals':
100
102
  return a < b ? a : b;
101
103
  case 'enum':
102
104
  return mergeEnum(a, b, path);
105
+ case 'flags':
106
+ return mergeEnum(a, b, path, 'flags');
103
107
  case 'validate':
104
108
  return compose(a, b);
105
109
  case 'aliases':
@@ -211,7 +215,7 @@ const merge = (a, b, options = {}) => {
211
215
  throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', 'Merge options must be an object');
212
216
  }
213
217
  const { name = a.name, metadata = {} } = options;
214
- const namespaces = Array.from(new Set([...a.namespaces, ...b.namespaces]));
218
+ const namespaces = namespacesOf([a, b]);
215
219
  const structA = isStruct(a.fields);
216
220
  const structB = isStruct(b.fields);
217
221
  try {