@alexify/metaschema 3.2.0 → 3.3.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.
@@ -9,6 +9,9 @@ const { hasBrand, define } = require('../util.js');
9
9
  const { isStruct } = require('../struct.js');
10
10
  const { SchemaDefinitionError } = require('../errors.js');
11
11
  const { embeds } = require('../prototypes/reference.js');
12
+ const { FORMATS } = require('../rules.js');
13
+ const { idFieldOf } = require('../kinds.js');
14
+ const { baseTypeOf } = require('../types.js');
12
15
 
13
16
  // What differs between the dialects: the keyword of a type, where the
14
17
  // definitions live, whether `const`, tuples, `propertyNames` and siblings of
@@ -40,6 +43,8 @@ const TARGETS = Object.assign(Object.create(null), {
40
43
  definitions: '#/components/schemas/',
41
44
  nullable: true,
42
45
  oneOf: true,
46
+ // OpenAPI's name of base64 text.
47
+ byte: true,
43
48
  annotations: ['title', 'description', 'default', 'example', 'deprecated'],
44
49
  },
45
50
  mongodb: {
@@ -111,6 +116,14 @@ const createContext = (options, unknown) => {
111
116
  );
112
117
  }
113
118
  const mongo = name === 'mongodb';
119
+ // The ids of stored records as MongoDB holds them (the ./mongodb subpath
120
+ // writes them so): an ObjectId under `_id`, and in every reference.
121
+ const objectIds = option(options, 'ids', ['string', 'objectId']) === 'objectId';
122
+ if (objectIds && !mongo) {
123
+ throw invalidOptions(
124
+ `JSON Schema option "ids" "objectId" needs target "mongodb", got "${name}"`,
125
+ );
126
+ }
114
127
  if (!mongo && !isPointer(definitions)) {
115
128
  throw invalidOptions('JSON Schema option "definitions" must be a pointer such as "#/$defs/"');
116
129
  }
@@ -124,6 +137,7 @@ const createContext = (options, unknown) => {
124
137
  input: mongo || io === 'input',
125
138
  any,
126
139
  references,
140
+ objectIds,
127
141
  strict,
128
142
  closed: strict || unknown !== 'ignore',
129
143
  prefix: mongo ? null : definitions,
@@ -295,11 +309,12 @@ const reference = (field, context) => {
295
309
  const name = field.type;
296
310
  const target = field.root.findReference(name);
297
311
  let json;
312
+ const id = context.objectIds ? { bsonType: 'objectId' } : typed('string', context);
298
313
  if (target === null) {
299
314
  if (field.embed === true) json = unrepresentable(context, `Reference "${name}" (embed)`);
300
- else json = typed('string', context);
315
+ else json = id;
301
316
  } else if (!embeds(target, field.embed, context.references)) {
302
- json = typed('string', context);
317
+ json = id;
303
318
  } else {
304
319
  json = definition(target, context);
305
320
  }
@@ -331,9 +346,16 @@ const RENDER = Object.assign(Object.create(null), {
331
346
  const json = typed('string', context);
332
347
  if (context.strict) return json;
333
348
  bounds(json, field.length, 'minLength', 'maxLength');
349
+ // A format a validator may not know (`ulid`, `iban`) is asserted by its
350
+ // shape too, where the field has no pattern of its own.
351
+ const shape = field.format === undefined ? undefined : FORMATS[field.format]?.pattern;
334
352
  if (field.pattern !== undefined) json.pattern = field.pattern.source;
353
+ else if (shape !== undefined) json.pattern = shape;
335
354
  // The names are those of JSON Schema; a $jsonSchema has no `format`.
336
- if (field.format !== undefined && !context.mongo) json.format = field.format;
355
+ if (field.format !== undefined && !context.mongo) {
356
+ const byte = field.format === 'base64' && context.target.byte === true;
357
+ json.format = byte ? 'byte' : field.format;
358
+ }
337
359
  return json;
338
360
  },
339
361
  number: (field, context) => ranged(typed('number', context), field, context),
@@ -373,12 +395,7 @@ const RENDER = Object.assign(Object.create(null), {
373
395
 
374
396
  // The built-in type a field validates as: its own, or the one its alias
375
397
  // chain ends in.
376
- const baseOf = (field) => {
377
- const { types } = field.root;
378
- let Type = field.constructor;
379
- while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
380
- return Type.type;
381
- };
398
+ const baseOf = (field) => baseTypeOf(field).type;
382
399
 
383
400
  // The schema of the type of a field: the metadata of a custom type when it
384
401
  // says (`jsonSchema`, or `bson` for mongodb), else the built-in it is or
@@ -407,14 +424,20 @@ const render = (field, context) => {
407
424
  // A struct: its validated fields as properties (a calculated field is a
408
425
  // function and has no schema), the required ones listed, no other keys
409
426
  // unless the schema ignores them. The strict profile lists every property.
410
- const struct = (fields, context) => {
427
+ const struct = (fields, context, id = null, root = false) => {
411
428
  const properties = {};
412
429
  const required = [];
430
+ // The id field of a stored record is `_id` in the document, the first key;
431
+ // the database gives one to a record inserted without it.
432
+ if (id !== null) {
433
+ properties[ID] = { bsonType: 'objectId' };
434
+ if (root) required.push(ID);
435
+ }
413
436
  // A struct is a null-prototype dictionary: its own keys, in order; a key
414
437
  // such as `__proto__` is defined as data on the document.
415
438
  for (const key in fields) {
416
439
  const field = fields[key];
417
- if (!hasBrand(field, 'Type')) continue;
440
+ if (key === id || !hasBrand(field, 'Type')) continue;
418
441
  try {
419
442
  define(properties, key, render(field, context));
420
443
  } catch (error) {
@@ -430,14 +453,23 @@ const struct = (fields, context) => {
430
453
  return json;
431
454
  };
432
455
 
456
+ // The id field a stored kind adds, which `ids: 'objectId'` writes as `_id`,
457
+ // unless the schema has an `_id` of its own.
458
+ const idOf = (schema, context) => {
459
+ if (!context.objectIds) return null;
460
+ const id = idFieldOf(schema);
461
+ return id === null || ID in schema.fields ? null : id;
462
+ };
463
+
433
464
  // The schema being rendered owns the location of an error met in it, and
434
465
  // is restored when the rendering leaves it, thrown out of or not.
435
- const renderSchema = (schema, context) => {
466
+ const renderSchema = (schema, context, root = false) => {
436
467
  const { owner } = context;
437
468
  const { fields } = schema;
438
469
  context.owner = schema.name;
439
470
  try {
440
- return isStruct(fields) ? struct(fields, context) : render(fields, context);
471
+ if (!isStruct(fields)) return render(fields, context);
472
+ return struct(fields, context, idOf(schema, context), root);
441
473
  } finally {
442
474
  context.owner = owner;
443
475
  }
@@ -452,7 +484,7 @@ const renderRoot = (schema, context) => {
452
484
  `Profile "strict" needs a struct at the root, got "${schema.fields.type}"`,
453
485
  );
454
486
  }
455
- const json = renderSchema(schema, context);
487
+ const json = renderSchema(schema, context, true);
456
488
  // Every stored document has an `_id`; a closed mongodb root must let it in.
457
489
  if (context.mongo && json.additionalProperties === false && json.properties[ID] === undefined) {
458
490
  json.properties[ID] = {};
package/src/kinds.js CHANGED
@@ -33,12 +33,21 @@ const projection = (kind, meta, root) => {
33
33
  return { defs, metadata };
34
34
  };
35
35
 
36
+ // The key of the id field a stored kind adds: named after the entity
37
+ // (`orderId`), `id` for an anonymous schema.
38
+ const idKeyOf = (name) => (name ? `${toLowerCamel(name)}Id` : 'id');
39
+
40
+ // The id field of a built schema: the key above for a stored kind, null for
41
+ // a memory kind. The one rule, read by the derive, mongodb and generators
42
+ // subpaths (which each add what `_id` means to them).
43
+ const idFieldOf = (schema) => (KIND_STORED.includes(schema.kind) ? idKeyOf(schema.name) : null);
44
+
36
45
  // The metadata of a kind over the defaults of its scope and store; a stored
37
46
  // kind adds the optional id field named after the entity.
38
47
  const kindOf = (defaultScope, defaultStore, stored) => (kind, meta, root) => {
39
48
  const { scope = defaultScope, store = defaultStore, allow = 'write' } = meta;
40
49
  const defs = Object.create(null);
41
- if (stored) defs[root.name ? `${toLowerCamel(root.name)}Id` : 'id'] = '?string';
50
+ if (stored) defs[idKeyOf(root.name)] = '?string';
42
51
  return { defs, metadata: { ...meta, kind, scope, store, allow } };
43
52
  };
44
53
 
@@ -62,4 +71,4 @@ const getKindMetadata = (kind, meta = {}, root) => {
62
71
 
63
72
  const constants = { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW };
64
73
 
65
- module.exports = { constants, getKindMetadata };
74
+ module.exports = { constants, getKindMetadata, idFieldOf };
package/src/lint.js CHANGED
@@ -3,9 +3,26 @@
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
5
  const { hasBrand } = require('./util.js');
6
+ const { embeds } = require('./prototypes/reference.js');
6
7
 
7
8
  const warning = (code, text) => `Warning [${code}]: ${text}`;
8
9
 
10
+ // The types no converter of coercion exists for: a value of them is taken
11
+ // as it is.
12
+ const NEVER_CONVERTED = new Set(['any', 'unknown', 'json', 'null']);
13
+
14
+ // A `coerce` key where no conversion can happen: a reference checked as an
15
+ // id (the record it names is never entered), a type that takes any value.
16
+ const deadCoerce = (field) => {
17
+ const name = field.one || field.many;
18
+ if (name !== undefined) {
19
+ const target = field.root.findReference(name);
20
+ if (target !== null && embeds(target, field.embed, 'kind')) return '';
21
+ return 'a reference checked as an id';
22
+ }
23
+ return NEVER_CONVERTED.has(field.type) ? `a value of type "${field.type}"` : '';
24
+ };
25
+
9
26
  // A field lints by its definition keys: the keys every type knows, the
10
27
  // annotations that any field may carry for code that reads the schema, and
11
28
  // the options of its own type. A custom type with its own construct owns
@@ -15,6 +32,7 @@ const KNOWN = new Set([
15
32
  'type',
16
33
  'required',
17
34
  'nullable',
35
+ 'coerce',
18
36
  'validate',
19
37
  'parse',
20
38
  'serialize',
@@ -52,6 +70,12 @@ const lintField = (field, path, warnings, element = false, member = false) => {
52
70
  const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
53
71
  warnings.push(warning('unbounded-pattern', text));
54
72
  }
73
+ if (field.coerce !== undefined) {
74
+ const dead = deadCoerce(field);
75
+ if (dead !== '') {
76
+ warnings.push(warning('dead-coerce', `"${path}" has coerce, but ${dead} is never converted`));
77
+ }
78
+ }
55
79
  if (field.schema !== undefined) lintStruct(field.schema, path, warnings);
56
80
  const { value, union } = field;
57
81
  if (value !== undefined) {
package/src/metadata.js CHANGED
@@ -61,6 +61,10 @@ class SchemaMetadata {
61
61
 
62
62
  #setMany(values) {
63
63
  const { kind, scope, store, allow, parent, unknown, ...custom } = values;
64
+ if (custom.coerce !== undefined && typeof custom.coerce !== 'boolean') {
65
+ const reason = `Schema metadata "coerce" must be a boolean, got ${JSON.stringify(custom.coerce)}`;
66
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
67
+ }
64
68
  this.kind = kind || this.kind;
65
69
  this.scope = scope || this.scope;
66
70
  this.store = store || this.store;
package/src/model/data.js CHANGED
@@ -106,6 +106,21 @@ const structDefinitionOf = (fields) => {
106
106
  return def;
107
107
  };
108
108
 
109
+ // The kind metadata of a built schema, as its definition gave it.
110
+ const metadataOf = (schema) => {
111
+ const { kind, scope, store, allow, unknown, custom } = schema;
112
+ return { kind, scope, store, allow, unknown, ...custom };
113
+ };
114
+
115
+ // A struct definition: the kind of `base` (unless `metadata` names one) as
116
+ // its first key, so the fields after it read as a struct whatever their names.
117
+ const structDefinition = (base, metadata, fields) => {
118
+ const { kind = base.kind, ...rest } = { ...base, ...metadata };
119
+ const definition = { [capitalize(kind)]: rest };
120
+ for (const key of Object.keys(fields)) define(definition, key, fields[key]);
121
+ return definition;
122
+ };
123
+
109
124
  module.exports = {
110
125
  DEPTH,
111
126
  invalidSnapshot,
@@ -119,4 +134,6 @@ module.exports = {
119
134
  capitalize,
120
135
  definitionOf,
121
136
  structDefinitionOf,
137
+ metadataOf,
138
+ structDefinition,
122
139
  };
@@ -9,7 +9,14 @@ const { Schema } = require('../schema.js');
9
9
  const { isStruct } = require('../struct.js');
10
10
  const { isThenable } = require('../issues.js');
11
11
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
12
- const { same, capitalize, definitionOf, structDefinitionOf, atSchema } = require('./data.js');
12
+ const {
13
+ same,
14
+ definitionOf,
15
+ structDefinitionOf,
16
+ metadataOf,
17
+ structDefinition,
18
+ atSchema,
19
+ } = require('./data.js');
13
20
 
14
21
  // The keys a field definition settles by a rule of its own; every other key
15
22
  // (an annotation, an option of a custom type) comes from the first schema.
@@ -216,12 +223,8 @@ const merge = (a, b, options = {}) => {
216
223
  namespaces,
217
224
  );
218
225
  }
219
- const { kind, scope, store, allow, unknown, custom } = a;
220
- const meta = { scope, store, allow, unknown, ...custom, ...metadata };
221
- const { kind: given = kind, ...rest } = meta;
222
- const definition = { [capitalize(given)]: rest };
223
226
  const fields = mergeStruct(structDefinitionOf(a.fields), structDefinitionOf(b.fields), '');
224
- for (const key of Object.keys(fields)) define(definition, key, fields[key]);
227
+ const definition = structDefinition(metadataOf(a), metadata, fields);
225
228
  for (const source of [a, b]) {
226
229
  for (const key in source.indexes) {
227
230
  const index = source.indexes[key];
@@ -9,6 +9,7 @@ const { hasBrand, define } = require('../util.js');
9
9
  const { createContext } = require('../context.js');
10
10
  const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
11
11
  const { isStruct } = require('../struct.js');
12
+ const { baseTypeOf } = require('../types.js');
12
13
  const { embeds } = require('../prototypes/reference.js');
13
14
  const { toDotPath, finalize } = require('../issues.js');
14
15
  const en = require('../locales/en.js');
@@ -48,9 +49,7 @@ const ABSENT = Symbol('absent');
48
49
  // The built-in type a field validates as: its own, or the one its alias
49
50
  // chain ends in; a custom type with a check of its own has none.
50
51
  const baseOf = (field) => {
51
- const { types } = field.root;
52
- let Type = field.constructor;
53
- while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
52
+ const Type = baseTypeOf(field);
54
53
  return Type.source === undefined ? Type.type : null;
55
54
  };
56
55
 
package/src/model.js CHANGED
@@ -1,4 +1,4 @@
1
- const { firstKey } = require('./metautil.js');
1
+ const { firstKey, isFirstLower } = require('./metautil.js');
2
2
 
3
3
  const { BRAND, INSPECT } = require('./util.js');
4
4
  const { Schema } = require('./schema.js');
@@ -7,15 +7,40 @@ const { SchemaDefinitionError } = require('./errors.js');
7
7
  const { warning } = require('./lint.js');
8
8
  const { snapshotOf } = require('./snapshot.js');
9
9
 
10
+ const invalidOption = (name, expected, value) => {
11
+ const reason = `Model option "${name}" must be ${expected}, got ${JSON.stringify(value)}`;
12
+ return new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
13
+ };
14
+
10
15
  const registryFor = (options) => {
11
16
  const { registry = 'shared' } = options;
12
17
  if (registry !== 'shared' && registry !== 'isolated') {
13
- const reason = `Model option "registry" must be "shared" or "isolated", got ${JSON.stringify(registry)}`;
14
- throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
18
+ throw invalidOption('registry', '"shared" or "isolated"', registry);
15
19
  }
16
20
  return registry === 'isolated' ? createRegistry() : TYPES;
17
21
  };
18
22
 
23
+ // The converters of coercion the model gives for its own type names, read
24
+ // by the `./coerce` subpath before the process-wide table for the fields
25
+ // of its entities (and of a schema that attaches the model): what an
26
+ // isolated registry is to the types. Frozen, with no prototype.
27
+ const coercionsFor = (options) => {
28
+ const { coercions = null } = options;
29
+ if (coercions === null) return null;
30
+ const expected = 'an object of functions by type name';
31
+ if (typeof coercions !== 'object' || Array.isArray(coercions)) {
32
+ throw invalidOption('coercions', expected, coercions);
33
+ }
34
+ const table = Object.create(null);
35
+ for (const name of Object.keys(coercions)) {
36
+ if (!isFirstLower(name) || typeof coercions[name] !== 'function') {
37
+ throw invalidOption('coercions', expected, name);
38
+ }
39
+ table[name] = coercions[name];
40
+ }
41
+ return Object.freeze(table);
42
+ };
43
+
19
44
  class Model {
20
45
  // The model's own warnings (the cycles met while ordering), found while
21
46
  // building; the rest comes from the entities on first use.
@@ -24,6 +49,7 @@ class Model {
24
49
 
25
50
  constructor(types, entities, database = null, options = {}) {
26
51
  this.types = typeFactory(types, registryFor(options));
52
+ this.coercions = coercionsFor(options);
27
53
  this.entities = new Map();
28
54
  this.database = database;
29
55
  this.order = new Set();
@@ -0,0 +1,118 @@
1
+ // The BSON side of the `./mongodb` subpath: the types a field holds a value
2
+ // of the driver in, and the module of the driver the program registers, the
3
+ // one that turns the ids a record carries as strings into ObjectIds. Nothing
4
+ // is imported from bson or mongodb: a value of the driver is recognized by
5
+ // its `_bsontype` and by a method that JSON cannot give a value (a body of a
6
+ // request claiming to be an ObjectId is data), never by `instanceof`, so a
7
+ // value of another realm or of another copy of bson is one too.
8
+ const { idFieldOf } = require('../kinds.js');
9
+ const { invalidOption, notRegistered } = require('../errors.js');
10
+ const { register: coercion } = require('../coerce/index.js');
11
+
12
+ // The tag every value of bson carries, and the key of a document.
13
+ const TAG = '_bsontype';
14
+ const ID = '_id';
15
+
16
+ const tagOf = (value) => (value !== null && typeof value === 'object' ? value[TAG] : undefined);
17
+
18
+ const isObjectId = (value) => {
19
+ const tag = tagOf(value);
20
+ return (tag === 'ObjectId' || tag === 'ObjectID') && typeof value.toHexString === 'function';
21
+ };
22
+
23
+ const isDecimal128 = (value) => tagOf(value) === 'Decimal128' && typeof value.toJSON === 'function';
24
+
25
+ const isBinary = (value) =>
26
+ (tagOf(value) === 'Binary' && typeof value.toJSON === 'function') ||
27
+ Object.prototype.toString.call(value) === '[object Uint8Array]';
28
+
29
+ const construct = () => {};
30
+
31
+ // A custom type as a model takes it: the check, the BSON type of the
32
+ // mongodb target and the JSON Schema of the value on the wire.
33
+ const typeOf = (test, bson, jsonSchema) =>
34
+ Object.freeze({
35
+ construct,
36
+ checkType: (value) => test(value),
37
+ metadata: Object.freeze({ bson, jsonSchema }),
38
+ });
39
+
40
+ const HEX = /^[0-9a-fA-F]{24}$/;
41
+
42
+ // The types to give a model: `new Model({ ...types, ...own }, entities)`.
43
+ // They are not registered by register(): a type name is a shorthand key of
44
+ // a definition, so a program says where it uses them.
45
+ const types = Object.freeze({
46
+ objectId: typeOf(isObjectId, 'objectId', { type: 'string', pattern: HEX.source }),
47
+ decimal128: typeOf(isDecimal128, 'decimal', { type: 'string' }),
48
+ binary: typeOf(isBinary, 'binData', { type: 'string', contentEncoding: 'base64' }),
49
+ });
50
+
51
+ // The module of the driver (or of bson) the program registered.
52
+ let driver = null;
53
+
54
+ const driverOf = () => {
55
+ if (driver === null) throw notRegistered('An ObjectId', 'mongodb');
56
+ return driver;
57
+ };
58
+
59
+ // The converters of coercion for the BSON types, the ones parse runs on the
60
+ // input of a field of such a type: a 24-digit hex string is an ObjectId, a
61
+ // decimal string or a number a Decimal128, base64 text a Binary. What they
62
+ // cannot read comes back as it was, for the check to report.
63
+ const toObjectId = (value) =>
64
+ typeof value === 'string' && HEX.test(value) ? new driver.ObjectId(value) : value;
65
+
66
+ // A decimal written as one (`fromString` of the driver reads `NaN`, `inf`
67
+ // and an exponent too), or a finite number.
68
+ const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
69
+
70
+ const toDecimal128 = (value) => {
71
+ if (typeof value === 'number') {
72
+ return Number.isFinite(value) ? driver.Decimal128.fromString(String(value)) : value;
73
+ }
74
+ return typeof value === 'string' && DECIMAL.test(value)
75
+ ? driver.Decimal128.fromString(value)
76
+ : value;
77
+ };
78
+
79
+ // Text of the base64 shape only: the decoder of the driver reads anything,
80
+ // and the empty string is never converted.
81
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
82
+
83
+ const toBinary = (value) =>
84
+ typeof value === 'string' && value.length % 4 === 0 && BASE64.test(value)
85
+ ? driver.Binary.createFromBase64(value)
86
+ : value;
87
+
88
+ // Takes the module of the driver (`require('mongodb')`, which carries the
89
+ // bson it was built with) or of bson, and installs the converters of the
90
+ // BSON types into the coercion of `./coerce`: the one of a type the module
91
+ // cannot build (a slim build without `Decimal128` or `Binary`) is not
92
+ // installed, so that such a value is reported by the check rather than
93
+ // lost in a converter that throws. Once: another module after the first is
94
+ // an error, since values of the first are in the program.
95
+ const register = (options) => {
96
+ const bson = options === null || typeof options !== 'object' ? undefined : options.bson;
97
+ const valid = bson !== null && typeof bson === 'object' && typeof bson.ObjectId === 'function';
98
+ if (!valid) {
99
+ throw invalidOption('bson', 'the module of the mongodb driver or of bson', typeof bson);
100
+ }
101
+ if (driver !== null && driver !== bson) {
102
+ throw invalidOption('bson', 'the module registered before', 'another one');
103
+ }
104
+ const converters = { objectId: toObjectId };
105
+ if (typeof bson.Decimal128?.fromString === 'function') converters.decimal128 = toDecimal128;
106
+ if (typeof bson.Binary?.createFromBase64 === 'function') converters.binary = toBinary;
107
+ driver = bson;
108
+ coercion(converters);
109
+ };
110
+
111
+ // The id field a stored kind adds, which a document holds as `_id`, unless
112
+ // the schema has an `_id` of its own.
113
+ const idOf = (schema) => {
114
+ const id = idFieldOf(schema);
115
+ return id === null || ID in schema.fields ? null : id;
116
+ };
117
+
118
+ module.exports = { ID, HEX, types, register, driverOf, idOf, isObjectId };