@alexify/metaschema 2.0.0 → 3.1.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 +443 -1
- package/README.md +124 -12
- package/SECURITY.md +27 -8
- package/index.d.ts +537 -84
- package/package.json +25 -6
- package/src/codec.js +544 -0
- package/src/compile/code.js +92 -0
- package/src/compile/emit.js +540 -0
- package/src/compile/index.d.ts +38 -0
- package/src/compile/index.js +176 -0
- package/src/context.js +68 -19
- package/src/errors.js +19 -1
- package/src/generators/fromjsonschema.js +520 -0
- package/src/generators/index.d.ts +46 -0
- package/src/generators/index.js +95 -0
- package/src/generators/jsonschema.js +535 -0
- package/src/generators/typescript.js +237 -0
- package/src/index.js +0 -2
- package/src/issues.js +117 -22
- package/src/kinds.js +9 -12
- package/src/lint.js +31 -14
- package/src/locales/en.js +10 -2
- package/src/locales/uk.js +7 -2
- package/src/metadata.js +41 -44
- package/src/metautil.js +8 -1
- package/src/model/data.js +122 -0
- package/src/model/diff.js +438 -0
- package/src/model/index.d.ts +56 -0
- package/src/model/index.js +42 -0
- package/src/model/merge.js +254 -0
- package/src/model/pattern.js +322 -0
- package/src/model/restore.js +226 -0
- package/src/model/sample.js +394 -0
- package/src/model.js +18 -15
- package/src/preprocessor.js +9 -11
- package/src/prototypes/abstract.js +14 -1
- package/src/prototypes/collections.js +20 -3
- package/src/prototypes/reference.js +17 -3
- package/src/prototypes/scalars.js +1 -3
- package/src/prototypes/schema.js +15 -2
- package/src/prototypes/tuple.js +14 -9
- package/src/prototypes/union.js +57 -18
- package/src/result.js +5 -14
- package/src/rules.js +55 -26
- package/src/runtime/browser.js +2 -2
- package/src/runtime/node.js +4 -2
- package/src/schema.js +129 -101
- package/src/snapshot.js +111 -0
- package/src/struct.js +80 -23
- package/src/types.js +5 -11
- package/src/util.js +39 -0
|
@@ -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,5 +1,4 @@
|
|
|
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');
|
|
@@ -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
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// are rendered once, at the end of the check, through the locale of that check.
|
|
5
5
|
// Every issue has the same keys in the same order, so loops over them see one
|
|
6
6
|
// shape.
|
|
7
|
-
const { hasBrand, shorten } = require('./util.js');
|
|
7
|
+
const { hasBrand, shorten, safeString } = require('./util.js');
|
|
8
|
+
const { asyncReturn } = require('./errors.js');
|
|
8
9
|
const en = require('./locales/en.js');
|
|
9
10
|
|
|
10
11
|
// Shared by the issues that carry no params, so none of them is ever undefined.
|
|
@@ -57,7 +58,8 @@ const issues = {
|
|
|
57
58
|
record(context, 'union', { expected, discriminator }, key),
|
|
58
59
|
reference: (context, entity, key) => record(context, 'reference', { entity }, key),
|
|
59
60
|
circular: (context, key) => record(context, 'circular', EMPTY, key),
|
|
60
|
-
|
|
61
|
+
depth: (context, max, key) => record(context, 'depth', { max }, key),
|
|
62
|
+
exception: (context, error, key) => record(context, 'exception', { error }, key),
|
|
61
63
|
};
|
|
62
64
|
|
|
63
65
|
// A key of the value that is not an identifier is bracketed and quoted, so
|
|
@@ -82,13 +84,8 @@ const toDotPath = (path, root = '') => {
|
|
|
82
84
|
|
|
83
85
|
// The path of an issue returned by a validator is relative to the field the
|
|
84
86
|
// validator belongs to: an array of keys, or a single key.
|
|
85
|
-
const relative = (context, path) =>
|
|
86
|
-
|
|
87
|
-
if (Array.isArray(path)) return context.path.concat(path);
|
|
88
|
-
const keys = context.path.slice();
|
|
89
|
-
keys.push(path);
|
|
90
|
-
return keys;
|
|
91
|
-
};
|
|
87
|
+
const relative = (context, path) =>
|
|
88
|
+
Array.isArray(path) ? context.path.concat(path) : pathOf(context, path);
|
|
92
89
|
|
|
93
90
|
const isIssue = (output) =>
|
|
94
91
|
output !== null && typeof output === 'object' && typeof output.message === 'string';
|
|
@@ -131,13 +128,17 @@ const absorb = (context, output, code, fallback) => {
|
|
|
131
128
|
push(context, { code: output.code || code, path, message: output.message, params });
|
|
132
129
|
return;
|
|
133
130
|
}
|
|
134
|
-
record(context, code, EMPTY, undefined,
|
|
131
|
+
record(context, code, EMPTY, undefined, safeString(output));
|
|
135
132
|
};
|
|
136
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.
|
|
137
138
|
const render = (messages, issue) => {
|
|
138
139
|
if (typeof messages === 'function') return messages(issue);
|
|
139
140
|
const detail = messages[issue.code] || en[issue.code];
|
|
140
|
-
return detail ===
|
|
141
|
+
return typeof detail === 'function' ? detail(issue.params, issue) : issue.message;
|
|
141
142
|
};
|
|
142
143
|
|
|
143
144
|
// Messages are produced once, after the walk, for the issues that have none
|
|
@@ -160,37 +161,131 @@ const describe = (messages, root, issue) => {
|
|
|
160
161
|
return `${field(toDotPath(issue.path, root))} ${message}`;
|
|
161
162
|
};
|
|
162
163
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
+
}
|
|
167
205
|
let output;
|
|
168
206
|
try {
|
|
169
|
-
output = call(toDotPath(
|
|
207
|
+
output = fn.call(owner, value, toDotPath(path, context.root));
|
|
170
208
|
} catch (error) {
|
|
171
209
|
issues.exception(context, error);
|
|
172
210
|
return;
|
|
173
211
|
}
|
|
174
|
-
|
|
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);
|
|
175
221
|
};
|
|
176
222
|
|
|
177
|
-
|
|
178
|
-
|
|
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
|
+
};
|
|
179
239
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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 = [];
|
|
183
268
|
};
|
|
184
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
|
+
|
|
185
276
|
module.exports = {
|
|
186
277
|
EMPTY,
|
|
187
278
|
NONE,
|
|
188
279
|
issues,
|
|
189
280
|
typeOf,
|
|
281
|
+
pathOf,
|
|
190
282
|
toDotPath,
|
|
191
283
|
absorb,
|
|
192
284
|
finalize,
|
|
193
285
|
describe,
|
|
286
|
+
isThenable,
|
|
287
|
+
abandon,
|
|
194
288
|
runValidate,
|
|
195
289
|
runCheckType,
|
|
290
|
+
settle,
|
|
196
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
CHANGED
|
@@ -10,9 +10,14 @@ const warning = (code, text) => `Warning [${code}]: ${text}`;
|
|
|
10
10
|
// annotations that any field may carry for code that reads the schema, and
|
|
11
11
|
// the options of its own type. A custom type with its own construct owns
|
|
12
12
|
// its vocabulary and is not linted.
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
const KNOWN = new Set([
|
|
14
|
+
'root',
|
|
15
|
+
'type',
|
|
16
|
+
'required',
|
|
17
|
+
'nullable',
|
|
18
|
+
'validate',
|
|
19
|
+
'parse',
|
|
20
|
+
'serialize',
|
|
16
21
|
'default',
|
|
17
22
|
'unique',
|
|
18
23
|
'index',
|
|
@@ -21,35 +26,47 @@ const ANNOTATIONS = [
|
|
|
21
26
|
'description',
|
|
22
27
|
'examples',
|
|
23
28
|
'deprecated',
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const KNOWN = new Set([...COMMON, ...ANNOTATIONS]);
|
|
29
|
+
'aliases',
|
|
30
|
+
]);
|
|
27
31
|
|
|
28
32
|
const isCustom = (Type) => Type.source !== undefined && Type.source.js === undefined;
|
|
29
33
|
|
|
30
|
-
|
|
34
|
+
// `element` says the field is an element of a tuple, whose `name` is the
|
|
35
|
+
// name the tuple gave it (`[{ x: 'number' }]`), not an option; `member`
|
|
36
|
+
// that it is a field of a struct, the one place aliases are read from.
|
|
37
|
+
const lintField = (field, path, warnings, element = false, member = false) => {
|
|
31
38
|
const Type = field.constructor;
|
|
32
39
|
if (!isCustom(Type)) {
|
|
33
40
|
for (const key of Object.keys(field)) {
|
|
34
41
|
if (KNOWN.has(key) || Type.options.has(key)) continue;
|
|
42
|
+
if (element && key === 'name') continue;
|
|
35
43
|
const text = `option "${key}" of "${path}" is not known to type "${field.type}"`;
|
|
36
44
|
warnings.push(warning('unknown-option', text));
|
|
37
45
|
}
|
|
38
46
|
}
|
|
47
|
+
if (field.aliases !== undefined && !member) {
|
|
48
|
+
const text = `"${path}" has aliases, but only a field of a struct is read from them`;
|
|
49
|
+
warnings.push(warning('dead-aliases', text));
|
|
50
|
+
}
|
|
39
51
|
if (field.pattern !== undefined && field.length?.max === undefined) {
|
|
40
52
|
const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
|
|
41
53
|
warnings.push(warning('unbounded-pattern', text));
|
|
42
54
|
}
|
|
43
55
|
if (field.schema !== undefined) lintStruct(field.schema, path, warnings);
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
56
|
+
const { value, union } = field;
|
|
57
|
+
if (value !== undefined) {
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
60
|
+
lintField(value[index], `${path}[${index}]`, warnings, true);
|
|
61
|
+
}
|
|
47
62
|
} else {
|
|
48
|
-
lintField(
|
|
63
|
+
lintField(value, `${path}[]`, warnings);
|
|
49
64
|
}
|
|
50
65
|
}
|
|
51
|
-
if (
|
|
52
|
-
|
|
66
|
+
if (union !== undefined) {
|
|
67
|
+
for (let index = 0; index < union.length; index += 1) {
|
|
68
|
+
lintField(union[index], `${path}|${index}`, warnings);
|
|
69
|
+
}
|
|
53
70
|
}
|
|
54
71
|
};
|
|
55
72
|
|
|
@@ -61,7 +78,7 @@ const lintStruct = (fields, prefix, warnings) => {
|
|
|
61
78
|
for (const key of Object.keys(fields)) {
|
|
62
79
|
const field = fields[key];
|
|
63
80
|
if (!hasBrand(field, 'Type')) continue;
|
|
64
|
-
lintField(field, prefix ? `${prefix}.${key}` : key, warnings);
|
|
81
|
+
lintField(field, prefix ? `${prefix}.${key}` : key, warnings, false, true);
|
|
65
82
|
}
|
|
66
83
|
};
|
|
67
84
|
|
package/src/locales/en.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The English messages. A locale is a table of renderers by issue code: each
|
|
2
2
|
// one turns the params of an issue into the text that follows the field in a
|
|
3
3
|
// message. `field` renders the location prefix of an error line.
|
|
4
|
-
const { shorten } = require('../util.js');
|
|
4
|
+
const { shorten, safeString } = require('../util.js');
|
|
5
5
|
|
|
6
6
|
const field = (path) => `Field "${path}"`;
|
|
7
7
|
|
|
@@ -37,7 +37,9 @@ const reference = ({ entity }) => `Entity "${entity}" is not found`;
|
|
|
37
37
|
|
|
38
38
|
const circular = () => 'is a circular reference';
|
|
39
39
|
|
|
40
|
-
const
|
|
40
|
+
const depth = ({ max }) => `is nested deeper than ${max} references`;
|
|
41
|
+
|
|
42
|
+
const exception = ({ error }) => `validation failed ${safeString(error)}`;
|
|
41
43
|
|
|
42
44
|
const custom = () => 'validation error';
|
|
43
45
|
|
|
@@ -53,6 +55,12 @@ module.exports = {
|
|
|
53
55
|
union,
|
|
54
56
|
reference,
|
|
55
57
|
circular,
|
|
58
|
+
depth,
|
|
56
59
|
exception,
|
|
57
60
|
custom,
|
|
58
61
|
};
|
|
62
|
+
|
|
63
|
+
// A table without a prototype: a code a validator makes up (`constructor`)
|
|
64
|
+
// finds no renderer here. Set after the literal, which cjs-module-lexer reads
|
|
65
|
+
// for the named exports of the ESM interop.
|
|
66
|
+
Object.setPrototypeOf(module.exports, null);
|
package/src/locales/uk.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Ukrainian messages, with the same table as ./en.js. Pass the table to a
|
|
2
2
|
// check as `messages`: `schema.check(value, { messages: uk })`.
|
|
3
|
-
const { shorten } = require('../util.js');
|
|
3
|
+
const { shorten, safeString } = require('../util.js');
|
|
4
4
|
|
|
5
5
|
const field = (path) => `Поле "${path}"`;
|
|
6
6
|
|
|
@@ -36,7 +36,9 @@ const reference = ({ entity }) => `сутність "${entity}" не знайд
|
|
|
36
36
|
|
|
37
37
|
const circular = () => 'є циклічним посиланням';
|
|
38
38
|
|
|
39
|
-
const
|
|
39
|
+
const depth = ({ max }) => `вкладене глибше ніж ${max} посилань`;
|
|
40
|
+
|
|
41
|
+
const exception = ({ error }) => `перевірка завершилась помилкою ${safeString(error)}`;
|
|
40
42
|
|
|
41
43
|
const custom = () => 'помилка перевірки';
|
|
42
44
|
|
|
@@ -52,6 +54,9 @@ module.exports = {
|
|
|
52
54
|
union,
|
|
53
55
|
reference,
|
|
54
56
|
circular,
|
|
57
|
+
depth,
|
|
55
58
|
exception,
|
|
56
59
|
custom,
|
|
57
60
|
};
|
|
61
|
+
|
|
62
|
+
Object.setPrototypeOf(module.exports, null);
|