@alexify/metaschema 0.0.0-stage → 2.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.
@@ -0,0 +1,57 @@
1
+ // Ukrainian messages, with the same table as ./en.js. Pass the table to a
2
+ // check as `messages`: `schema.check(value, { messages: uk })`.
3
+ const { shorten } = require('../util.js');
4
+
5
+ const field = (path) => `Поле "${path}"`;
6
+
7
+ const required = () => 'є обовʼязковим';
8
+
9
+ const type = ({ expected, key }) =>
10
+ key === undefined ? `не відповідає типу: ${expected}` : `ключі мають бути типу ${expected}`;
11
+
12
+ const list = (keys) => {
13
+ let text = shorten(keys[0]);
14
+ for (let index = 1; index < keys.length; index += 1) text += `, ${shorten(keys[index])}`;
15
+ return text;
16
+ };
17
+
18
+ const unexpected = ({ keys }) => `має неочікувані ключі: ${list(keys)}`;
19
+
20
+ const enumeration = ({ values }) => `значення не входить до переліку: ${values.join(', ')}`;
21
+
22
+ const length = ({ min, actual }) =>
23
+ min !== undefined && actual < min ? 'значення закоротке' : 'перевищує максимальну довжину';
24
+
25
+ const range = ({ min, max, actual }) =>
26
+ min !== undefined && actual < min ? `менше за ${min}` : `більше за ${max}`;
27
+
28
+ const pattern = ({ pattern: source }) => `не відповідає шаблону ${source}`;
29
+
30
+ const union = ({ expected, discriminator }) =>
31
+ discriminator === undefined
32
+ ? `не відповідає жодному з: ${expected.join(', ')}`
33
+ : `не є одним із: ${expected.join(', ')}`;
34
+
35
+ const reference = ({ entity }) => `сутність "${entity}" не знайдено`;
36
+
37
+ const circular = () => 'є циклічним посиланням';
38
+
39
+ const exception = ({ error }) => `перевірка завершилась помилкою ${error}`;
40
+
41
+ const custom = () => 'помилка перевірки';
42
+
43
+ module.exports = {
44
+ field,
45
+ required,
46
+ type,
47
+ unexpected,
48
+ enum: enumeration,
49
+ length,
50
+ range,
51
+ pattern,
52
+ union,
53
+ reference,
54
+ circular,
55
+ exception,
56
+ custom,
57
+ };
@@ -0,0 +1,117 @@
1
+ const { getKindMetadata } = require('./kinds.js');
2
+ const { ValidationResult } = require('./result.js');
3
+ const { SchemaDefinitionError } = require('./errors.js');
4
+ const OPTIONS = ['validate', 'parse', 'serialize', 'format'];
5
+ const METADATA_COLLECTIONS = ['indexes', 'options'];
6
+ const UNKNOWN = ['reject', 'ignore'];
7
+
8
+ // The unknown-keys policy of a schema is the default of its `check`, so a
9
+ // value with keys the schema does not have is rejected or ignored without
10
+ // an option on every call; the option of a call still wins.
11
+ const unknownOf = (unknown) => {
12
+ if (unknown === undefined) return 'reject';
13
+ if (!UNKNOWN.includes(unknown)) {
14
+ const reason = `Schema metadata "unknown" must be "reject" or "ignore", got ${JSON.stringify(unknown)}`;
15
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
16
+ }
17
+ return unknown;
18
+ };
19
+
20
+ class Options {
21
+ constructor() {
22
+ this.validate = null;
23
+ this.format = null;
24
+ this.parse = null;
25
+ this.serialize = null;
26
+ }
27
+
28
+ extract(key, field) {
29
+ const isFn = typeof field === 'function';
30
+ const isOption = OPTIONS.includes(key) && isFn;
31
+ if (isOption) this[key] = field;
32
+ return isOption;
33
+ }
34
+ }
35
+
36
+ class Indexes {
37
+ // Index definitions (`index`, `primary`, `unique` arrays) are taken out of the
38
+ // fields; a `many` relation is recorded here as well but stays a field, so
39
+ // the method reports only whether the entry was taken.
40
+ extract(key, field) {
41
+ if (field === null || typeof field !== 'object') return false;
42
+ const { index, primary, unique, many } = field;
43
+ const isIndex = Array.isArray(index || primary || unique);
44
+ if (isIndex || many) this[key] = field;
45
+ return isIndex;
46
+ }
47
+ }
48
+
49
+ class SchemaMetadata {
50
+ constructor() {
51
+ this.kind = 'struct';
52
+ this.scope = 'local';
53
+ this.store = 'memory';
54
+ this.allow = 'write';
55
+ this.parent = '';
56
+ this.unknown = 'reject';
57
+ this.indexes = new Indexes();
58
+ this.options = new Options();
59
+ this.custom = {};
60
+ this.references = new Set();
61
+ this.relations = new Set();
62
+ }
63
+
64
+ #setMany(values) {
65
+ const { kind, scope, store, allow, parent, unknown, ...custom } = values;
66
+ this.kind = kind || this.kind;
67
+ this.scope = scope || this.scope;
68
+ this.store = store || this.store;
69
+ this.allow = allow || this.allow;
70
+ this.parent = parent || this.parent;
71
+ this.unknown = unknownOf(unknown);
72
+ this.custom = custom;
73
+ }
74
+
75
+ updateFromSchema({ references = [], relations = [] }) {
76
+ for (const ref of references) this.references.add(ref);
77
+ for (const rel of relations) this.relations.add(rel);
78
+ }
79
+
80
+ updateFromKind({ kind, meta, root }) {
81
+ const { defs, metadata } = getKindMetadata(kind, meta, root);
82
+ this.#setMany(metadata);
83
+ return defs;
84
+ }
85
+
86
+ extractMetadata(defs) {
87
+ const fields = Object.create(null);
88
+ for (const pair of Object.entries(defs)) {
89
+ const key = pair[0];
90
+ const field = pair[1];
91
+ let extracted = false;
92
+ for (const collection of METADATA_COLLECTIONS) {
93
+ const taken = this[collection].extract(key, field);
94
+ if (taken) extracted = true;
95
+ }
96
+ if (!extracted) fields[key] = field;
97
+ }
98
+ return fields;
99
+ }
100
+
101
+ // Runs only the schema-level validate function, as a result of its own.
102
+ validate(value, path = '') {
103
+ if (!this.options.validate) return null;
104
+ const result = new ValidationResult();
105
+ try {
106
+ return result.add(this.options.validate(value, path));
107
+ } catch (error) {
108
+ return result.add({
109
+ code: 'exception',
110
+ message: `validation failed ${error}`,
111
+ params: { error },
112
+ });
113
+ }
114
+ }
115
+ }
116
+
117
+ module.exports = { ValidationResult, SchemaMetadata };
@@ -0,0 +1,23 @@
1
+ // Copied from metautil v5.5.2 (lib/strings.js, lib/objects.js)
2
+ // https://github.com/metarhia/metautil — MIT, Copyright (c) 2017-2026 Metarhia contributors
3
+
4
+ const inRange = (x, min, max) => x >= min && x <= max;
5
+
6
+ const isFirstUpper = (s) => !!s && inRange(s[0], 'A', 'Z');
7
+
8
+ const isFirstLower = (s) => !!s && inRange(s[0], 'a', 'z');
9
+
10
+ const isFirstLetter = (s) => isFirstUpper(s) || isFirstLower(s);
11
+
12
+ const toLowerCamel = (s) => s.charAt(0).toLowerCase() + s.slice(1);
13
+
14
+ const firstKey = (obj) => Object.keys(obj).find(isFirstLetter);
15
+
16
+ module.exports = {
17
+ inRange,
18
+ isFirstUpper,
19
+ isFirstLower,
20
+ isFirstLetter,
21
+ toLowerCamel,
22
+ firstKey,
23
+ };
package/src/model.js ADDED
@@ -0,0 +1,108 @@
1
+ const { firstKey } = require('./metautil.js');
2
+
3
+ const { Schema } = require('./schema.js');
4
+ const { TYPES, createRegistry, typeFactory } = require('./types.js');
5
+ const { SchemaDefinitionError } = require('./errors.js');
6
+ const { warning } = require('./lint.js');
7
+
8
+ const REGISTRIES = ['shared', 'isolated'];
9
+
10
+ const registryFor = (options) => {
11
+ const { registry = 'shared' } = options;
12
+ if (!REGISTRIES.includes(registry)) {
13
+ const reason = `Model option "registry" must be "shared" or "isolated", got ${JSON.stringify(registry)}`;
14
+ throw new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
15
+ }
16
+ return registry === 'isolated' ? createRegistry() : TYPES;
17
+ };
18
+
19
+ class Model {
20
+ // The model's own warnings (the cycles met while ordering), found while
21
+ // building; the rest comes from the entities on first use.
22
+ #cycles = [];
23
+ #warnings = null;
24
+
25
+ constructor(types, entities, database = null, options = {}) {
26
+ this.types = typeFactory(types, registryFor(options));
27
+ this.entities = new Map();
28
+ this.database = database;
29
+ this.order = new Set();
30
+ const projections = [];
31
+ for (const pair of entities) {
32
+ const name = pair[0];
33
+ const entity = pair[1];
34
+ const first = firstKey(entity);
35
+ const isProjection = first === 'Projection';
36
+ if (isProjection) {
37
+ projections.push({ name, entity });
38
+ continue;
39
+ }
40
+ const schema = new Schema(name, entity, [this]);
41
+ this.entities.set(name, schema);
42
+ }
43
+ for (const projection of projections) {
44
+ const { name, entity } = projection;
45
+ const schema = new Schema(name, entity, [this]);
46
+ this.entities.set(name, schema);
47
+ }
48
+ this.#preprocess();
49
+ }
50
+
51
+ // The lint warnings of every entity, the references and types they cannot
52
+ // resolve, and the recursive dependencies, as `Warning [code]: text`.
53
+ get warnings() {
54
+ if (this.#warnings !== null) return this.#warnings;
55
+ const warnings = [];
56
+ for (const pair of this.entities) {
57
+ const name = pair[0];
58
+ const entity = pair[1];
59
+ if (name.startsWith('.')) continue;
60
+ warnings.push(...entity.warnings, ...entity.checkConsistency());
61
+ }
62
+ warnings.push(...this.#cycles);
63
+ this.#warnings = warnings;
64
+ return warnings;
65
+ }
66
+
67
+ #preprocess() {
68
+ const { entities, order } = this;
69
+ if (entities.has('Identifier')) order.add('Identifier');
70
+ for (const name of entities.keys()) {
71
+ const isMeta = name.startsWith('.');
72
+ if (!isMeta) this.#reorderEntity(name, new Set());
73
+ }
74
+ }
75
+
76
+ // Depth-first ordering: an entity is added after everything it references.
77
+ // `visiting` holds the current path, so a reference back into it is a cycle
78
+ // of any length, not only one through the entity the walk started from.
79
+ #reorderEntity(name, visiting) {
80
+ const entity = this.entities.get(name);
81
+ if (!entity || this.order.has(name)) return;
82
+ visiting.add(name);
83
+ for (const ref of entity.references) {
84
+ if (ref === name) continue;
85
+ if (visiting.has(ref)) {
86
+ this.#cycles.push(
87
+ warning('recursive-reference', `"${name}" depends on "${ref}" recursively`),
88
+ );
89
+ continue;
90
+ }
91
+ this.#reorderEntity(ref, visiting);
92
+ }
93
+ visiting.delete(name);
94
+ this.order.add(name);
95
+ }
96
+
97
+ get dts() {
98
+ const { entities, order } = this;
99
+ const dts = [];
100
+ for (const name of order) {
101
+ const schema = entities.get(name);
102
+ dts.push(schema.toInterface());
103
+ }
104
+ return `${dts.join('\n\n')}\n`;
105
+ }
106
+ }
107
+
108
+ module.exports = { Model };
@@ -0,0 +1,133 @@
1
+ const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
2
+
3
+ const { hasBrand, formatters } = require('./util.js');
4
+ const { SchemaDefinitionError } = require('./errors.js');
5
+
6
+ // The first key of an object decides what it is: a Schema or a built field is
7
+ // used as it is, a capitalized key is a kind, `type` is the long form, a type
8
+ // name is that type's shorthand, and anything else is a nested struct.
9
+ const PARSERS = {
10
+ string: ['stringShorthand'],
11
+ object: [
12
+ 'schemaInstance',
13
+ 'typeInstance',
14
+ 'schemaWithKind',
15
+ 'typeLongForm',
16
+ 'typeShorthand',
17
+ 'kindlessSchema',
18
+ ],
19
+ function: ['functionField'],
20
+ array: ['tupleShorthand'],
21
+ };
22
+
23
+ const sourceType = (src) => {
24
+ if (src === null) return 'null';
25
+ if (Array.isArray(src)) return 'array';
26
+ return typeof src;
27
+ };
28
+
29
+ const invalid = (source, srcType = sourceType(source)) =>
30
+ new SchemaDefinitionError(
31
+ 'ERR_INVALID_DEFINITION',
32
+ `Invalid definition: "${source}" of type ${srcType}`,
33
+ );
34
+
35
+ class Preprocessor {
36
+ constructor(root) {
37
+ this.Schema = root.constructor;
38
+ this.root = root;
39
+ this.types = root.types;
40
+ }
41
+
42
+ // The first key of an object is read once here and handed to the parsers
43
+ // that look at it.
44
+ parse(source) {
45
+ const srcType = sourceType(source);
46
+ const parsers = PARSERS[srcType];
47
+ if (parsers) {
48
+ const first = srcType === 'object' ? firstKey(source) : undefined;
49
+ for (const name of parsers) {
50
+ const result = this[name](source, first);
51
+ if (result) return result;
52
+ }
53
+ }
54
+ throw invalid(source, srcType);
55
+ }
56
+
57
+ // A Schema instance as a field: `{ schema: instance }` and the long form go
58
+ // through the type parsers, and the schema type accepts the instance there.
59
+ schemaInstance(source) {
60
+ if (!hasBrand(source, 'Schema')) return null;
61
+ const defs = { schema: source };
62
+ return { Type: this.types.schema, defs };
63
+ }
64
+
65
+ // A field already built (a projection copies the fields of its parent) is
66
+ // parsed again from its own definition, so the copy belongs to the schema
67
+ // that holds it.
68
+ typeInstance(source) {
69
+ if (!hasBrand(source, 'Type')) return null;
70
+ return this.typeLongForm({ type: source.type, ...source.toJSON() }, 'type');
71
+ }
72
+
73
+ stringShorthand(source) {
74
+ return this.typeLongForm({ type: source }, 'type');
75
+ }
76
+
77
+ typeLongForm(source, first) {
78
+ if (first !== 'type') return null;
79
+ if (typeof source.type !== 'string') throw invalid(source.type);
80
+ const { types } = this;
81
+ const parsed = formatters.type(source.type, source.required);
82
+ const { type, required } = parsed;
83
+ if (isFirstUpper(type)) {
84
+ const defs = { one: type, required, ...source };
85
+ return { Type: types.reference, defs };
86
+ }
87
+ if (!types[type]) {
88
+ throw new SchemaDefinitionError('ERR_UNKNOWN_TYPE', `Unknown type "${type}"`);
89
+ }
90
+ const defs = { required, ...source };
91
+ return { Type: types[type], defs };
92
+ }
93
+
94
+ typeShorthand(source, first) {
95
+ const { types } = this;
96
+ const parsed = formatters.key(first, source.required);
97
+ const type = parsed.field;
98
+ const required = parsed.required;
99
+ if (!types[type]) return null;
100
+ const { [first]: def, ...rest } = source;
101
+ const defs = { type, [type]: def, required, ...rest };
102
+ return { Type: types[type], defs };
103
+ }
104
+
105
+ schemaWithKind(source, first) {
106
+ const { types, root } = this;
107
+ if (!isFirstUpper(first)) return null;
108
+ const { [first]: meta, ...fields } = source;
109
+ const kind = toLowerCamel(first);
110
+ const kindMeta = { kind, meta, root };
111
+ const defs = { schema: fields };
112
+ return { Type: types.schema, defs, kindMeta };
113
+ }
114
+
115
+ kindlessSchema(source) {
116
+ const { types } = this;
117
+ const kindMeta = { kind: 'struct' };
118
+ const defs = { schema: source };
119
+ return { Type: types.schema, defs, kindMeta };
120
+ }
121
+
122
+ tupleShorthand(source) {
123
+ const { types } = this;
124
+ const defs = { value: source, required: true };
125
+ return { Type: types.tuple, defs };
126
+ }
127
+
128
+ functionField() {
129
+ return {};
130
+ }
131
+ }
132
+
133
+ module.exports = { Preprocessor };
@@ -0,0 +1,121 @@
1
+ const { BRAND, INSPECT } = require('../util.js');
2
+ const { FORMAT, notApplicable, compileRules } = require('../rules.js');
3
+ const { runValidate, runCheckType } = require('../issues.js');
4
+ const { SchemaDefinitionError } = require('../errors.js');
5
+
6
+ // Keys of a field definition become properties of the field, so a key that
7
+ // names one of its methods (or the prototype itself) would replace it. The
8
+ // methods of the type contract are reserved whether the type has them or not.
9
+ const RESERVED = new Set(['__proto__', 'prototype', 'check', 'checkType', 'compile', 'construct']);
10
+
11
+ const reservedKey = (key) =>
12
+ new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
13
+
14
+ const invalidNullable = () =>
15
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "nullable" needs a boolean');
16
+
17
+ // A nullable field accepts null in place of a value of its type, whatever
18
+ // its rules; `required` still says whether the key must be there.
19
+ const nullable = (inner) => (value, context, key) => {
20
+ if (value === null) return;
21
+ inner(value, context, key);
22
+ };
23
+
24
+ // The check of a field with rules or a validate function: the type check,
25
+ // then the rules, then the validate function. A type failure cancels the
26
+ // rest (a length or a validator makes no sense for a value of another type),
27
+ // and validate runs only on a value that passed everything before it, so it
28
+ // can rely on the type and the rules. A field with neither is its type check
29
+ // alone.
30
+ const withRules = (type, inner, rules) => {
31
+ const { required, validate } = type;
32
+ return (value, context, key) => {
33
+ if (value == null && !required) return;
34
+ const before = context.count;
35
+ inner(value, context, key);
36
+ if (context.count !== before) return;
37
+ for (let index = 0; index < rules.length; index += 1) {
38
+ if (context.count >= context.limit) break;
39
+ rules[index](value, context, key);
40
+ }
41
+ if (validate && context.count === before) {
42
+ const nested = key !== undefined;
43
+ if (nested) context.path.push(key);
44
+ runValidate(type, validate, value, context);
45
+ if (nested) context.path.pop();
46
+ }
47
+ };
48
+ };
49
+
50
+ class AbstractType {
51
+ // The rules the type accepts and the definition keys it reads, by name; a
52
+ // type class sets its own.
53
+ static rules = new Set();
54
+ static options = new Set();
55
+
56
+ // The compiled check of the field: a closure built once from the field,
57
+ // kept out of its definition (toJSON, util.inspect) as a private field.
58
+ #check;
59
+
60
+ constructor(def, preprocessor) {
61
+ this.root = preprocessor.root;
62
+ const { rules } = this.constructor;
63
+ for (const key of Object.keys(def)) {
64
+ const value = def[key];
65
+ if (key === 'type' || key === this.type) continue;
66
+ if (RESERVED.has(key) || typeof this[key] === 'function') throw reservedKey(key);
67
+ const format = FORMAT[key];
68
+ if (format === undefined) {
69
+ this[key] = value;
70
+ continue;
71
+ }
72
+ if (!rules.has(key)) throw notApplicable(key, this.type, rules);
73
+ this[key] = format(value);
74
+ }
75
+ this.construct(def, preprocessor);
76
+ if (this.type) this.root.references.add(this.type);
77
+ if (this.nullable !== undefined && typeof this.nullable !== 'boolean') throw invalidNullable();
78
+ // The rule checks that apply to this field, compiled once: a field
79
+ // without rules is its type check alone, and check is the hot path.
80
+ const checks = compileRules(this, rules);
81
+ const inner = this.compile();
82
+ const plain = checks.length === 0 && !this.validate;
83
+ const check = plain ? inner : withRules(this, inner, checks);
84
+ this.#check = this.nullable === true ? nullable(check) : check;
85
+ }
86
+
87
+ // Records the problems of a value into the context of the current check,
88
+ // under `key` when the field is reached through one.
89
+ get check() {
90
+ return this.#check;
91
+ }
92
+
93
+ // The type check of a field, as a closure built once from the field. A
94
+ // built-in prototype compiles its own; a custom type has a
95
+ // `checkType(value, path)` that returns messages, run through the
96
+ // validator contract.
97
+ compile() {
98
+ const type = this;
99
+ const { required } = this;
100
+ return (value, context, key) => {
101
+ if (value == null && !required) return;
102
+ const nested = key !== undefined;
103
+ if (nested) context.path.push(key);
104
+ runCheckType(type, value, context);
105
+ if (nested) context.path.pop();
106
+ };
107
+ }
108
+
109
+ toJSON() {
110
+ const { root, ...rest } = this;
111
+ return rest;
112
+ }
113
+
114
+ [INSPECT](depth, options, inspect) {
115
+ return inspect(this.toJSON(), options);
116
+ }
117
+ }
118
+
119
+ AbstractType.prototype[BRAND] = 'Type';
120
+
121
+ module.exports = { AbstractType };