@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,146 @@
1
+ const { issues } = require('../issues.js');
2
+
3
+ // Collections iterate their source directly: an object with for...in over
4
+ // its own keys, a Map and a Set through their iterators, an array by index.
5
+ // A collection pushes its own key on the path before its elements and pops
6
+ // it after them; an element is checked with its key or index.
7
+ const object = {
8
+ rules: ['length'],
9
+ options: ['key', 'value', 'length'],
10
+ kind: 'struct',
11
+
12
+ construct(def, prep) {
13
+ const { type } = this;
14
+ const { [type]: short, key, value } = def;
15
+ const pair = short ? Object.entries(short)[0] : [key, value];
16
+ const keyType = pair[0];
17
+ const valueDef = pair[1];
18
+ this.key = keyType;
19
+ const { Type, defs } = prep.parse(valueDef);
20
+ this.value = new Type(defs, prep);
21
+ },
22
+
23
+ compile() {
24
+ const { required, type, key: keyType } = this;
25
+ const { check } = this.value;
26
+ return (value, context, key) => {
27
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
28
+ if (!required && value == null) return;
29
+ issues.type(context, type, value, key);
30
+ return;
31
+ }
32
+ const nested = key !== undefined;
33
+ if (nested) context.path.push(key);
34
+ let count = 0;
35
+ for (const name in value) {
36
+ if (!Object.hasOwn(value, name)) continue;
37
+ if (context.count >= context.limit) break;
38
+ count += 1;
39
+ // oxlint-disable-next-line valid-typeof
40
+ if (typeof name !== keyType) {
41
+ issues.key(context, keyType, name);
42
+ break;
43
+ }
44
+ check(value[name], context, name);
45
+ }
46
+ if (count === 0 && required) issues.required(context);
47
+ if (nested) context.path.pop();
48
+ };
49
+ },
50
+
51
+ isInstance(value) {
52
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
53
+ },
54
+ };
55
+
56
+ const map = {
57
+ ...object,
58
+
59
+ compile() {
60
+ const { required, type, key: keyType } = this;
61
+ const { check } = this.value;
62
+ return (value, context, key) => {
63
+ if (value?.constructor?.name !== 'Map') {
64
+ if (!required && value == null) return;
65
+ issues.type(context, type, value, key);
66
+ return;
67
+ }
68
+ if (value.size === 0) {
69
+ if (required) issues.required(context, key);
70
+ return;
71
+ }
72
+ const nested = key !== undefined;
73
+ if (nested) context.path.push(key);
74
+ for (const pair of value) {
75
+ if (context.count >= context.limit) break;
76
+ const name = pair[0];
77
+ // oxlint-disable-next-line valid-typeof
78
+ if (typeof name !== keyType) {
79
+ issues.key(context, keyType, name);
80
+ break;
81
+ }
82
+ check(pair[1], context, name);
83
+ }
84
+ if (nested) context.path.pop();
85
+ };
86
+ },
87
+
88
+ isInstance(value) {
89
+ return value?.constructor?.name === 'Map';
90
+ },
91
+ };
92
+
93
+ // An array and a Set are walked the same way, by position; only the type
94
+ // test differs.
95
+ const compileList = (type, isList) => {
96
+ const { required } = type;
97
+ const { check } = type.value;
98
+ const name = type.type;
99
+ return (value, context, key) => {
100
+ if (!isList(value)) {
101
+ if (!required && value == null) return;
102
+ issues.type(context, name, value, key);
103
+ return;
104
+ }
105
+ const nested = key !== undefined;
106
+ if (nested) context.path.push(key);
107
+ let index = 0;
108
+ for (const item of value) {
109
+ if (context.count >= context.limit) break;
110
+ check(item, context, index);
111
+ index += 1;
112
+ }
113
+ if (nested) context.path.pop();
114
+ };
115
+ };
116
+
117
+ const array = {
118
+ kind: 'struct',
119
+ rules: ['length'],
120
+ options: ['value', 'length'],
121
+
122
+ construct(def, prep) {
123
+ const { type } = this;
124
+ const source = def[type] || def.value;
125
+ const { Type, defs } = prep.parse(source);
126
+ this.value = new Type(defs, prep);
127
+ },
128
+
129
+ compile() {
130
+ return compileList(this, this.isInstance);
131
+ },
132
+
133
+ isInstance(value) {
134
+ return Array.isArray(value);
135
+ },
136
+ };
137
+
138
+ const set = {
139
+ ...array,
140
+
141
+ isInstance(value) {
142
+ return value?.constructor?.name === 'Set';
143
+ },
144
+ };
145
+
146
+ module.exports = { object, map, array, set };
@@ -0,0 +1,19 @@
1
+ const { issues } = require('../issues.js');
2
+
3
+ const json = {
4
+ kind: 'struct',
5
+ options: [],
6
+
7
+ construct() {},
8
+
9
+ compile() {
10
+ const { required } = this;
11
+ return (value, context, key) => {
12
+ if (value !== null && typeof value === 'object') return;
13
+ if (!required && value == null) return;
14
+ issues.type(context, 'object', value, key);
15
+ };
16
+ },
17
+ };
18
+
19
+ module.exports = { json };
@@ -0,0 +1,99 @@
1
+ const { SchemaDefinitionError } = require('../errors.js');
2
+ const { RUN } = require('../util.js');
3
+ const { issues } = require('../issues.js');
4
+
5
+ const invalidEmbed = () =>
6
+ new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "embed" needs a boolean');
7
+
8
+ // A reference is the one place a schema can recurse (Category.parent is a
9
+ // Category), so it is where a value met again while it is still being
10
+ // checked is a cycle, reported instead of recursed into.
11
+ const runReferenced = (schema, value, context, key) => {
12
+ if (value === null || typeof value !== 'object') {
13
+ schema[RUN](value, context, key);
14
+ return;
15
+ }
16
+ if (context.seen === null) context.seen = new Set();
17
+ const { seen } = context;
18
+ if (seen.has(value)) {
19
+ issues.circular(context, key);
20
+ return;
21
+ }
22
+ seen.add(value);
23
+ schema[RUN](value, context, key);
24
+ seen.delete(value);
25
+ };
26
+
27
+ // Whether a referenced value is the record itself (the graph view) or its
28
+ // id (the storage view): the mode of the check when it says so, otherwise
29
+ // the field's `embed`, otherwise the store of the target's kind. A stored
30
+ // kind lives in its own table, so a row holds its id; a memory kind has no
31
+ // table of its own, so it is part of the row.
32
+ const embeds = (schema, embed, mode) => {
33
+ if (mode !== 'kind') return mode === 'embed';
34
+ return embed === undefined ? schema.store !== 'persistent' : embed;
35
+ };
36
+
37
+ const reference = {
38
+ kind: 'struct',
39
+ options: ['one', 'many', 'embed'],
40
+
41
+ construct(def) {
42
+ const key = def.many === undefined ? 'one' : 'many';
43
+ const target = def[key];
44
+ if (typeof target !== 'string' || target === '') {
45
+ const reason = `Reference "${key}" needs an entity name, got ${JSON.stringify(target)}`;
46
+ throw new SchemaDefinitionError('ERR_INVALID_REFERENCE', reason);
47
+ }
48
+ if (this.embed !== undefined && typeof this.embed !== 'boolean') throw invalidEmbed();
49
+ // Read from the referencing side: a `many` field holds the many end of
50
+ // a one-to-many relation, a single reference the many end of many-to-one.
51
+ const relation = key === 'many' ? 'one-to-many' : 'many-to-one';
52
+ this[key] = target;
53
+ this.type = target;
54
+ this.root.relations.add({ to: target, type: relation });
55
+ },
56
+
57
+ // The target is looked up at check time: entities of a model are built in
58
+ // any order and a namespace may be attached later.
59
+ compile() {
60
+ const { one, many, root, required, embed } = this;
61
+ if (one) {
62
+ return (value, context, key) => {
63
+ if (!required && value == null) return;
64
+ const schema = root.findReference(one);
65
+ if (!schema) {
66
+ issues.reference(context, one, key);
67
+ return;
68
+ }
69
+ if (embeds(schema, embed, context.references)) runReferenced(schema, value, context, key);
70
+ else if (typeof value !== 'string') issues.type(context, 'string', value, key);
71
+ };
72
+ }
73
+ const expected = `array of ${many}`;
74
+ return (value, context, key) => {
75
+ if (!required && value == null) return;
76
+ const schema = root.findReference(many);
77
+ if (!schema) {
78
+ issues.reference(context, many, key);
79
+ return;
80
+ }
81
+ if (!Array.isArray(value)) {
82
+ issues.type(context, expected, value, key);
83
+ return;
84
+ }
85
+ const nested = key !== undefined;
86
+ if (nested) context.path.push(key);
87
+ const embedded = embeds(schema, embed, context.references);
88
+ for (let index = 0; index < value.length; index += 1) {
89
+ if (context.count >= context.limit) break;
90
+ const item = value[index];
91
+ if (embedded) runReferenced(schema, item, context, index);
92
+ else if (typeof item !== 'string') issues.type(context, 'string', item, index);
93
+ }
94
+ if (nested) context.path.pop();
95
+ };
96
+ },
97
+ };
98
+
99
+ module.exports = { reference, embeds };
@@ -0,0 +1,154 @@
1
+ const { SchemaDefinitionError } = require('../errors.js');
2
+ const { issues } = require('../issues.js');
3
+
4
+ const missingEnum = (type) => {
5
+ const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
6
+ return new SchemaDefinitionError('ERR_INVALID_ENUM', hint);
7
+ };
8
+
9
+ // A single comparison on the way through for a valid value; the optional
10
+ // case is looked at only when it fails.
11
+ const scalarCheck = (scalar, required) => (value, context, key) => {
12
+ // oxlint-disable-next-line valid-typeof
13
+ if (typeof value === scalar) return;
14
+ if (!required && value == null) return;
15
+ issues.type(context, scalar, value, key);
16
+ };
17
+
18
+ const scalar = {
19
+ kind: 'scalar',
20
+ options: [],
21
+
22
+ construct() {},
23
+
24
+ compile() {
25
+ return scalarCheck(this.scalar, this.required);
26
+ },
27
+ };
28
+
29
+ // Past this many values a Set lookup beats a linear scan.
30
+ const ENUM_SET_SIZE = 8;
31
+
32
+ const enumerable = {
33
+ kind: 'scalar',
34
+ options: ['enum'],
35
+
36
+ construct(def) {
37
+ const values = def.enum;
38
+ if (!Array.isArray(values) || values.length === 0) throw missingEnum(this.type);
39
+ this.enum = values;
40
+ },
41
+
42
+ compile() {
43
+ const values = this.enum;
44
+ const { required } = this;
45
+ if (values.length > ENUM_SET_SIZE) {
46
+ const set = new Set(values);
47
+ return (value, context, key) => {
48
+ if (set.has(value)) return;
49
+ if (!required && value == null) return;
50
+ issues.enum(context, values, key);
51
+ };
52
+ }
53
+ return (value, context, key) => {
54
+ if (values.includes(value)) return;
55
+ if (!required && value == null) return;
56
+ issues.enum(context, values, key);
57
+ };
58
+ },
59
+ };
60
+
61
+ // A number without a fraction; it renders as a number in TypeScript.
62
+ const integer = {
63
+ kind: 'scalar',
64
+ scalar: 'number',
65
+ rules: ['min', 'max'],
66
+ options: ['min', 'max'],
67
+
68
+ construct() {},
69
+
70
+ compile() {
71
+ const { required } = this;
72
+ return (value, context, key) => {
73
+ if (Number.isInteger(value)) return;
74
+ if (!required && value == null) return;
75
+ issues.type(context, 'integer', value, key);
76
+ };
77
+ },
78
+ };
79
+
80
+ // A Date instance with a time: an invalid Date is a type error.
81
+ const date = {
82
+ kind: 'scalar',
83
+ scalar: 'date',
84
+ options: [],
85
+
86
+ construct() {},
87
+
88
+ compile() {
89
+ const { required } = this;
90
+ return (value, context, key) => {
91
+ if (value?.constructor?.name === 'Date' && !Number.isNaN(value.getTime())) return;
92
+ if (!required && value == null) return;
93
+ issues.type(context, 'date', value, key);
94
+ };
95
+ },
96
+ };
97
+
98
+ const nothing = {
99
+ kind: 'scalar',
100
+ scalar: 'null',
101
+ options: [],
102
+
103
+ construct() {},
104
+
105
+ compile() {
106
+ const { required } = this;
107
+ return (value, context, key) => {
108
+ if (value === null) return;
109
+ if (value === undefined && !required) return;
110
+ issues.type(context, 'null', value, key);
111
+ };
112
+ },
113
+ };
114
+
115
+ // Any value at all, null and undefined included; `required` still says
116
+ // whether the key must be there.
117
+ const accept = () => {};
118
+
119
+ const any = {
120
+ kind: 'scalar',
121
+ scalar: 'any',
122
+ options: [],
123
+
124
+ construct() {},
125
+
126
+ compile() {
127
+ return accept;
128
+ },
129
+ };
130
+
131
+ const unknown = { ...any, scalar: 'unknown' };
132
+
133
+ const string = {
134
+ ...scalar,
135
+ scalar: 'string',
136
+ rules: ['length', 'pattern'],
137
+ options: ['length', 'unicode', 'pattern'],
138
+ };
139
+ const number = { ...scalar, scalar: 'number', rules: ['min', 'max'], options: ['min', 'max'] };
140
+ const bigint = { ...scalar, scalar: 'bigint', rules: ['min', 'max'], options: ['min', 'max'] };
141
+ const boolean = { ...scalar, scalar: 'boolean' };
142
+
143
+ module.exports = {
144
+ string,
145
+ number,
146
+ integer,
147
+ bigint,
148
+ boolean,
149
+ date,
150
+ null: nothing,
151
+ any,
152
+ unknown,
153
+ enum: enumerable,
154
+ };
@@ -0,0 +1,44 @@
1
+ const { hasBrand } = require('../util.js');
2
+ const { createStruct, isStruct, checkOf } = require('../struct.js');
3
+ const { SchemaDefinitionError } = require('../errors.js');
4
+
5
+ const missingSchema = (type) => {
6
+ const hint = `Type "${type}" needs a schema definition: { type: '${type}', schema: { ... } }`;
7
+ return new SchemaDefinitionError('ERR_MISSING_SCHEMA', hint);
8
+ };
9
+
10
+ const isDefinition = (value) =>
11
+ value !== null && typeof value === 'object' && !Array.isArray(value);
12
+
13
+ // A nested struct: built from a definition object, or borrowed from a Schema
14
+ // instance, whose fields, references and schema-level validate are reused.
15
+ const schema = {
16
+ kind: 'struct',
17
+ options: ['schema'],
18
+
19
+ construct(defs, prep) {
20
+ const { schema: definition, required } = defs;
21
+ if (!isDefinition(definition)) throw missingSchema(this.type);
22
+ this.required = required ?? true;
23
+ if (hasBrand(definition, 'Schema')) {
24
+ prep.root.updateFromSchema(definition);
25
+ this.schema = definition.fields;
26
+ this.validate = definition.options.validate || undefined;
27
+ return;
28
+ }
29
+ if (isStruct(definition)) this.schema = definition;
30
+ else this.schema = createStruct(definition, prep);
31
+ this.validate = definition.validate || undefined;
32
+ },
33
+
34
+ compile() {
35
+ const { required } = this;
36
+ const check = isStruct(this.schema) ? checkOf(this.schema) : this.schema.check;
37
+ return (value, context, key) => {
38
+ if (!required && value == null) return;
39
+ check(value, context, key);
40
+ };
41
+ },
42
+ };
43
+
44
+ module.exports = { schema };
@@ -0,0 +1,68 @@
1
+ const { isFirstUpper } = require('../metautil.js');
2
+ const { formatters } = require('../util.js');
3
+ const { SchemaDefinitionError } = require('../errors.js');
4
+ const { issues } = require('../issues.js');
5
+
6
+ const invalidTuple = (reason) => new SchemaDefinitionError('ERR_INVALID_TUPLE', `Tuple ${reason}`);
7
+
8
+ // A named element is `{ name: 'type' }`: one key that is not `type`, a type
9
+ // name or a kind, holding a type name. Anything else is a definition of its
10
+ // own (a nested struct, a collection, a tuple).
11
+ const nameOf = (element, types) => {
12
+ if (element === null || typeof element !== 'object' || Array.isArray(element)) return null;
13
+ const keys = Object.keys(element);
14
+ if (keys.length !== 1 || typeof element[keys[0]] !== 'string') return null;
15
+ const { field } = formatters.key(keys[0]);
16
+ if (field === 'type' || types[field] || isFirstUpper(field)) return null;
17
+ return keys[0];
18
+ };
19
+
20
+ const tuple = {
21
+ kind: 'struct',
22
+ options: ['value', 'tuple'],
23
+
24
+ construct(def, prep) {
25
+ const elements = def.value || def.tuple;
26
+ if (!Array.isArray(elements)) throw invalidTuple('needs a list of element definitions');
27
+ this.value = elements.map((element, index) => {
28
+ const key = nameOf(element, prep.types);
29
+ const source = key === null ? element : element[key];
30
+ const { Type, defs } = prep.parse(source);
31
+ if (!Type) throw invalidTuple(`element ${index} cannot be a function`);
32
+ if (key !== null) {
33
+ const { field, required } = formatters.key(key);
34
+ defs.required = (defs.required ?? true) && required;
35
+ const type = new Type(defs, prep);
36
+ type.name = field;
37
+ return type;
38
+ }
39
+ return new Type(defs, prep);
40
+ });
41
+ },
42
+
43
+ compile() {
44
+ const { required, type } = this;
45
+ const checks = this.value.map((element) => element.check);
46
+ const { length } = checks;
47
+ return (value, context, key) => {
48
+ if (!Array.isArray(value)) {
49
+ if (!required && value == null) return;
50
+ issues.type(context, type, value, key);
51
+ return;
52
+ }
53
+ if (value.length > length) {
54
+ issues.length(context, undefined, length, value.length, key);
55
+ return;
56
+ }
57
+ const nested = key !== undefined;
58
+ if (nested) context.path.push(key);
59
+ for (let index = 0; index < length; index += 1) {
60
+ if (context.count >= context.limit) break;
61
+ checks[index](value[index], context, index);
62
+ }
63
+ if (nested) context.path.pop();
64
+ };
65
+ },
66
+ };
67
+
68
+ module.exports = { tuple };
@@ -0,0 +1,100 @@
1
+ const { SchemaDefinitionError } = require('../errors.js');
2
+ const { issues } = require('../issues.js');
3
+
4
+ const invalidUnion = (reason) => new SchemaDefinitionError('ERR_INVALID_UNION', `Union ${reason}`);
5
+
6
+ // What a branch is called in the message of a value that matched none.
7
+ const nameOf = (branch) => (branch.type === 'schema' ? 'object' : branch.type);
8
+
9
+ // The values of the discriminator field of a branch: the branch must be a
10
+ // struct whose field of that name is an enum, so the branch is known from
11
+ // one lookup.
12
+ const valuesOf = (branch, discriminator, index) => {
13
+ const field = branch.type === 'schema' ? branch.schema[discriminator] : undefined;
14
+ if (!field || !Array.isArray(field.enum)) {
15
+ const reason = `branch ${index} needs an enum field "${discriminator}" to discriminate on`;
16
+ throw invalidUnion(reason);
17
+ }
18
+ return field.enum;
19
+ };
20
+
21
+ // A value of one of several definitions. Without a discriminator the
22
+ // branches are tried in order and the first one that records nothing wins;
23
+ // what a failed branch recorded is dropped. With one, the branch is picked
24
+ // by the value of that field in one Map lookup.
25
+ const union = {
26
+ kind: 'struct',
27
+ options: ['union', 'discriminator'],
28
+
29
+ construct(def, prep) {
30
+ const branches = def.union;
31
+ if (!Array.isArray(branches) || branches.length === 0) {
32
+ throw invalidUnion('needs a list of branches: { union: [...] }');
33
+ }
34
+ this.union = branches.map((branch, index) => {
35
+ const { Type, defs } = prep.parse(branch);
36
+ if (!Type) throw invalidUnion(`branch ${index} cannot be a function`);
37
+ return new Type(defs, prep);
38
+ });
39
+ const { discriminator } = this;
40
+ if (discriminator === undefined) return;
41
+ if (typeof discriminator !== 'string' || discriminator === '') {
42
+ throw invalidUnion('discriminator needs a field name');
43
+ }
44
+ const seen = new Set();
45
+ this.union.forEach((branch, index) => {
46
+ for (const value of valuesOf(branch, discriminator, index)) {
47
+ if (seen.has(value)) {
48
+ const shown = JSON.stringify(value);
49
+ throw invalidUnion(`discriminator value ${shown} is in two branches`);
50
+ }
51
+ seen.add(value);
52
+ }
53
+ });
54
+ },
55
+
56
+ compile() {
57
+ const { required, discriminator } = this;
58
+ if (discriminator === undefined) return this.compilePlain(required);
59
+ const table = new Map();
60
+ for (const branch of this.union) {
61
+ for (const value of branch.schema[discriminator].enum) table.set(value, branch.check);
62
+ }
63
+ const expected = Array.from(table.keys());
64
+ return (value, context, key) => {
65
+ if (value === null || typeof value !== 'object') {
66
+ if (!required && value == null) return;
67
+ issues.type(context, 'object', value, key);
68
+ return;
69
+ }
70
+ const check = table.get(value[discriminator]);
71
+ if (check !== undefined) {
72
+ check(value, context, key);
73
+ return;
74
+ }
75
+ const nested = key !== undefined;
76
+ if (nested) context.path.push(key);
77
+ issues.union(context, expected, discriminator, discriminator);
78
+ if (nested) context.path.pop();
79
+ };
80
+ },
81
+
82
+ compilePlain(required) {
83
+ const checks = this.union.map((branch) => branch.check);
84
+ const expected = this.union.map(nameOf);
85
+ const { length } = checks;
86
+ return (value, context, key) => {
87
+ if (!required && value == null) return;
88
+ const { count } = context;
89
+ for (let index = 0; index < length; index += 1) {
90
+ checks[index](value, context, key);
91
+ if (context.count === count) return;
92
+ context.issues.length = count;
93
+ context.count = count;
94
+ }
95
+ issues.union(context, expected, undefined, key);
96
+ };
97
+ },
98
+ };
99
+
100
+ module.exports = { union };