@alexify/metaschema 3.4.0 → 4.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.
- package/CHANGELOG.md +227 -1
- package/README.md +29 -11
- package/SECURITY.md +5 -4
- package/index.d.ts +912 -480
- package/package.json +8 -6
- package/src/checks.js +72 -107
- package/src/codec.js +67 -58
- package/src/coerce/index.d.ts +31 -21
- package/src/coerce/index.js +64 -47
- package/src/compile/code.js +2 -2
- package/src/compile/emit.js +20 -31
- package/src/compile/index.d.ts +41 -25
- package/src/compile/index.js +45 -32
- package/src/context.js +10 -10
- package/src/definition/index.d.ts +10 -7
- package/src/definition/index.js +2 -1
- package/src/derive/index.d.ts +25 -17
- package/src/derive/index.js +21 -15
- package/src/errors.js +84 -59
- package/src/formats/index.d.ts +27 -21
- package/src/formats/index.js +15 -13
- package/src/generators/{fromjsonschema.js → from-json-schema.js} +170 -127
- package/src/generators/index.d.ts +23 -15
- package/src/generators/index.js +2 -2
- package/src/generators/{jsonschema.js → json-schema.js} +37 -43
- package/src/generators/typescript.js +9 -6
- package/src/index.js +2 -1
- package/src/issues.js +41 -42
- package/src/kinds.js +31 -10
- package/src/lint.js +64 -19
- package/src/locales/en.js +7 -7
- package/src/locales/uk.js +6 -6
- package/src/metadata.js +2 -2
- package/src/model/data.js +34 -20
- package/src/model/diff.js +29 -24
- package/src/model/index.d.ts +51 -35
- package/src/model/infer.js +70 -61
- package/src/model/merge.js +29 -18
- package/src/model/pattern.js +105 -102
- package/src/model/restore.js +33 -21
- package/src/model/sample.js +90 -100
- package/src/model.js +4 -2
- package/src/mongodb/bson.js +12 -12
- package/src/mongodb/document.js +7 -6
- package/src/mongodb/index.d.ts +54 -31
- package/src/mongodb/update.js +12 -9
- package/src/preprocessor.js +25 -15
- package/src/prototypes/abstract.js +8 -8
- package/src/prototypes/collections.js +7 -7
- package/src/prototypes/flags.js +1 -1
- package/src/prototypes/reference.js +3 -4
- package/src/prototypes/scalars.js +1 -1
- package/src/prototypes/schema.js +5 -6
- package/src/prototypes/tuple.js +11 -10
- package/src/prototypes/union.js +5 -4
- package/src/rules.js +23 -20
- package/src/runtime/browser.js +6 -1
- package/src/runtime/node.js +19 -2
- package/src/schema.js +19 -14
- package/src/snapshot.js +14 -12
- package/src/stream/index.d.ts +33 -21
- package/src/stream/index.js +37 -20
- package/src/struct.js +6 -6
- package/src/types.js +35 -26
- package/src/util.js +70 -64
- package/src/validation.js +10 -13
package/src/mongodb/index.d.ts
CHANGED
|
@@ -9,8 +9,10 @@ import type {
|
|
|
9
9
|
ValidationResult,
|
|
10
10
|
} from '../../index.js';
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* What the subpath reads of the values of bson (4 to 6) or of the driver,
|
|
14
|
+
* which re-exports them; nothing is imported from either.
|
|
15
|
+
*/
|
|
14
16
|
export interface ObjectIdLike {
|
|
15
17
|
readonly _bsontype: 'ObjectId' | 'ObjectID';
|
|
16
18
|
toHexString(): string;
|
|
@@ -24,64 +26,80 @@ export interface BinaryLike {
|
|
|
24
26
|
toJSON(): unknown;
|
|
25
27
|
}
|
|
26
28
|
|
|
27
|
-
|
|
29
|
+
/** The module of the driver (`require('mongodb')`) or of bson. */
|
|
28
30
|
export interface BSONModule {
|
|
29
31
|
ObjectId: new (hex: string) => ObjectIdLike;
|
|
30
32
|
Decimal128?: { fromString(text: string): Decimal128Like };
|
|
31
33
|
Binary?: { createFromBase64(text: string): BinaryLike };
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
/**
|
|
37
|
+
* The BSON types, to give a model: `new Model({ ...types, ...own }, entities)`.
|
|
38
|
+
* A value is one by its `_bsontype` and a method, never by `instanceof`;
|
|
39
|
+
* `binary` takes a Uint8Array too.
|
|
40
|
+
*/
|
|
37
41
|
export const types: {
|
|
38
42
|
readonly objectId: TypeEntry;
|
|
39
43
|
readonly decimal128: TypeEntry;
|
|
40
44
|
readonly binary: TypeEntry;
|
|
41
45
|
};
|
|
42
46
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Keeps the module of the driver for the functions of the subpath and teaches
|
|
49
|
+
* `./coerce` the BSON types (a string of 24 hex digits is an ObjectId, a
|
|
50
|
+
* decimal string a Decimal128, base64 text a Binary). Once: another module
|
|
51
|
+
* after the first throws.
|
|
52
|
+
*/
|
|
47
53
|
export function register(options: { bson: BSONModule }): void;
|
|
48
54
|
|
|
55
|
+
/** How `toDocument`, `fromDocument` and `toUpdate` write ids and references. */
|
|
49
56
|
export interface DocumentOptions {
|
|
50
|
-
|
|
51
|
-
|
|
57
|
+
/**
|
|
58
|
+
* The ids of stored records and references as ObjectIds (the default) or
|
|
59
|
+
* as the strings the program keeps.
|
|
60
|
+
*/
|
|
52
61
|
ids?: 'objectId' | 'string';
|
|
53
|
-
|
|
54
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Which references are records (and so documents with their own `_id`)
|
|
64
|
+
* and which ids, as in `check`.
|
|
65
|
+
*/
|
|
55
66
|
references?: 'kind' | 'embed' | 'id';
|
|
56
|
-
|
|
57
|
-
|
|
67
|
+
/**
|
|
68
|
+
* How many embedded records deep the walk goes (128 by default, as in
|
|
69
|
+
* `check`); a record deeper is left as it is for the check to report.
|
|
70
|
+
*/
|
|
58
71
|
maxDepth?: number;
|
|
59
72
|
}
|
|
60
73
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
74
|
+
/**
|
|
75
|
+
* The document of a value: its serializers run, the id field of a stored
|
|
76
|
+
* record moved to `_id` (left out when there is none, so that the database
|
|
77
|
+
* gives one), ids made ObjectIds, undefined values and calculated fields left
|
|
78
|
+
* out. Needs `register()`: `ALX_ERR_NOT_REGISTERED` otherwise.
|
|
79
|
+
*/
|
|
65
80
|
export function toDocument(
|
|
66
81
|
target: Schema,
|
|
67
82
|
value: unknown,
|
|
68
83
|
options?: DocumentOptions,
|
|
69
84
|
): Record<string, unknown>;
|
|
70
85
|
|
|
71
|
-
|
|
72
|
-
|
|
86
|
+
/**
|
|
87
|
+
* The value of a document: `_id` back to the id field, ObjectIds to their hex
|
|
88
|
+
* strings, then `parse` with `coerce: true` unless the options say otherwise.
|
|
89
|
+
*/
|
|
73
90
|
export function fromDocument<D extends string | object>(
|
|
74
91
|
target: Schema<D>,
|
|
75
92
|
document: unknown,
|
|
76
93
|
options?: ParseOptions & Pick<DocumentOptions, 'references'>,
|
|
77
94
|
): ParseResult<InferOutput<D>>;
|
|
95
|
+
/** `fromDocument` with `parseAsync`, for a schema with async validators or decoders. */
|
|
78
96
|
export function fromDocumentAsync<D extends string | object>(
|
|
79
97
|
target: Schema<D>,
|
|
80
98
|
document: unknown,
|
|
81
99
|
options?: ParseOptions & Pick<DocumentOptions, 'references'>,
|
|
82
100
|
): Promise<ParseResult<InferOutput<D>>>;
|
|
83
101
|
|
|
84
|
-
|
|
102
|
+
/** An index as `createIndexes` takes it. */
|
|
85
103
|
export interface IndexDescription {
|
|
86
104
|
key: Record<string, 1>;
|
|
87
105
|
name?: string;
|
|
@@ -89,11 +107,11 @@ export interface IndexDescription {
|
|
|
89
107
|
sparse?: true;
|
|
90
108
|
}
|
|
91
109
|
|
|
92
|
-
|
|
110
|
+
/** The indexes of a schema, or of every stored entity of a model by name. */
|
|
93
111
|
export function indexesOf(target: Schema): IndexDescription[];
|
|
94
112
|
export function indexesOf(target: Model): Record<string, IndexDescription[]>;
|
|
95
113
|
|
|
96
|
-
|
|
114
|
+
/** An update of the driver: operators and the dotted paths they act on. */
|
|
97
115
|
export type UpdateOperator =
|
|
98
116
|
| '$set'
|
|
99
117
|
| '$setOnInsert'
|
|
@@ -108,22 +126,27 @@ export type UpdateOperator =
|
|
|
108
126
|
| '$pull'
|
|
109
127
|
| '$pullAll'
|
|
110
128
|
| '$pop';
|
|
129
|
+
/** An update document: each operator with the dotted paths it acts on. */
|
|
111
130
|
export type Update = { [O in UpdateOperator]?: Record<string, unknown> };
|
|
112
131
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
132
|
+
/**
|
|
133
|
+
* The issues of an update against the schema: the field each path names,
|
|
134
|
+
* the value each operator sets, pushes or adds to it. The id of a stored
|
|
135
|
+
* record is set by `$setOnInsert` only.
|
|
136
|
+
*/
|
|
116
137
|
export function checkUpdate(
|
|
117
138
|
target: Schema,
|
|
118
139
|
update: Update,
|
|
119
140
|
options?: CheckOptions,
|
|
120
141
|
): ValidationResult;
|
|
121
142
|
|
|
122
|
-
|
|
123
|
-
|
|
143
|
+
/**
|
|
144
|
+
* The update as the database takes it: the values serialized, their ids made
|
|
145
|
+
* ObjectIds, the id of the record as `_id`. Check it with `checkUpdate` first.
|
|
146
|
+
*/
|
|
124
147
|
export function toUpdate(target: Schema, update: Update, options?: DocumentOptions): Update;
|
|
125
148
|
|
|
126
|
-
|
|
149
|
+
/** `Infer` learns the BSON types once this file is loaded. */
|
|
127
150
|
declare module '../../index.js' {
|
|
128
151
|
interface CustomTypes {
|
|
129
152
|
objectId: ObjectIdLike;
|
package/src/mongodb/update.js
CHANGED
|
@@ -21,6 +21,7 @@ const { NESTED, LIST, KEYED, TUPLE, REFERENCE } = SHAPES;
|
|
|
21
21
|
|
|
22
22
|
// A place an update is not checked at: a union, any, json.
|
|
23
23
|
const LOOSE = Symbol('loose');
|
|
24
|
+
const LOOSE_TYPES = new Set(['union', 'any', 'unknown', 'json']);
|
|
24
25
|
// An element of a list of ids: a string.
|
|
25
26
|
const ID = Symbol('id');
|
|
26
27
|
// A part a node does not have (an element of a string, a field of an id):
|
|
@@ -35,9 +36,12 @@ const INDEX = /^\d+$/;
|
|
|
35
36
|
|
|
36
37
|
// The operators of the values a path is set to, of the lists it adds to or
|
|
37
38
|
// takes from, and every operator of an update the subpath reads.
|
|
38
|
-
const
|
|
39
|
-
const
|
|
40
|
-
const
|
|
39
|
+
const VALUE_NAMES = ['$set', '$setOnInsert', '$min', '$max'];
|
|
40
|
+
const LIST_NAMES = ['$push', '$addToSet', '$pull', '$pullAll'];
|
|
41
|
+
const OTHER_NAMES = ['$unset', '$inc', '$mul', '$currentDate', '$pop'];
|
|
42
|
+
const VALUES = new Set(VALUE_NAMES);
|
|
43
|
+
const LISTS = new Set(LIST_NAMES);
|
|
44
|
+
const OPERATORS = new Set(OTHER_NAMES.concat(VALUE_NAMES, LIST_NAMES));
|
|
41
45
|
|
|
42
46
|
// The type a field is of, through the aliases of custom types.
|
|
43
47
|
const baseOf = (field) => baseTypeOf(field).type;
|
|
@@ -70,8 +74,7 @@ const step = (node, segment, references) => {
|
|
|
70
74
|
if (!ELEMENT.test(segment)) return NONE;
|
|
71
75
|
return target === null ? ID : target;
|
|
72
76
|
}
|
|
73
|
-
|
|
74
|
-
return base === 'union' || base === 'any' || base === 'unknown' || base === 'json' ? LOOSE : NONE;
|
|
77
|
+
return LOOSE_TYPES.has(baseOf(node)) ? LOOSE : NONE;
|
|
75
78
|
};
|
|
76
79
|
|
|
77
80
|
// The node a path names, or null, NONE, LOOSE or DEEP: the records a path
|
|
@@ -129,7 +132,7 @@ const checkStep = (node, value, context, key) => {
|
|
|
129
132
|
};
|
|
130
133
|
|
|
131
134
|
const checkOperation = (operator, node, value, context, key) => {
|
|
132
|
-
if (VALUES.
|
|
135
|
+
if (VALUES.has(operator)) checkAt(node, value, context, key);
|
|
133
136
|
else if (operator === '$unset') {
|
|
134
137
|
if (hasBrand(node, 'Type') && node.required) issues.required(context, key);
|
|
135
138
|
} else if (operator === '$inc' || operator === '$mul') checkStep(node, value, context, key);
|
|
@@ -186,7 +189,7 @@ const checkUpdate = (target, update, options) => {
|
|
|
186
189
|
const unknown = [];
|
|
187
190
|
for (const operator of Object.keys(update)) {
|
|
188
191
|
const operand = update[operator];
|
|
189
|
-
if (!OPERATORS.
|
|
192
|
+
if (!OPERATORS.has(operator) || !isObject(operand)) {
|
|
190
193
|
unknown.push(operator);
|
|
191
194
|
continue;
|
|
192
195
|
}
|
|
@@ -209,8 +212,8 @@ const valueOf = (state, context, node, value) => {
|
|
|
209
212
|
};
|
|
210
213
|
|
|
211
214
|
const operandOf = (state, context, operator, node, value) => {
|
|
212
|
-
if (VALUES.
|
|
213
|
-
if (!LISTS.
|
|
215
|
+
if (VALUES.has(operator)) return valueOf(state, context, node, value);
|
|
216
|
+
if (!LISTS.has(operator)) return value;
|
|
214
217
|
const element = elementOf(node, state.references);
|
|
215
218
|
if (element === null) return value;
|
|
216
219
|
const each = (item) => valueOf(state, context, element, item);
|
package/src/preprocessor.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
const { isFirstUpper, toLowerCamel, firstKey } = require('./metautil.js');
|
|
2
2
|
|
|
3
3
|
const { hasBrand, formatters, typeOf } = require('./util.js');
|
|
4
|
+
const { constants, isKindKey } = require('./kinds.js');
|
|
4
5
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
5
6
|
|
|
7
|
+
const BUILT_IN_KINDS = new Set(constants.KIND);
|
|
8
|
+
|
|
6
9
|
// The first key of an object decides what it is: a Schema or a built field is
|
|
7
|
-
// used as it is, a
|
|
8
|
-
//
|
|
9
|
-
|
|
10
|
+
// used as it is, a kind key (`isKindKey` of kinds.js: a name like `Entity`
|
|
11
|
+
// holding the metadata object) is a kind, `type` is the long form, a type
|
|
12
|
+
// name is that type's shorthand, and anything else is a nested struct, a
|
|
13
|
+
// capitalized key that is no kind (`PORT`, `Name: 'string'`) included.
|
|
14
|
+
const PARSERS = {
|
|
15
|
+
__proto__: null,
|
|
10
16
|
string: ['stringShorthand'],
|
|
11
17
|
object: [
|
|
12
18
|
'schemaInstance',
|
|
@@ -18,34 +24,32 @@ const PARSERS = Object.assign(Object.create(null), {
|
|
|
18
24
|
],
|
|
19
25
|
function: ['functionField'],
|
|
20
26
|
array: ['tupleShorthand'],
|
|
21
|
-
}
|
|
27
|
+
};
|
|
22
28
|
|
|
23
|
-
const invalid = (source,
|
|
24
|
-
new SchemaDefinitionError(
|
|
25
|
-
'ERR_INVALID_DEFINITION',
|
|
26
|
-
`Invalid definition: "${source}" of type ${srcType}`,
|
|
27
|
-
);
|
|
29
|
+
const invalid = (source, sourceType = typeOf(source)) =>
|
|
30
|
+
new SchemaDefinitionError(`Invalid definition: "${source}" of type ${sourceType}`);
|
|
28
31
|
|
|
29
32
|
class Preprocessor {
|
|
30
33
|
constructor(root) {
|
|
31
34
|
this.Schema = root.constructor;
|
|
32
35
|
this.root = root;
|
|
33
36
|
this.types = root.types;
|
|
37
|
+
this.kinds = null;
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
// The first key of an object is read once here and handed to the parsers
|
|
37
41
|
// that look at it.
|
|
38
42
|
parse(source) {
|
|
39
|
-
const
|
|
40
|
-
const parsers = PARSERS[
|
|
43
|
+
const sourceType = typeOf(source);
|
|
44
|
+
const parsers = PARSERS[sourceType];
|
|
41
45
|
if (parsers) {
|
|
42
|
-
const first =
|
|
46
|
+
const first = sourceType === 'object' ? firstKey(source) : undefined;
|
|
43
47
|
for (const name of parsers) {
|
|
44
48
|
const result = this[name](source, first);
|
|
45
49
|
if (result) return result;
|
|
46
50
|
}
|
|
47
51
|
}
|
|
48
|
-
throw invalid(source,
|
|
52
|
+
throw invalid(source, sourceType);
|
|
49
53
|
}
|
|
50
54
|
|
|
51
55
|
// A Schema instance as a field: `{ schema: instance }` and the long form go
|
|
@@ -82,7 +86,7 @@ class Preprocessor {
|
|
|
82
86
|
return { Type: types.reference, defs };
|
|
83
87
|
}
|
|
84
88
|
if (!types[type]) {
|
|
85
|
-
throw new SchemaDefinitionError(
|
|
89
|
+
throw new SchemaDefinitionError(`Unknown type "${type}"`, { code: 'ALX_ERR_UNKNOWN_TYPE' });
|
|
86
90
|
}
|
|
87
91
|
const defs = { required, ...source };
|
|
88
92
|
return { Type: types[type], defs };
|
|
@@ -102,9 +106,15 @@ class Preprocessor {
|
|
|
102
106
|
|
|
103
107
|
schemaWithKind(source, first) {
|
|
104
108
|
const { types, root } = this;
|
|
105
|
-
if (!
|
|
109
|
+
if (!isKindKey(first, source[first])) return null;
|
|
106
110
|
const { [first]: meta, ...fields } = source;
|
|
107
111
|
const kind = toLowerCamel(first);
|
|
112
|
+
// A kind of the program's own is kept for the lint: metadata that reads
|
|
113
|
+
// as field definitions is most likely a field that was read as a kind.
|
|
114
|
+
if (!BUILT_IN_KINDS.has(kind)) {
|
|
115
|
+
if (this.kinds === null) this.kinds = [];
|
|
116
|
+
this.kinds.push([first, meta]);
|
|
117
|
+
}
|
|
108
118
|
const kindMeta = { kind, meta, root };
|
|
109
119
|
const defs = { schema: fields };
|
|
110
120
|
return { Type: types.schema, defs, kindMeta };
|
|
@@ -16,18 +16,18 @@ const RESERVED = new Set([
|
|
|
16
16
|
'root',
|
|
17
17
|
]);
|
|
18
18
|
|
|
19
|
-
const reservedKey = (key) =>
|
|
20
|
-
new SchemaDefinitionError('ERR_RESERVED_KEY', `Key "${key}" is reserved in a field definition`);
|
|
21
|
-
|
|
22
19
|
// The options of a field that are flags: `nullable` (null in place of a
|
|
23
20
|
// value) and `coerce` (whether parse converts the input of its subtree).
|
|
24
21
|
const FLAGS = ['nullable', 'coerce'];
|
|
25
22
|
|
|
26
|
-
const
|
|
27
|
-
new SchemaDefinitionError(
|
|
23
|
+
const reservedKey = (key) =>
|
|
24
|
+
new SchemaDefinitionError(`Key "${key}" is reserved in a field definition`, {
|
|
25
|
+
code: 'ALX_ERR_RESERVED_KEY',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const invalidFlag = (key) => new SchemaDefinitionError(`Option "${key}" needs a boolean`);
|
|
28
29
|
|
|
29
|
-
const invalidCodec = (key) =>
|
|
30
|
-
new SchemaDefinitionError('ERR_INVALID_DEFINITION', `Option "${key}" needs a function`);
|
|
30
|
+
const invalidCodec = (key) => new SchemaDefinitionError(`Option "${key}" needs a function`);
|
|
31
31
|
|
|
32
32
|
// `parse` (the decoder) and `serialize` are read by parse and serialize, on
|
|
33
33
|
// any type; a definition that gave them anything else can never work.
|
|
@@ -105,4 +105,4 @@ class AbstractType {
|
|
|
105
105
|
|
|
106
106
|
AbstractType.prototype[BRAND] = 'Type';
|
|
107
107
|
|
|
108
|
-
module.exports = {
|
|
108
|
+
module.exports = { BUILD, AbstractType };
|
|
@@ -5,7 +5,7 @@ const { isMap, isSet } = require('../util.js');
|
|
|
5
5
|
// never match a key, and the JIT quotes the key type into its source.
|
|
6
6
|
const invalidKey = (type) => {
|
|
7
7
|
const reason = `Type "${type}" needs a key type of "string" or "number"`;
|
|
8
|
-
return new SchemaDefinitionError(
|
|
8
|
+
return new SchemaDefinitionError(reason);
|
|
9
9
|
};
|
|
10
10
|
|
|
11
11
|
// The collections: a dictionary (`object`, `map`) of a key type and a value
|
|
@@ -16,7 +16,7 @@ const object = {
|
|
|
16
16
|
options: ['key', 'value', 'length'],
|
|
17
17
|
kind: 'struct',
|
|
18
18
|
|
|
19
|
-
construct(def,
|
|
19
|
+
construct(def, preprocessor) {
|
|
20
20
|
const { type } = this;
|
|
21
21
|
const { [type]: short, key, value } = def;
|
|
22
22
|
let keyType = key;
|
|
@@ -32,8 +32,8 @@ const object = {
|
|
|
32
32
|
}
|
|
33
33
|
if (keyType !== 'string' && keyType !== 'number') throw invalidKey(type);
|
|
34
34
|
this.key = keyType;
|
|
35
|
-
const { Type, defs } =
|
|
36
|
-
this.value = new Type(defs,
|
|
35
|
+
const { Type, defs } = preprocessor.parse(valueDef);
|
|
36
|
+
this.value = new Type(defs, preprocessor);
|
|
37
37
|
},
|
|
38
38
|
|
|
39
39
|
isInstance(value) {
|
|
@@ -54,11 +54,11 @@ const array = {
|
|
|
54
54
|
rules: ['length'],
|
|
55
55
|
options: ['value', 'length'],
|
|
56
56
|
|
|
57
|
-
construct(def,
|
|
57
|
+
construct(def, preprocessor) {
|
|
58
58
|
const { type } = this;
|
|
59
59
|
const source = def[type] || def.value;
|
|
60
|
-
const { Type, defs } =
|
|
61
|
-
this.value = new Type(defs,
|
|
60
|
+
const { Type, defs } = preprocessor.parse(source);
|
|
61
|
+
this.value = new Type(defs, preprocessor);
|
|
62
62
|
},
|
|
63
63
|
|
|
64
64
|
isInstance(value) {
|
package/src/prototypes/flags.js
CHANGED
|
@@ -2,7 +2,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
2
2
|
|
|
3
3
|
const invalidFlags = (type) => {
|
|
4
4
|
const hint = `Type "${type}" needs a list of distinct names: { ${type}: ['read', 'write'] }`;
|
|
5
|
-
return new SchemaDefinitionError(
|
|
5
|
+
return new SchemaDefinitionError(hint);
|
|
6
6
|
};
|
|
7
7
|
|
|
8
8
|
// A set of named switches: an object whose keys are names of the list, each
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
2
|
|
|
3
|
-
const invalidEmbed = () =>
|
|
4
|
-
new SchemaDefinitionError('ERR_INVALID_DEFINITION', 'Option "embed" needs a boolean');
|
|
3
|
+
const invalidEmbed = () => new SchemaDefinitionError('Option "embed" needs a boolean');
|
|
5
4
|
|
|
6
5
|
// Whether a referenced value is the record itself (the graph view) or its
|
|
7
6
|
// id (the storage view): the mode of the check when it says so, otherwise
|
|
@@ -22,7 +21,7 @@ const reference = {
|
|
|
22
21
|
const target = def[key];
|
|
23
22
|
if (typeof target !== 'string' || target === '') {
|
|
24
23
|
const reason = `Reference "${key}" needs an entity name, got ${JSON.stringify(target)}`;
|
|
25
|
-
throw new SchemaDefinitionError('
|
|
24
|
+
throw new SchemaDefinitionError(reason, { code: 'ALX_ERR_INVALID_REFERENCE' });
|
|
26
25
|
}
|
|
27
26
|
if (this.embed !== undefined && typeof this.embed !== 'boolean') throw invalidEmbed();
|
|
28
27
|
// Read from the referencing side: a `many` field holds the many end of
|
|
@@ -34,4 +33,4 @@ const reference = {
|
|
|
34
33
|
},
|
|
35
34
|
};
|
|
36
35
|
|
|
37
|
-
module.exports = {
|
|
36
|
+
module.exports = { embeds, reference };
|
|
@@ -2,7 +2,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
2
2
|
|
|
3
3
|
const missingEnum = (type) => {
|
|
4
4
|
const hint = `Type "${type}" needs a list of values: { type: '${type}', enum: [...] }`;
|
|
5
|
-
return new SchemaDefinitionError('
|
|
5
|
+
return new SchemaDefinitionError(hint, { code: 'ALX_ERR_INVALID_ENUM' });
|
|
6
6
|
};
|
|
7
7
|
|
|
8
8
|
// The scalar types: what a field of each holds (its check is `COMPILE` of
|
package/src/prototypes/schema.js
CHANGED
|
@@ -4,7 +4,7 @@ const { SchemaDefinitionError } = require('../errors.js');
|
|
|
4
4
|
|
|
5
5
|
const missingSchema = (type) => {
|
|
6
6
|
const hint = `Type "${type}" needs a schema definition: { type: '${type}', schema: { ... } }`;
|
|
7
|
-
return new SchemaDefinitionError('
|
|
7
|
+
return new SchemaDefinitionError(hint, { code: 'ALX_ERR_MISSING_SCHEMA' });
|
|
8
8
|
};
|
|
9
9
|
|
|
10
10
|
const isDefinition = (value) =>
|
|
@@ -29,18 +29,17 @@ const schema = {
|
|
|
29
29
|
kind: 'struct',
|
|
30
30
|
options: ['schema'],
|
|
31
31
|
|
|
32
|
-
construct(defs,
|
|
32
|
+
construct(defs, preprocessor) {
|
|
33
33
|
const { schema: definition, required } = defs;
|
|
34
34
|
if (!isDefinition(definition)) throw missingSchema(this.type);
|
|
35
35
|
this.required = required ?? true;
|
|
36
36
|
if (hasBrand(definition, 'Schema')) {
|
|
37
|
-
|
|
37
|
+
preprocessor.root.updateFromSchema(definition);
|
|
38
38
|
this.schema = definition.fields;
|
|
39
|
-
adopt(this, definition.options);
|
|
40
|
-
return;
|
|
39
|
+
return void adopt(this, definition.options);
|
|
41
40
|
}
|
|
42
41
|
if (isStruct(definition)) this.schema = definition;
|
|
43
|
-
else this.schema = createStruct(definition,
|
|
42
|
+
else this.schema = createStruct(definition, preprocessor);
|
|
44
43
|
adopt(this, definition);
|
|
45
44
|
},
|
|
46
45
|
};
|
package/src/prototypes/tuple.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
const { isFirstUpper } = require('../metautil.js');
|
|
2
1
|
const { formatters } = require('../util.js');
|
|
3
2
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
4
3
|
|
|
5
|
-
const invalidTuple = (reason) =>
|
|
4
|
+
const invalidTuple = (reason) =>
|
|
5
|
+
new SchemaDefinitionError(`Tuple ${reason}`, { code: 'ALX_ERR_INVALID_TUPLE' });
|
|
6
6
|
|
|
7
|
-
// A named element is `{ name: 'type' }`: one key that is not `type
|
|
8
|
-
// name
|
|
9
|
-
//
|
|
7
|
+
// A named element is `{ name: 'type' }`: one key that is not `type` or a type
|
|
8
|
+
// name, holding a type name (a string is no metadata of a kind, so `{ X:
|
|
9
|
+
// 'number' }` is a name too). Anything else is a definition of its own (a
|
|
10
|
+
// nested struct, a collection, a tuple).
|
|
10
11
|
const nameOf = (element, types) => {
|
|
11
12
|
if (element === null || typeof element !== 'object' || Array.isArray(element)) return null;
|
|
12
13
|
const keys = Object.keys(element);
|
|
13
14
|
if (keys.length !== 1 || typeof element[keys[0]] !== 'string') return null;
|
|
14
15
|
const { field } = formatters.key(keys[0]);
|
|
15
|
-
if (field === 'type' || types[field]
|
|
16
|
+
if (field === 'type' || types[field]) return null;
|
|
16
17
|
return keys[0];
|
|
17
18
|
};
|
|
18
19
|
|
|
@@ -20,15 +21,15 @@ const tuple = {
|
|
|
20
21
|
kind: 'struct',
|
|
21
22
|
options: ['value', 'tuple'],
|
|
22
23
|
|
|
23
|
-
construct(def,
|
|
24
|
+
construct(def, preprocessor) {
|
|
24
25
|
const elements = def.value || def.tuple;
|
|
25
26
|
if (!Array.isArray(elements)) throw invalidTuple('needs a list of element definitions');
|
|
26
27
|
const built = [];
|
|
27
28
|
for (let index = 0; index < elements.length; index += 1) {
|
|
28
29
|
const element = elements[index];
|
|
29
|
-
const key = nameOf(element,
|
|
30
|
+
const key = nameOf(element, preprocessor.types);
|
|
30
31
|
const source = key === null ? element : element[key];
|
|
31
|
-
const { Type, defs } =
|
|
32
|
+
const { Type, defs } = preprocessor.parse(source);
|
|
32
33
|
if (!Type) throw invalidTuple(`element ${index} cannot be a function`);
|
|
33
34
|
let name = null;
|
|
34
35
|
if (key !== null) {
|
|
@@ -36,7 +37,7 @@ const tuple = {
|
|
|
36
37
|
defs.required = (defs.required ?? true) && parsed.required;
|
|
37
38
|
name = parsed.field;
|
|
38
39
|
}
|
|
39
|
-
const type = new Type(defs,
|
|
40
|
+
const type = new Type(defs, preprocessor);
|
|
40
41
|
if (name !== null) type.name = name;
|
|
41
42
|
built.push(type);
|
|
42
43
|
}
|
package/src/prototypes/union.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const { SchemaDefinitionError } = require('../errors.js');
|
|
2
2
|
|
|
3
|
-
const invalidUnion = (reason) =>
|
|
3
|
+
const invalidUnion = (reason) =>
|
|
4
|
+
new SchemaDefinitionError(`Union ${reason}`, { code: 'ALX_ERR_INVALID_UNION' });
|
|
4
5
|
|
|
5
6
|
// The values of the discriminator field of a branch: the branch must be a
|
|
6
7
|
// struct whose field of that name is an enum, so the branch is known from
|
|
@@ -20,16 +21,16 @@ const union = {
|
|
|
20
21
|
kind: 'struct',
|
|
21
22
|
options: ['union', 'discriminator'],
|
|
22
23
|
|
|
23
|
-
construct(def,
|
|
24
|
+
construct(def, preprocessor) {
|
|
24
25
|
const branches = def.union;
|
|
25
26
|
if (!Array.isArray(branches) || branches.length === 0) {
|
|
26
27
|
throw invalidUnion('needs a list of branches: { union: [...] }');
|
|
27
28
|
}
|
|
28
29
|
const built = [];
|
|
29
30
|
for (let index = 0; index < branches.length; index += 1) {
|
|
30
|
-
const { Type, defs } =
|
|
31
|
+
const { Type, defs } = preprocessor.parse(branches[index]);
|
|
31
32
|
if (!Type) throw invalidUnion(`branch ${index} cannot be a function`);
|
|
32
|
-
built.push(new Type(defs,
|
|
33
|
+
built.push(new Type(defs, preprocessor));
|
|
33
34
|
}
|
|
34
35
|
this.union = built;
|
|
35
36
|
const { discriminator } = this;
|
package/src/rules.js
CHANGED
|
@@ -7,10 +7,25 @@
|
|
|
7
7
|
// check.
|
|
8
8
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
// The formatter of each rule, by name; the names are the rules that exist. A
|
|
11
|
+
// null-prototype dictionary: a definition key may be called `constructor`.
|
|
12
|
+
// The formats a string may name (`format: 'email'`): a null-prototype table
|
|
13
|
+
// of `{ test, examples }` entries, empty until `register()` of the formats
|
|
14
|
+
// subpath fills it (the core knows the rule, the subpath the formats), read
|
|
15
|
+
// when the field is built. A name the table lacks is a definition error with
|
|
16
|
+
// the hint, never a check that passes everything.
|
|
17
|
+
const FORMATS = Object.create(null);
|
|
18
|
+
|
|
19
|
+
// The entry a field's format named when the field was built: a format the
|
|
20
|
+
// program registers later under that name does not change the field, whose
|
|
21
|
+
// check is compiled on its first use.
|
|
22
|
+
const NAMED = new WeakMap();
|
|
23
|
+
|
|
24
|
+
const invalidRule = (reason, options) =>
|
|
25
|
+
new SchemaDefinitionError(reason, { ...options, code: 'ALX_ERR_INVALID_RULE' });
|
|
11
26
|
|
|
12
27
|
const invalidLength = (reason = 'needs a number, [min, max] or { min, max }') =>
|
|
13
|
-
new SchemaDefinitionError(
|
|
28
|
+
new SchemaDefinitionError(`Rule "length" ${reason}`, { code: 'ALX_ERR_INVALID_LENGTH' });
|
|
14
29
|
|
|
15
30
|
const isBound = (value) => value === undefined || typeof value === 'number';
|
|
16
31
|
|
|
@@ -46,24 +61,11 @@ const formatPattern = (value) => {
|
|
|
46
61
|
try {
|
|
47
62
|
return new RegExp(source, `${given}u`);
|
|
48
63
|
} catch (error) {
|
|
49
|
-
|
|
64
|
+
const reason = `Rule "pattern" is not a valid regular expression: ${error.message}`;
|
|
65
|
+
throw invalidRule(reason, { cause: error });
|
|
50
66
|
}
|
|
51
67
|
};
|
|
52
68
|
|
|
53
|
-
// The formatter of each rule, by name; the names are the rules that exist. A
|
|
54
|
-
// null-prototype dictionary: a definition key may be called `constructor`.
|
|
55
|
-
// The formats a string may name (`format: 'email'`): a null-prototype table
|
|
56
|
-
// of `{ test, examples }` entries, empty until `register()` of the formats
|
|
57
|
-
// subpath fills it (the core knows the rule, the subpath the formats), read
|
|
58
|
-
// when the field is built. A name the table lacks is a definition error with
|
|
59
|
-
// the hint, never a check that passes everything.
|
|
60
|
-
const FORMATS = Object.create(null);
|
|
61
|
-
|
|
62
|
-
// The entry a field's format named when the field was built: a format the
|
|
63
|
-
// program registers later under that name does not change the field, whose
|
|
64
|
-
// check is compiled on its first use.
|
|
65
|
-
const NAMED = new WeakMap();
|
|
66
|
-
|
|
67
69
|
const formatName = (value, type) => {
|
|
68
70
|
if (typeof value !== 'string') throw invalidRule('Rule "format" needs the name of a format');
|
|
69
71
|
if (FORMATS[value] === undefined) {
|
|
@@ -84,14 +86,15 @@ const formatDecimals = (value) => {
|
|
|
84
86
|
return value;
|
|
85
87
|
};
|
|
86
88
|
|
|
87
|
-
const FORMAT =
|
|
89
|
+
const FORMAT = {
|
|
90
|
+
__proto__: null,
|
|
88
91
|
length: formatLength,
|
|
89
92
|
min: formatLimit('min'),
|
|
90
93
|
max: formatLimit('max'),
|
|
91
94
|
pattern: formatPattern,
|
|
92
95
|
format: formatName,
|
|
93
96
|
decimals: formatDecimals,
|
|
94
|
-
}
|
|
97
|
+
};
|
|
95
98
|
|
|
96
99
|
// The bounds of a field leave room for a value: the definition is checked
|
|
97
100
|
// when the field is built, its check compiled later.
|
|
@@ -107,4 +110,4 @@ const notApplicable = (rule, type, rules) => {
|
|
|
107
110
|
return invalidRule(`Rule "${rule}" does not apply to type "${type}"${hint}`);
|
|
108
111
|
};
|
|
109
112
|
|
|
110
|
-
module.exports = {
|
|
113
|
+
module.exports = { FORMATS, formatOf, FORMAT, checkBounds, notApplicable };
|
package/src/runtime/browser.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
// Browser twin of ./node.js: the same interface, mapped in by the package.json
|
|
2
2
|
// `browser` field. There is no file system to write to, so it rejects.
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const { SchemaUsageError } = require('../errors.js');
|
|
5
|
+
|
|
6
|
+
const writeFile = () => {
|
|
7
|
+
const message = 'saveTypes is not available in the browser';
|
|
8
|
+
return Promise.reject(new SchemaUsageError(message, { code: 'ALX_ERR_UNSUPPORTED_RUNTIME' }));
|
|
9
|
+
};
|
|
5
10
|
|
|
6
11
|
module.exports = { writeFile };
|