@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.
@@ -0,0 +1,258 @@
1
+ // An update of MongoDB against a schema: the fields its dotted paths name
2
+ // (`'address.city'`, `'items.$.qty'`), the values its operators set, push or
3
+ // add to. What depends on the document stored (a length after a `$push`, a
4
+ // bound after an `$inc`, a parent a dotted `$set` creates) is the
5
+ // collection validator's to check; a union, `any` and `json` are not
6
+ // entered. A deep partial schema is not the shape of an update: `$set`
7
+ // replaces what a path names whole, and names nested fields by their paths.
8
+ const { hasBrand, define, RUN } = require('../util.js');
9
+ const { isStruct } = require('../struct.js');
10
+ const { embeds } = require('../prototypes/reference.js');
11
+ const { infoOf, apply, SERIALIZE } = require('../codec.js');
12
+ const { createContext } = require('../context.js');
13
+ const { issues, finalize } = require('../issues.js');
14
+ const { ValidationResult } = require('../result.js');
15
+ const { baseTypeOf } = require('../types.js');
16
+ const { invalidTarget } = require('../errors.js');
17
+ const { ID: KEY, idOf } = require('./bson.js');
18
+ const { SHAPES, walk, idValue, stateOf, listOf } = require('./document.js');
19
+
20
+ const { NESTED, LIST, KEYED, TUPLE, REFERENCE } = SHAPES;
21
+
22
+ // A place an update is not checked at: a union, any, json.
23
+ const LOOSE = Symbol('loose');
24
+ // An element of a list of ids: a string.
25
+ const ID = Symbol('id');
26
+ // A part a node does not have (an element of a string, a field of an id):
27
+ // the path is malformed whatever the policy for unknown keys says, which
28
+ // decides `null`, a key a struct does not have.
29
+ const NONE = Symbol('none');
30
+ // A path through more embedded records than `maxDepth`.
31
+ const DEEP = Symbol('deep');
32
+
33
+ const ELEMENT = /^(?:\d+|\$|\$\[\w*\])$/;
34
+ const INDEX = /^\d+$/;
35
+
36
+ // The operators of the values a path is set to, of the lists it adds to or
37
+ // takes from, and every operator of an update the subpath reads.
38
+ const VALUES = ['$set', '$setOnInsert', '$min', '$max'];
39
+ const LISTS = ['$push', '$addToSet', '$pull', '$pullAll'];
40
+ const OPERATORS = [...VALUES, ...LISTS, '$unset', '$inc', '$mul', '$currentDate', '$pop'];
41
+
42
+ // The type a field is of, through the aliases of custom types.
43
+ const baseOf = (field) => baseTypeOf(field).type;
44
+
45
+ // The record of a reference where it is embedded, else null.
46
+ const targetOf = (node, references) => {
47
+ const target = node.root.findReference(node.one || node.many);
48
+ return target !== null && embeds(target, node.embed, references) ? target : null;
49
+ };
50
+
51
+ // What one segment of a path names from a node: the field of a struct, the
52
+ // element of a list (an index, `$`, `$[]`, `$[name]`) or of a tuple, the
53
+ // value of a dictionary, a field of the record a reference embeds; null for
54
+ // a key a struct does not have, NONE for a part a node cannot have.
55
+ const step = (node, segment, references) => {
56
+ if (hasBrand(node, 'Schema')) return step(node.fields, segment, references);
57
+ if (isStruct(node)) return hasBrand(node[segment], 'Type') ? node[segment] : null;
58
+ const { shape } = infoOf(node);
59
+ if (shape === NESTED) return step(node.schema, segment, references);
60
+ if (shape === LIST) return ELEMENT.test(segment) ? node.value : NONE;
61
+ if (shape === KEYED) return node.value;
62
+ if (shape === TUPLE) {
63
+ if (INDEX.test(segment)) return node.value[Number(segment)] ?? NONE;
64
+ return ELEMENT.test(segment) ? LOOSE : NONE;
65
+ }
66
+ if (shape === REFERENCE) {
67
+ const target = targetOf(node, references);
68
+ // An id has no parts; an element of a list of ids is an id.
69
+ if (node.one) return target === null ? NONE : step(target, segment, references);
70
+ if (!ELEMENT.test(segment)) return NONE;
71
+ return target === null ? ID : target;
72
+ }
73
+ const base = baseOf(node);
74
+ return base === 'union' || base === 'any' || base === 'unknown' || base === 'json' ? LOOSE : NONE;
75
+ };
76
+
77
+ // The node a path names, or null, NONE, LOOSE or DEEP: the records a path
78
+ // goes through are counted as the check counts the records it enters.
79
+ const resolve = (target, segments, references, maxDepth) => {
80
+ let node = target;
81
+ let depth = 0;
82
+ for (let index = 0; index < segments.length && node !== LOOSE; index += 1) {
83
+ if (node === ID) return NONE;
84
+ if (hasBrand(node, 'Type') && infoOf(node).shape === REFERENCE) {
85
+ depth += 1;
86
+ if (depth > maxDepth) return DEEP;
87
+ }
88
+ node = step(node, segments[index], references);
89
+ if (node === null || node === NONE) return node;
90
+ }
91
+ return node;
92
+ };
93
+
94
+ // The element a `$push` or a `$addToSet` adds to the field, or null when it
95
+ // is no list.
96
+ const elementOf = (node, references) => {
97
+ if (typeof node === 'symbol' || !hasBrand(node, 'Type')) return null;
98
+ const { shape } = infoOf(node);
99
+ if (shape === LIST) return node.value;
100
+ if (shape !== REFERENCE || !node.many) return null;
101
+ return targetOf(node, references) ?? ID;
102
+ };
103
+
104
+ // The values a list operator carries: one, or the list of `$each`.
105
+ const itemsOf = (value) =>
106
+ value !== null && typeof value === 'object' && Array.isArray(value.$each) ? value.$each : [value];
107
+
108
+ const checkAt = (node, value, context, key) => {
109
+ if (node === ID) {
110
+ if (typeof value !== 'string') issues.type(context, 'string', value, key);
111
+ } else if (hasBrand(node, 'Schema')) node[RUN](value, context, key);
112
+ else node.check(value, context, key);
113
+ };
114
+
115
+ // An operand of `$inc` or `$mul`: a number for a field of numbers (a whole
116
+ // one for an integer, a bigint for a bigint), never a field of another type;
117
+ // the issue names what the operator takes, not the type of the field.
118
+ const checkStep = (node, value, context, key) => {
119
+ const base = hasBrand(node, 'Type') ? baseOf(node) : '';
120
+ const fits =
121
+ base === 'bigint'
122
+ ? typeof value === 'bigint'
123
+ : typeof value === 'number' &&
124
+ (base === 'number' || (base === 'integer' && Number.isInteger(value)));
125
+ if (!fits) {
126
+ const expected = base === 'bigint' || base === 'integer' ? base : 'number';
127
+ issues.type(context, expected, value, key);
128
+ }
129
+ };
130
+
131
+ const checkOperation = (operator, node, value, context, key) => {
132
+ if (VALUES.includes(operator)) checkAt(node, value, context, key);
133
+ else if (operator === '$unset') {
134
+ if (hasBrand(node, 'Type') && node.required) issues.required(context, key);
135
+ } else if (operator === '$inc' || operator === '$mul') checkStep(node, value, context, key);
136
+ else if (operator === '$currentDate') checkAt(node, new Date(), context, key);
137
+ else if (operator === '$push' || operator === '$addToSet') {
138
+ const element = elementOf(node, context.references);
139
+ if (element === null) issues.type(context, 'array', value, key);
140
+ else for (const item of itemsOf(value)) checkAt(element, item, context, key);
141
+ }
142
+ };
143
+
144
+ const segmentOf = (segment) => (INDEX.test(segment) ? Number(segment) : segment);
145
+
146
+ // One path of an operator: the parents on the path of the context, the
147
+ // field it names checked by what the operator does. The id of a stored
148
+ // record (its field, or the `_id` of the document it is written to) is set
149
+ // by an insert only; a path with an empty segment, or into a part a node
150
+ // cannot have, names nothing whatever the policy for unknown keys says.
151
+ const checkPath = (target, id, operator, path, value, context) => {
152
+ const segments = path.split('.');
153
+ const last = segments.length - 1;
154
+ for (let index = 0; index < last; index += 1) context.path.push(segmentOf(segments[index]));
155
+ const key = segmentOf(segments[last]);
156
+ const first = segments[0];
157
+ const immutable =
158
+ (first === id || (first === KEY && !(KEY in target.fields))) && operator !== '$setOnInsert';
159
+ const malformed = immutable || segments.includes('');
160
+ const node = malformed ? NONE : resolve(target, segments, context.references, context.maxDepth);
161
+ if (node === DEEP) issues.depth(context, context.maxDepth, key);
162
+ else if (node === NONE || (node === null && context.unknown === 'reject')) {
163
+ issues.unexpected(context, [segments[last]]);
164
+ } else if (node !== null && node !== LOOSE) checkOperation(operator, node, value, context, key);
165
+ context.path.length -= last;
166
+ };
167
+
168
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
169
+
170
+ const sourceOf = (target, update) => {
171
+ if (!hasBrand(target, 'Schema') || !isStruct(target.fields)) {
172
+ throw invalidTarget('A Schema of a struct is expected');
173
+ }
174
+ if (!isObject(update)) throw invalidTarget('An update is an object of operators');
175
+ };
176
+
177
+ // The issues of an update against the schema, as a ValidationResult: the
178
+ // options of check (`unknown` decides what a path the schema does not have
179
+ // is, `references` which records are entered, `maxErrors`, `messages`,
180
+ // `root`). An operator the subpath does not know, or that has no object of
181
+ // paths, is one `unexpected` issue at the root.
182
+ const checkUpdate = (target, update, options) => {
183
+ sourceOf(target, update);
184
+ const context = createContext(options, target.name, target.unknown);
185
+ const id = idOf(target);
186
+ const unknown = [];
187
+ for (const operator of Object.keys(update)) {
188
+ const operand = update[operator];
189
+ if (!OPERATORS.includes(operator) || !isObject(operand)) {
190
+ unknown.push(operator);
191
+ continue;
192
+ }
193
+ for (const path of Object.keys(operand)) {
194
+ if (context.count >= context.limit) break;
195
+ checkPath(target, id, operator, path, operand[path], context);
196
+ }
197
+ }
198
+ if (unknown.length > 0 && context.count < context.limit) issues.unexpected(context, unknown);
199
+ finalize(context.issues, context.messages);
200
+ return new ValidationResult(context);
201
+ };
202
+
203
+ // A value of an update as the document holds it: its serializers run, its
204
+ // ids made ObjectIds.
205
+ const valueOf = (state, context, node, value) => {
206
+ if (node === ID) return idValue(state, value);
207
+ const serialized = apply(infoOf(node), node, value, context, undefined, SERIALIZE, SERIALIZE);
208
+ return walk(state, node, serialized);
209
+ };
210
+
211
+ const operandOf = (state, context, operator, node, value) => {
212
+ if (VALUES.includes(operator)) return valueOf(state, context, node, value);
213
+ if (!LISTS.includes(operator)) return value;
214
+ const element = elementOf(node, state.references);
215
+ if (element === null) return value;
216
+ const each = (item) => valueOf(state, context, element, item);
217
+ if (operator === '$pullAll') return Array.isArray(value) ? listOf(value, each) : value;
218
+ if (isObject(value)) {
219
+ if (!Array.isArray(value.$each)) return value;
220
+ return { ...value, $each: listOf(value.$each, each) };
221
+ }
222
+ return each(value);
223
+ };
224
+
225
+ // The update as the database takes it: the values the schema knows
226
+ // serialized and their ids made ObjectIds, the id of the record as `_id`.
227
+ // What `checkUpdate` would reject is not checked here: check first.
228
+ const toUpdate = (target, update, options) => {
229
+ sourceOf(target, update);
230
+ const state = stateOf(target, options, true);
231
+ const context = createContext({ references: state.references }, target.name, target.unknown);
232
+ const id = idOf(target);
233
+ const out = {};
234
+ for (const operator of Object.keys(update)) {
235
+ const operand = update[operator];
236
+ if (!isObject(operand)) {
237
+ define(out, operator, operand);
238
+ continue;
239
+ }
240
+ const next = {};
241
+ for (const path of Object.keys(operand)) {
242
+ const segments = path.split('.');
243
+ const node = resolve(target, segments, state.references, state.maxDepth);
244
+ let value = operand[path];
245
+ if (segments[0] === id) {
246
+ segments[0] = KEY;
247
+ if (segments.length === 1) value = idValue(state, value);
248
+ } else if (node !== null && (node === ID || typeof node !== 'symbol')) {
249
+ value = operandOf(state, context, operator, node, value);
250
+ }
251
+ define(next, segments.join('.'), value);
252
+ }
253
+ define(out, operator, next);
254
+ }
255
+ return out;
256
+ };
257
+
258
+ module.exports = { checkUpdate, toUpdate };
@@ -11,8 +11,12 @@ const RESERVED = new Set(['__proto__', 'prototype', 'check', 'checkType', 'compi
11
11
  const reservedKey = (key) =>
12
12
  new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
13
13
 
14
- const invalidNullable = () =>
15
- new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "nullable" needs a boolean');
14
+ // The options of a field that are flags: `nullable` (null in place of a
15
+ // value) and `coerce` (whether parse converts the input of its subtree).
16
+ const FLAGS = ['nullable', 'coerce'];
17
+
18
+ const invalidFlag = (key) =>
19
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a boolean`);
16
20
 
17
21
  const invalidCodec = (key) =>
18
22
  new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
@@ -86,7 +90,9 @@ class AbstractType {
86
90
  }
87
91
  this.construct(def, preprocessor);
88
92
  if (this.type) this.root.references.add(this.type);
89
- if (this.nullable !== undefined && typeof this.nullable !== 'boolean') throw invalidNullable();
93
+ for (const key of FLAGS) {
94
+ if (this[key] !== undefined && typeof this[key] !== 'boolean') throw invalidFlag(key);
95
+ }
90
96
  checkCodecs(this);
91
97
  // The rule checks that apply to this field, compiled once: a field
92
98
  // without rules is its type check alone, and check is the hot path.
package/src/schema.js CHANGED
@@ -14,6 +14,7 @@ const {
14
14
  PREPARE,
15
15
  FINISH,
16
16
  SERIALIZE,
17
+ COERCE,
17
18
  infoOf,
18
19
  apply,
19
20
  looped,
@@ -90,6 +91,11 @@ class Schema extends SchemaMetadata {
90
91
  // What the passes of parse and serialize know about the schema, on first use.
91
92
  #codec = null;
92
93
 
94
+ // Whether parse coerces the input unless the call says otherwise: the
95
+ // `coerce` of the kind metadata, read once (an own property would shadow
96
+ // the method the `./coerce` subpath installs).
97
+ #coerce = false;
98
+
93
99
  static from(source, namespaces) {
94
100
  return new Schema('', source, namespaces);
95
101
  }
@@ -129,6 +135,7 @@ class Schema extends SchemaMetadata {
129
135
  this.fields = createStruct(combined, preprocessor);
130
136
  }
131
137
  this.#tracked = isSchemaType && this.relations.size > 0;
138
+ this.#coerce = Object.hasOwn(this.custom, 'coerce') && this.custom.coerce === true;
132
139
  this[RUN] = compileSchema(this);
133
140
  const hook = Schema[HOOK];
134
141
  if (hook !== undefined) hook(this);
@@ -227,46 +234,52 @@ class Schema extends SchemaMetadata {
227
234
  return resultOf(context);
228
235
  }
229
236
 
230
- #pass(phase, source, context) {
237
+ #pass(phase, source, context, extra) {
231
238
  if (this.#codec === null) this.#codec = infoOf(this);
232
- return apply(this.#codec, this, source, context, undefined, phase, wantOf(phase, context));
239
+ const want = wantOf(phase, context) | extra;
240
+ return apply(this.#codec, this, source, context, undefined, phase, want);
233
241
  }
234
242
 
235
- // The defaults of the schema over a value, before its check; the objects
236
- // met on the way down are not the check's, and a value that loops through
237
- // its references is checked as it was given.
238
- #prepare(source, context) {
239
- const prepared = this.#pass(PREPARE, source, context);
243
+ // Validates a value and builds the value of the program from it: the input
244
+ // coerced (when the call, else the schema, asks for it) and the defaults
245
+ // filled in, the check, and on a valid value `unknown: 'strip'`, the
246
+ // decoders of its fields (the parts of a value before the value) and the
247
+ // schema's own `parse`. `{ valid, value, issues }`: the value is undefined
248
+ // when invalid, and the value given when there was nothing to apply; the
249
+ // value given is never written to. The objects met before the check are
250
+ // not the check's, and a value that loops through its references is
251
+ // checked as it was given. The pass before the check is written out here
252
+ // and in parseAsync, not in a method of its own: with coercion such a
253
+ // method no longer fit the bytecode V8 inlines into parse, and the call
254
+ // cost the JIT backend 13%.
255
+ parse(source, options) {
256
+ const context = createContext(options, this.name, this.unknown, true);
257
+ const own = options === undefined ? undefined : options.coerce;
258
+ const coerce = own === undefined ? this.#coerce : own;
259
+ const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
240
260
  const value = looped(context) ? source : prepared;
241
261
  context.seen = null;
242
262
  if (this.#tracked) context.source = value;
243
- return value;
244
- }
245
-
246
- // Validates a value and builds the value of the program from it: the
247
- // defaults fill the missing keys, the check runs, and a valid value goes
248
- // through `unknown: 'strip'`, the decoders of its fields (the parts of a
249
- // value before the value) and the schema's own `parse`. `{ valid, value,
250
- // issues }`: the value is undefined when invalid, and the value given when
251
- // there was nothing to apply; the value given is never written to.
252
- parse(source, options) {
253
- const context = createContext(options, this.name, this.unknown, true);
254
- const value = this.#prepare(source, context);
255
263
  this[RUN](value, context);
256
- const output = context.count === 0 ? this.#pass(FINISH, value, context) : undefined;
264
+ const output = context.count === 0 ? this.#pass(FINISH, value, context, 0) : undefined;
257
265
  return parsed(context, output);
258
266
  }
259
267
 
260
268
  async parseAsync(source, options) {
261
269
  const context = createContext(options, this.name, this.unknown, true);
262
270
  context.async = [];
263
- const value = this.#prepare(source, context);
271
+ const own = options === undefined ? undefined : options.coerce;
272
+ const coerce = own === undefined ? this.#coerce : own;
273
+ const prepared = this.#pass(PREPARE, source, context, coerce === true ? COERCE : 0);
274
+ const value = looped(context) ? source : prepared;
275
+ context.seen = null;
276
+ if (this.#tracked) context.source = value;
264
277
  walkAsync(this, value, context);
265
278
  if (context.async.length > 0) await settle(context);
266
279
  let output;
267
280
  if (context.count === 0) {
268
281
  // Only a promise of the pass is awaited: a thenable in the value is data.
269
- output = this.#pass(FINISH, value, context);
282
+ output = this.#pass(FINISH, value, context, 0);
270
283
  if (output instanceof Promise) output = (await output).value;
271
284
  }
272
285
  return parsed(context, output);
@@ -277,7 +290,7 @@ class Schema extends SchemaMetadata {
277
290
  // `options.check` the verdict of `check` over the result as well.
278
291
  serialize(source, options) {
279
292
  const context = createContext(options, this.name, this.unknown);
280
- const value = this.#pass(SERIALIZE, source, context);
293
+ const value = this.#pass(SERIALIZE, source, context, 0);
281
294
  if (options === undefined || options.check !== true) return { value };
282
295
  context.seen = null;
283
296
  if (this.#tracked) context.source = value;
package/src/types.js CHANGED
@@ -137,4 +137,23 @@ const typeFactory = (customTypes, registry = TYPES) => {
137
137
  return registry;
138
138
  };
139
139
 
140
- module.exports = { TYPES, createRegistry, readsAsStruct, typeFactory };
140
+ // The type a field validates as: its own class, or the one its alias chain
141
+ // ends in (`{ money: { js: 'number' } }` validates as a number, and so does
142
+ // `{ cents: { js: 'money' } }`); a custom type with a check of its own ends
143
+ // the chain with `source.js` undefined, and a name the registry cannot
144
+ // resolve (a namespace detached since) ends it where it stands. Read by the
145
+ // generators, the samples and the mongodb subpath, which look at `.type` and
146
+ // `.source` of what comes back.
147
+ const baseTypeOf = (field) => {
148
+ const { types } = field.root;
149
+ let Type = field.constructor;
150
+ for (;;) {
151
+ const js = Type.source?.js;
152
+ if (js === undefined) return Type;
153
+ const next = types[js];
154
+ if (next === undefined) return Type;
155
+ Type = next;
156
+ }
157
+ };
158
+
159
+ module.exports = { TYPES, createRegistry, readsAsStruct, typeFactory, baseTypeOf };