@alexify/metaschema 1.0.0 → 3.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 +551 -1
- package/README.md +235 -34
- package/SECURITY.md +32 -11
- package/index.d.ts +798 -23
- package/package.json +30 -6
- package/src/codec.js +490 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +512 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +141 -0
- package/src/errors.js +10 -1
- package/src/generators/index.d.ts +29 -0
- package/src/generators/index.js +90 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +1 -3
- package/src/issues.js +291 -0
- package/src/kinds.js +9 -12
- package/src/lint.js +98 -0
- package/src/locales/en.d.ts +5 -0
- package/src/locales/en.js +66 -0
- package/src/locales/uk.d.ts +5 -0
- package/src/locales/uk.js +62 -0
- package/src/metadata.js +65 -119
- package/src/metautil.js +8 -1
- package/src/model.js +31 -20
- package/src/preprocessor.js +45 -27
- package/src/prototypes/abstract.js +101 -51
- package/src/prototypes/collections.js +106 -41
- package/src/prototypes/json.js +9 -5
- package/src/prototypes/reference.js +91 -20
- package/src/prototypes/scalars.js +124 -16
- package/src/prototypes/schema.js +31 -6
- package/src/prototypes/tuple.js +57 -29
- package/src/prototypes/union.js +139 -0
- package/src/result.js +115 -0
- package/src/rules.js +185 -0
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +181 -68
- package/src/struct.js +101 -33
- package/src/types.js +14 -14
- package/src/util.js +41 -50
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// The TypeScript generator of the `./generators` subpath: an interface per
|
|
2
|
+
// struct (a type alias for a schema of one type), the description of a
|
|
3
|
+
// field as JSDoc and, when asked, a type of its own for every enum and
|
|
4
|
+
// nested struct.
|
|
5
|
+
const { isFirstUpper } = require('../metautil.js');
|
|
6
|
+
const { hasBrand, IDENTIFIER } = require('../util.js');
|
|
7
|
+
const { SchemaDefinitionError } = require('../errors.js');
|
|
8
|
+
const { embeds } = require('../prototypes/reference.js');
|
|
9
|
+
|
|
10
|
+
const TS_SCALARS = Object.assign(Object.create(null), {
|
|
11
|
+
string: 'string',
|
|
12
|
+
number: 'number',
|
|
13
|
+
boolean: 'boolean',
|
|
14
|
+
bigint: 'bigint',
|
|
15
|
+
date: 'Date',
|
|
16
|
+
null: 'null',
|
|
17
|
+
any: 'any',
|
|
18
|
+
unknown: 'unknown',
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const unrepresentable = (what) =>
|
|
22
|
+
new SchemaDefinitionError('ERR_UNREPRESENTABLE', `${what} cannot be represented in TypeScript`);
|
|
23
|
+
|
|
24
|
+
// The name of an interface or a type is an identifier; a declaration has no
|
|
25
|
+
// place for anything else.
|
|
26
|
+
const identifier = (name, what) => {
|
|
27
|
+
if (!IDENTIFIER.test(name)) throw unrepresentable(`${what} "${name}" (not an identifier)`);
|
|
28
|
+
return name;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// A key of an interface: bare when it is an identifier, quoted otherwise.
|
|
32
|
+
const tsKey = (key) => (IDENTIFIER.test(key) ? key : JSON.stringify(key));
|
|
33
|
+
|
|
34
|
+
// The literal type of an enum value; a value with no literal form (NaN, a
|
|
35
|
+
// symbol, an object) is its type.
|
|
36
|
+
const tsLiteral = (value) => {
|
|
37
|
+
switch (typeof value) {
|
|
38
|
+
case 'string':
|
|
39
|
+
return JSON.stringify(value);
|
|
40
|
+
case 'number':
|
|
41
|
+
return Number.isFinite(value) ? String(value) : 'number';
|
|
42
|
+
case 'bigint':
|
|
43
|
+
return `${value}n`;
|
|
44
|
+
case 'boolean':
|
|
45
|
+
return String(value);
|
|
46
|
+
case 'undefined':
|
|
47
|
+
return 'undefined';
|
|
48
|
+
default:
|
|
49
|
+
return value === null ? 'null' : 'unknown';
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
|
|
54
|
+
|
|
55
|
+
// The name of a nested type: the prefix and the key, capitalized, with what
|
|
56
|
+
// is not an identifier character replaced.
|
|
57
|
+
const typeName = (prefix, key) => {
|
|
58
|
+
const clean = key.replace(/[^\w$]+/g, '_');
|
|
59
|
+
return `${prefix}${clean.charAt(0).toUpperCase()}${clean.slice(1)}`;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Whether a reference field renders as its id (`companyId: string`) or as
|
|
63
|
+
// the referenced type (`company: Company`): the same rule as `check`, with
|
|
64
|
+
// a target that cannot be resolved taken as stored.
|
|
65
|
+
const asId = (def, target) => {
|
|
66
|
+
if (target === null) return def.embed !== true;
|
|
67
|
+
return !embeds(target, def.embed, 'kind');
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// The rendering of one dts: whether a nested struct and an enum get a type
|
|
71
|
+
// of their own, the names given so far (no two types share one), and the
|
|
72
|
+
// blocks rendered, a named type before the one that uses it.
|
|
73
|
+
const uniqueName = (ts, name) => {
|
|
74
|
+
let unique = name;
|
|
75
|
+
for (let n = 2; ts.names.has(unique); n += 1) unique = `${name}${n}`;
|
|
76
|
+
ts.names.add(unique);
|
|
77
|
+
return unique;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const tsStruct = (fields, ts, name) => `{ ${tsFields(fields, ts, name).join('; ')} }`;
|
|
81
|
+
|
|
82
|
+
const tsObject = (fields, ts, name) =>
|
|
83
|
+
hasBrand(fields, 'Struct') ? tsStruct(fields, ts, name) : tsType(fields, ts, name);
|
|
84
|
+
|
|
85
|
+
// The referenced type: its interface by name, inline when it has none, the
|
|
86
|
+
// name of the reference when it cannot be resolved.
|
|
87
|
+
const tsReference = (def, target, ts, name) => {
|
|
88
|
+
if (target === null || target.name) return identifier(def.type, 'Reference');
|
|
89
|
+
return tsObject(target.fields, ts, name);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// The TypeScript type of a field. A reference to a stored kind is held as
|
|
93
|
+
// an id, so it renders as a string (an array of them for `many`), a
|
|
94
|
+
// reference to a memory kind as the type itself; a custom scalar with its
|
|
95
|
+
// own check has no known shape and renders as a string. `name` is the name
|
|
96
|
+
// the type gets when the rendering names nested types; `target` is the
|
|
97
|
+
// referenced entity when the caller resolved it already; `top` says the
|
|
98
|
+
// node is the root of a schema of one type, whose alias is its name already.
|
|
99
|
+
const tsType = (def, ts, name, target, top = false) => {
|
|
100
|
+
const type = tsBase(def, ts, name, target, top);
|
|
101
|
+
return def.nullable === true ? `${type} | null` : type;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const tsBase = (def, ts, name, target, top) => {
|
|
105
|
+
if (isFirstUpper(def.type)) {
|
|
106
|
+
const resolved = target === undefined ? def.root.findReference(def.type) : target;
|
|
107
|
+
const element = asId(def, resolved) ? 'string' : tsReference(def, resolved, ts, name);
|
|
108
|
+
return def.many ? listOf(element) : element;
|
|
109
|
+
}
|
|
110
|
+
if (def.enum) {
|
|
111
|
+
const values = [];
|
|
112
|
+
for (let index = 0; index < def.enum.length; index += 1) {
|
|
113
|
+
values.push(tsLiteral(def.enum[index]));
|
|
114
|
+
}
|
|
115
|
+
const text = values.join(' | ');
|
|
116
|
+
if (!ts.named || top) return text;
|
|
117
|
+
const named = uniqueName(ts, name);
|
|
118
|
+
ts.blocks.push(`type ${named} = ${text};`);
|
|
119
|
+
return named;
|
|
120
|
+
}
|
|
121
|
+
if (def.union) {
|
|
122
|
+
const branches = [];
|
|
123
|
+
for (let index = 0; index < def.union.length; index += 1) {
|
|
124
|
+
branches.push(tsType(def.union[index], ts, `${name}${index}`));
|
|
125
|
+
}
|
|
126
|
+
return branches.join(' | ');
|
|
127
|
+
}
|
|
128
|
+
if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
|
|
129
|
+
if (def.schema) {
|
|
130
|
+
if (ts.named && !top && hasBrand(def.schema, 'Struct')) {
|
|
131
|
+
const named = uniqueName(ts, name);
|
|
132
|
+
ts.blocks.push(tsInterface(named, def.schema, ts));
|
|
133
|
+
return named;
|
|
134
|
+
}
|
|
135
|
+
return tsObject(def.schema, ts, name);
|
|
136
|
+
}
|
|
137
|
+
if (Array.isArray(def.value)) {
|
|
138
|
+
const elements = [];
|
|
139
|
+
for (let index = 0; index < def.value.length; index += 1) {
|
|
140
|
+
elements.push(tsType(def.value[index], ts, `${name}${index}`));
|
|
141
|
+
}
|
|
142
|
+
return `[${elements.join(', ')}]`;
|
|
143
|
+
}
|
|
144
|
+
if (def.key !== undefined && def.value) {
|
|
145
|
+
const entries = `${def.key}, ${tsType(def.value, ts, name)}`;
|
|
146
|
+
return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
|
|
147
|
+
}
|
|
148
|
+
if (def.value) {
|
|
149
|
+
const element = tsType(def.value, ts, name);
|
|
150
|
+
return def.isInstance([]) ? listOf(element) : `Set<${element}>`;
|
|
151
|
+
}
|
|
152
|
+
if (def.kind === 'struct') return 'unknown';
|
|
153
|
+
return 'string';
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const tsField = (key, def, ts, prefix) => {
|
|
157
|
+
const optional = def.required ? '' : '?';
|
|
158
|
+
const reference = isFirstUpper(def.type);
|
|
159
|
+
const target = reference ? def.root.findReference(def.type) : undefined;
|
|
160
|
+
const name = reference && asId(def, target) ? `${key}Id` : key;
|
|
161
|
+
return `${tsKey(name)}${optional}: ${tsType(def, ts, typeName(prefix, key), target)}`;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// The validated fields of a struct, in order: a struct is a null-prototype
|
|
165
|
+
// dictionary, so its keys are its own.
|
|
166
|
+
const tsFields = (fields, ts, prefix) => {
|
|
167
|
+
const lines = [];
|
|
168
|
+
for (const key in fields) {
|
|
169
|
+
const def = fields[key];
|
|
170
|
+
if (!hasBrand(def, 'Type')) continue;
|
|
171
|
+
lines.push(tsField(key, def, ts, prefix));
|
|
172
|
+
}
|
|
173
|
+
return lines;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// Text inside a comment: `*/` would close it.
|
|
177
|
+
const tsComment = (text) => String(text).replace(/\*\//g, '*\\/');
|
|
178
|
+
|
|
179
|
+
// The JSDoc of a field: its description, line by line, and `@deprecated`
|
|
180
|
+
// (with the note when the field gives one) when it says so.
|
|
181
|
+
const tsDoc = (def) => {
|
|
182
|
+
const { description, deprecated } = def;
|
|
183
|
+
const lines = description === undefined ? [] : tsComment(description).split('\n');
|
|
184
|
+
if (deprecated === true) lines.push('@deprecated');
|
|
185
|
+
else if (typeof deprecated === 'string') lines.push(`@deprecated ${tsComment(deprecated)}`);
|
|
186
|
+
if (lines.length === 0) return lines;
|
|
187
|
+
if (lines.length === 1) return [`/** ${lines[0]} */`];
|
|
188
|
+
const block = ['/**'];
|
|
189
|
+
for (let index = 0; index < lines.length; index += 1) block.push(` * ${lines[index]}`);
|
|
190
|
+
block.push(' */');
|
|
191
|
+
return block;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const tsInterface = (name, fields, ts) => {
|
|
195
|
+
const lines = [`interface ${name} {`];
|
|
196
|
+
for (const key in fields) {
|
|
197
|
+
const def = fields[key];
|
|
198
|
+
if (!hasBrand(def, 'Type')) continue;
|
|
199
|
+
const doc = tsDoc(def);
|
|
200
|
+
for (let index = 0; index < doc.length; index += 1) lines.push(` ${doc[index]}`);
|
|
201
|
+
lines.push(` ${tsField(key, def, ts, name)};`);
|
|
202
|
+
}
|
|
203
|
+
lines.push('}');
|
|
204
|
+
return lines.join('\n');
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// The schema as a TypeScript interface (a type alias for a schema of one
|
|
208
|
+
// type), with the description of a field as JSDoc. With `{ named: true }`
|
|
209
|
+
// a nested struct and an enum get a type of their own, named after the
|
|
210
|
+
// entity and the field, rendered before the interface that uses them.
|
|
211
|
+
// `names` holds the names given so far when several schemas share one
|
|
212
|
+
// rendering (a model), so that a nested type never takes an entity's name.
|
|
213
|
+
const toInterface = (schema, options = {}, names = new Set()) => {
|
|
214
|
+
const { name, fields } = schema;
|
|
215
|
+
if (name !== '') identifier(name, 'Entity name');
|
|
216
|
+
names.add(name);
|
|
217
|
+
const ts = { named: options.named === true, names, blocks: [] };
|
|
218
|
+
const struct = hasBrand(fields, 'Struct');
|
|
219
|
+
ts.blocks.push(
|
|
220
|
+
struct
|
|
221
|
+
? tsInterface(name, fields, ts)
|
|
222
|
+
: `type ${name} = ${tsType(fields, ts, name, undefined, true)};`,
|
|
223
|
+
);
|
|
224
|
+
return ts.blocks.join('\n\n');
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
// Every entity of a model as an interface, in dependency order.
|
|
228
|
+
const modelToTypeScript = (model, options) => {
|
|
229
|
+
const { entities, order } = model;
|
|
230
|
+
const names = new Set();
|
|
231
|
+
for (const name of order) names.add(name);
|
|
232
|
+
const dts = [];
|
|
233
|
+
for (const name of order) dts.push(toInterface(entities.get(name), options, names));
|
|
234
|
+
return `${dts.join('\n\n')}\n`;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
module.exports = { toInterface, modelToTypeScript };
|
package/src/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
const { constants, getKindMetadata } = require('./kinds.js');
|
|
2
|
-
const { saveTypes } = require('./runtime/node.js');
|
|
3
2
|
const { Schema } = require('./schema.js');
|
|
4
3
|
const { Model } = require('./model.js');
|
|
5
4
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
6
|
-
const { ValidationResult } = require('./
|
|
5
|
+
const { ValidationResult } = require('./result.js');
|
|
7
6
|
|
|
8
7
|
const { KIND, KIND_STORED, KIND_MEMORY, SCOPE, STORE, ALLOW } = constants;
|
|
9
8
|
|
|
@@ -15,7 +14,6 @@ module.exports = {
|
|
|
15
14
|
STORE,
|
|
16
15
|
ALLOW,
|
|
17
16
|
getKindMetadata,
|
|
18
|
-
saveTypes,
|
|
19
17
|
Schema,
|
|
20
18
|
Model,
|
|
21
19
|
SchemaDefinitionError,
|
package/src/issues.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// A validation issue is data: { code, path, message, params }. The library's
|
|
2
|
+
// own checks record the code, the path (an array of keys from the root of the
|
|
3
|
+
// value) and the params of the problem, and leave the message empty; messages
|
|
4
|
+
// are rendered once, at the end of the check, through the locale of that check.
|
|
5
|
+
// Every issue has the same keys in the same order, so loops over them see one
|
|
6
|
+
// shape.
|
|
7
|
+
const { hasBrand, shorten, safeString } = require('./util.js');
|
|
8
|
+
const { asyncReturn } = require('./errors.js');
|
|
9
|
+
const en = require('./locales/en.js');
|
|
10
|
+
|
|
11
|
+
// Shared by the issues that carry no params, so none of them is ever undefined.
|
|
12
|
+
const EMPTY = Object.freeze({});
|
|
13
|
+
|
|
14
|
+
// The issues of a context before the first one is recorded: a valid check
|
|
15
|
+
// never allocates a list.
|
|
16
|
+
const NONE = Object.freeze([]);
|
|
17
|
+
|
|
18
|
+
const push = (context, issue) => {
|
|
19
|
+
if (context.issues === NONE) context.issues = [];
|
|
20
|
+
context.issues.push(issue);
|
|
21
|
+
context.count += 1;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// The path of an issue: the current path, plus the key of the field under
|
|
25
|
+
// check when its check was given one instead of pushing it on the path (a
|
|
26
|
+
// leaf check never pushes; a container pushes its key before its children).
|
|
27
|
+
const pathOf = (context, key) => {
|
|
28
|
+
const { path } = context;
|
|
29
|
+
if (key === undefined) return path.slice();
|
|
30
|
+
if (path.length === 0) return [key];
|
|
31
|
+
const keys = path.slice();
|
|
32
|
+
keys.push(key);
|
|
33
|
+
return keys;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const record = (context, code, params, key, message = '') => {
|
|
37
|
+
push(context, { code, path: pathOf(context, key), message, params });
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const typeOf = (value) => {
|
|
41
|
+
if (value === null) return 'null';
|
|
42
|
+
if (Array.isArray(value)) return 'array';
|
|
43
|
+
return typeof value;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const issues = {
|
|
47
|
+
required: (context, key) => record(context, 'required', EMPTY, key),
|
|
48
|
+
type: (context, expected, value, key) =>
|
|
49
|
+
record(context, 'type', { expected, received: typeOf(value) }, key),
|
|
50
|
+
key: (context, expected, name, key) =>
|
|
51
|
+
record(context, 'type', { expected, received: typeof name, key: name }, key),
|
|
52
|
+
unexpected: (context, keys, key) => record(context, 'unexpected', { keys }, key),
|
|
53
|
+
enum: (context, values, key) => record(context, 'enum', { values }, key),
|
|
54
|
+
length: (context, min, max, actual, key) => record(context, 'length', { min, max, actual }, key),
|
|
55
|
+
range: (context, min, max, actual, key) => record(context, 'range', { min, max, actual }, key),
|
|
56
|
+
pattern: (context, pattern, key) => record(context, 'pattern', { pattern }, key),
|
|
57
|
+
union: (context, expected, discriminator, key) =>
|
|
58
|
+
record(context, 'union', { expected, discriminator }, key),
|
|
59
|
+
reference: (context, entity, key) => record(context, 'reference', { entity }, key),
|
|
60
|
+
circular: (context, key) => record(context, 'circular', EMPTY, key),
|
|
61
|
+
depth: (context, max, key) => record(context, 'depth', { max }, key),
|
|
62
|
+
exception: (context, error, key) => record(context, 'exception', { error }, key),
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// A key of the value that is not an identifier is bracketed and quoted, so
|
|
66
|
+
// `a.b` as one key and `a` then `b` render differently. Keys taken from the
|
|
67
|
+
// value may be huge; a message must not be.
|
|
68
|
+
const IDENTIFIER = /^[\w$]+$/;
|
|
69
|
+
|
|
70
|
+
const toDotPath = (path, root = '') => {
|
|
71
|
+
let text = root;
|
|
72
|
+
for (let index = 0; index < path.length; index += 1) {
|
|
73
|
+
const key = path[index];
|
|
74
|
+
if (typeof key === 'number') {
|
|
75
|
+
text += `[${key}]`;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const name = String(key);
|
|
79
|
+
if (!IDENTIFIER.test(name)) text += `[${JSON.stringify(shorten(name))}]`;
|
|
80
|
+
else text += text === '' ? shorten(name) : `.${shorten(name)}`;
|
|
81
|
+
}
|
|
82
|
+
return text;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// The path of an issue returned by a validator is relative to the field the
|
|
86
|
+
// validator belongs to: an array of keys, or a single key.
|
|
87
|
+
const relative = (context, path) =>
|
|
88
|
+
Array.isArray(path) ? context.path.concat(path) : pathOf(context, path);
|
|
89
|
+
|
|
90
|
+
const isIssue = (output) =>
|
|
91
|
+
output !== null && typeof output === 'object' && typeof output.message === 'string';
|
|
92
|
+
|
|
93
|
+
// Everything a validator or a custom checkType may return, recorded as
|
|
94
|
+
// issues: true, null and undefined are nothing; false is a generic error with
|
|
95
|
+
// `fallback` as its params; a string is a message; an object with a message is
|
|
96
|
+
// an issue of its own; an array holds any of these; a ValidationResult holds
|
|
97
|
+
// issues already.
|
|
98
|
+
const absorb = (context, output, code, fallback) => {
|
|
99
|
+
if (output === true || output === null || output === undefined) return;
|
|
100
|
+
if (output === false) {
|
|
101
|
+
record(context, code, fallback);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (typeof output === 'string') {
|
|
105
|
+
record(context, code, EMPTY, undefined, output);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (Array.isArray(output)) {
|
|
109
|
+
// One by one: a validator may legitimately return more messages than a
|
|
110
|
+
// spread call accepts.
|
|
111
|
+
for (const item of output) {
|
|
112
|
+
if (context.count >= context.limit) return;
|
|
113
|
+
absorb(context, item, code, fallback);
|
|
114
|
+
}
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (hasBrand(output, 'ValidationResult')) {
|
|
118
|
+
for (const issue of output.issues) {
|
|
119
|
+
if (context.count >= context.limit) return;
|
|
120
|
+
const path = context.path.concat(issue.path);
|
|
121
|
+
push(context, { code: issue.code, path, message: issue.message, params: issue.params });
|
|
122
|
+
}
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (isIssue(output)) {
|
|
126
|
+
const path = relative(context, output.path);
|
|
127
|
+
const params = output.params === undefined ? EMPTY : output.params;
|
|
128
|
+
push(context, { code: output.code || code, path, message: output.message, params });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
record(context, code, EMPTY, undefined, safeString(output));
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// The renderer of a code: the locale's own, else the built-in one. The tables
|
|
135
|
+
// have no prototype (the built-in ones by construction, a caller's through
|
|
136
|
+
// `messagesOf` in context.js), so a code a validator made up (`constructor`
|
|
137
|
+
// included) finds no renderer and keeps the validator's message.
|
|
138
|
+
const render = (messages, issue) => {
|
|
139
|
+
if (typeof messages === 'function') return messages(issue);
|
|
140
|
+
const detail = messages[issue.code] || en[issue.code];
|
|
141
|
+
return typeof detail === 'function' ? detail(issue.params, issue) : issue.message;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// Messages are produced once, after the walk, for the issues that have none
|
|
145
|
+
// (a validator's own message is kept as it is).
|
|
146
|
+
const finalize = (list, messages) => {
|
|
147
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
148
|
+
const issue = list[index];
|
|
149
|
+
if (issue.message === '') issue.message = render(messages, issue);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// A message that already names its field (`Field "User.name" is not hex`, the
|
|
154
|
+
// upstream convention for custom types) is kept as it is.
|
|
155
|
+
const PREFIXED = 'Field';
|
|
156
|
+
|
|
157
|
+
const describe = (messages, root, issue) => {
|
|
158
|
+
const { message } = issue;
|
|
159
|
+
if (message.startsWith(PREFIXED)) return message;
|
|
160
|
+
const field = typeof messages === 'function' ? en.field : messages.field || en.field;
|
|
161
|
+
return `${field(toDotPath(issue.path, root))} ${message}`;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const isThenable = (value) =>
|
|
165
|
+
value !== null && typeof value === 'object' && typeof value.then === 'function';
|
|
166
|
+
|
|
167
|
+
// A promise nothing waits for any more (a synchronous call that throws for
|
|
168
|
+
// it, a settle stopped by the error limit, the trial of a union branch) is
|
|
169
|
+
// still observed, so that its rejection is never an unhandled one.
|
|
170
|
+
const swallow = () => {};
|
|
171
|
+
|
|
172
|
+
const abandon = (thenable) => {
|
|
173
|
+
Promise.resolve(thenable).then(undefined, swallow);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// The params of a bare `false`: for a checkType the type it expected and what
|
|
177
|
+
// it got, built only now that there is something to record.
|
|
178
|
+
const fallbackOf = (code, owner, value) =>
|
|
179
|
+
code === 'type' ? { expected: owner.type, received: typeOf(value) } : EMPTY;
|
|
180
|
+
|
|
181
|
+
// What a validator or a checkType returned, into the context.
|
|
182
|
+
const conclude = (context, output, code, owner, value) => {
|
|
183
|
+
if (output === true || output == null) return;
|
|
184
|
+
const bare = output === false || Array.isArray(output);
|
|
185
|
+
absorb(context, output, code, bare ? fallbackOf(code, owner, value) : EMPTY);
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// Where user code runs (a validator, a custom checkType; the decoders have
|
|
189
|
+
// their own place in codec.js): an exception is reported as an issue, not
|
|
190
|
+
// thrown, and the function gets the value and the dotted path of the field,
|
|
191
|
+
// called on its owner here rather than through a closure made per call. In
|
|
192
|
+
// an async check (`context.async` is a list) a promise is kept with the path
|
|
193
|
+
// it was met at, and every validator after it is kept too, with what it needs
|
|
194
|
+
// to be called, so that the rule "a validator runs only when nothing before
|
|
195
|
+
// it failed" holds over the promises as well; `settle` runs the list after
|
|
196
|
+
// the walk, in field order. In a synchronous check a promise is an error of
|
|
197
|
+
// the call.
|
|
198
|
+
const guarded = (context, code, owner, fn, value) => {
|
|
199
|
+
const pending = context.async;
|
|
200
|
+
const { path, count } = context;
|
|
201
|
+
if (pending !== null && pending.length > 0) {
|
|
202
|
+
pending.push({ owner, fn, value, promise: null, path: path.slice(), code, count });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
let output;
|
|
206
|
+
try {
|
|
207
|
+
output = fn.call(owner, value, toDotPath(path, context.root));
|
|
208
|
+
} catch (error) {
|
|
209
|
+
issues.exception(context, error);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (isThenable(output)) {
|
|
213
|
+
if (pending === null) {
|
|
214
|
+
abandon(output);
|
|
215
|
+
throw asyncReturn('validator', toDotPath(path, context.root), 'checkAsync or parseAsync');
|
|
216
|
+
}
|
|
217
|
+
pending.push({ owner, fn: null, value, promise: output, path: path.slice(), code, count });
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
conclude(context, output, code, owner, value);
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// Whether an issue recorded since the validator was deferred lies under its
|
|
224
|
+
// path: the fields of the value it validates were checked before it.
|
|
225
|
+
const failedUnder = (context, entry) => {
|
|
226
|
+
const { issues: list } = context;
|
|
227
|
+
const { path } = entry;
|
|
228
|
+
for (let index = entry.count; index < list.length; index += 1) {
|
|
229
|
+
const recorded = list[index].path;
|
|
230
|
+
if (recorded.length < path.length) continue;
|
|
231
|
+
let under = true;
|
|
232
|
+
for (let depth = 0; depth < path.length && under; depth += 1) {
|
|
233
|
+
under = recorded[depth] === path[depth];
|
|
234
|
+
}
|
|
235
|
+
if (under) return true;
|
|
236
|
+
}
|
|
237
|
+
return false;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// Runs the validators an async check kept, one after the other in the order
|
|
241
|
+
// they were met, each recording under the path it was met at; the error
|
|
242
|
+
// limit stops the list as it stops the walk.
|
|
243
|
+
const settle = async (context) => {
|
|
244
|
+
const pending = context.async;
|
|
245
|
+
for (let index = 0; index < pending.length; index += 1) {
|
|
246
|
+
if (context.count >= context.limit) {
|
|
247
|
+
for (; index < pending.length; index += 1) {
|
|
248
|
+
if (pending[index].promise !== null) abandon(pending[index].promise);
|
|
249
|
+
}
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
const entry = pending[index];
|
|
253
|
+
if (entry.fn !== null && failedUnder(context, entry)) continue;
|
|
254
|
+
context.path = entry.path;
|
|
255
|
+
let output;
|
|
256
|
+
try {
|
|
257
|
+
output =
|
|
258
|
+
entry.fn === null
|
|
259
|
+
? await entry.promise
|
|
260
|
+
: await entry.fn.call(entry.owner, entry.value, toDotPath(entry.path, context.root));
|
|
261
|
+
} catch (error) {
|
|
262
|
+
issues.exception(context, error);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
conclude(context, output, entry.code, entry.owner, entry.value);
|
|
266
|
+
}
|
|
267
|
+
context.path = [];
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
const runValidate = (owner, validate, value, context) =>
|
|
271
|
+
guarded(context, 'custom', owner, validate, value);
|
|
272
|
+
|
|
273
|
+
const runCheckType = (type, value, context) =>
|
|
274
|
+
guarded(context, 'type', type, type.checkType, value);
|
|
275
|
+
|
|
276
|
+
module.exports = {
|
|
277
|
+
EMPTY,
|
|
278
|
+
NONE,
|
|
279
|
+
issues,
|
|
280
|
+
typeOf,
|
|
281
|
+
pathOf,
|
|
282
|
+
toDotPath,
|
|
283
|
+
absorb,
|
|
284
|
+
finalize,
|
|
285
|
+
describe,
|
|
286
|
+
isThenable,
|
|
287
|
+
abandon,
|
|
288
|
+
runValidate,
|
|
289
|
+
runCheckType,
|
|
290
|
+
settle,
|
|
291
|
+
};
|
package/src/kinds.js
CHANGED
|
@@ -33,21 +33,18 @@ const projection = (kind, meta, root) => {
|
|
|
33
33
|
return { defs, metadata };
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
36
|
+
// The metadata of a kind over the defaults of its scope and store; a stored
|
|
37
|
+
// kind adds the optional id field named after the entity.
|
|
38
|
+
const kindOf = (defaultScope, defaultStore, stored) => (kind, meta, root) => {
|
|
39
|
+
const { scope = defaultScope, store = defaultStore, allow = 'write' } = meta;
|
|
40
40
|
const defs = Object.create(null);
|
|
41
|
-
defs[id] = '?string';
|
|
42
|
-
return { defs, metadata };
|
|
41
|
+
if (stored) defs[root.name ? `${toLowerCamel(root.name)}Id` : 'id'] = '?string';
|
|
42
|
+
return { defs, metadata: { ...meta, kind, scope, store, allow } };
|
|
43
43
|
};
|
|
44
44
|
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const defs = Object.create(null);
|
|
49
|
-
return { defs, metadata };
|
|
50
|
-
};
|
|
45
|
+
const kindStored = kindOf('application', 'persistent', true);
|
|
46
|
+
|
|
47
|
+
const kindMemory = kindOf('local', 'memory', false);
|
|
51
48
|
|
|
52
49
|
const KIND_METADATA = Object.create(null);
|
|
53
50
|
for (const kind of KIND_MEMORY) {
|
package/src/lint.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Lints of a built schema: what is not wrong enough to throw, but is not
|
|
2
|
+
// what the author meant either. A contradiction that can never validate
|
|
3
|
+
// (an enum without values, a min above max) is a SchemaDefinitionError at
|
|
4
|
+
// build time; these are warnings, as `Warning [code]: text` strings.
|
|
5
|
+
const { hasBrand } = require('./util.js');
|
|
6
|
+
|
|
7
|
+
const warning = (code, text) => `Warning [${code}]: ${text}`;
|
|
8
|
+
|
|
9
|
+
// A field lints by its definition keys: the keys every type knows, the
|
|
10
|
+
// annotations that any field may carry for code that reads the schema, and
|
|
11
|
+
// the options of its own type. A custom type with its own construct owns
|
|
12
|
+
// its vocabulary and is not linted.
|
|
13
|
+
const KNOWN = new Set([
|
|
14
|
+
'root',
|
|
15
|
+
'type',
|
|
16
|
+
'required',
|
|
17
|
+
'nullable',
|
|
18
|
+
'validate',
|
|
19
|
+
'parse',
|
|
20
|
+
'serialize',
|
|
21
|
+
'default',
|
|
22
|
+
'unique',
|
|
23
|
+
'index',
|
|
24
|
+
'primary',
|
|
25
|
+
'title',
|
|
26
|
+
'description',
|
|
27
|
+
'examples',
|
|
28
|
+
'deprecated',
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const isCustom = (Type) => Type.source !== undefined && Type.source.js === undefined;
|
|
32
|
+
|
|
33
|
+
const lintField = (field, path, warnings) => {
|
|
34
|
+
const Type = field.constructor;
|
|
35
|
+
if (!isCustom(Type)) {
|
|
36
|
+
for (const key of Object.keys(field)) {
|
|
37
|
+
if (KNOWN.has(key) || Type.options.has(key)) continue;
|
|
38
|
+
const text = `option "${key}" of "${path}" is not known to type "${field.type}"`;
|
|
39
|
+
warnings.push(warning('unknown-option', text));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (field.pattern !== undefined && field.length?.max === undefined) {
|
|
43
|
+
const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
|
|
44
|
+
warnings.push(warning('unbounded-pattern', text));
|
|
45
|
+
}
|
|
46
|
+
if (field.schema !== undefined) lintStruct(field.schema, path, warnings);
|
|
47
|
+
const { value, union } = field;
|
|
48
|
+
if (value !== undefined) {
|
|
49
|
+
if (Array.isArray(value)) {
|
|
50
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
51
|
+
lintField(value[index], `${path}[${index}]`, warnings);
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
lintField(value, `${path}[]`, warnings);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (union !== undefined) {
|
|
58
|
+
for (let index = 0; index < union.length; index += 1) {
|
|
59
|
+
lintField(union[index], `${path}|${index}`, warnings);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const lintStruct = (fields, prefix, warnings) => {
|
|
65
|
+
if (!hasBrand(fields, 'Struct')) {
|
|
66
|
+
lintField(fields, prefix, warnings);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
for (const key of Object.keys(fields)) {
|
|
70
|
+
const field = fields[key];
|
|
71
|
+
if (!hasBrand(field, 'Type')) continue;
|
|
72
|
+
lintField(field, prefix ? `${prefix}.${key}` : key, warnings);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const lintIndexes = (schema, warnings) => {
|
|
77
|
+
const { name, indexes, fields } = schema;
|
|
78
|
+
for (const key of Object.keys(indexes)) {
|
|
79
|
+
const index = indexes[key];
|
|
80
|
+
const columns = index.index || index.primary || index.unique;
|
|
81
|
+
if (!Array.isArray(columns)) continue;
|
|
82
|
+
for (const column of columns) {
|
|
83
|
+
if (hasBrand(fields[column], 'Type')) continue;
|
|
84
|
+
const text = `index "${key}" of "${name}" names a field "${column}" it does not have`;
|
|
85
|
+
warnings.push(warning('missing-index-field', text));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// The warnings of one schema on its own: everything that needs no model.
|
|
91
|
+
const lintSchema = (schema) => {
|
|
92
|
+
const warnings = [];
|
|
93
|
+
lintStruct(schema.fields, schema.name, warnings);
|
|
94
|
+
lintIndexes(schema, warnings);
|
|
95
|
+
return warnings;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
module.exports = { warning, lintSchema };
|