@alexify/metaschema 2.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 +324 -1
- package/README.md +117 -12
- package/SECURITY.md +27 -8
- package/index.d.ts +319 -83
- package/package.json +21 -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 +65 -19
- 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 +0 -2
- package/src/issues.js +117 -22
- package/src/kinds.js +9 -12
- package/src/lint.js +20 -12
- 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.js +10 -15
- package/src/preprocessor.js +5 -10
- 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 +12 -0
- 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 +120 -101
- package/src/struct.js +18 -7
- package/src/types.js +5 -11
- package/src/util.js +39 -0
package/src/rules.js
CHANGED
|
@@ -50,13 +50,14 @@ const formatPattern = (value) => {
|
|
|
50
50
|
}
|
|
51
51
|
};
|
|
52
52
|
|
|
53
|
-
// The formatter of each rule, by name; the names are the rules that exist.
|
|
54
|
-
|
|
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
|
+
const FORMAT = Object.assign(Object.create(null), {
|
|
55
56
|
length: formatLength,
|
|
56
57
|
min: formatLimit('min'),
|
|
57
58
|
max: formatLimit('max'),
|
|
58
59
|
pattern: formatPattern,
|
|
59
|
-
};
|
|
60
|
+
});
|
|
60
61
|
|
|
61
62
|
const notApplicable = (rule, type, rules) => {
|
|
62
63
|
const hint = rule === 'length' && rules.has('min') ? '; use min and max' : '';
|
|
@@ -79,25 +80,39 @@ const codePoints = (text) => {
|
|
|
79
80
|
return count;
|
|
80
81
|
};
|
|
81
82
|
|
|
82
|
-
// The
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
const { size, length } = value;
|
|
88
|
-
if (typeof size === 'number') return size;
|
|
89
|
-
if (typeof length === 'number') return length;
|
|
90
|
-
return Object.keys(value).length;
|
|
83
|
+
// The own keys of an object, counted without a list of them.
|
|
84
|
+
const keyCount = (value) => {
|
|
85
|
+
let count = 0;
|
|
86
|
+
for (const name in value) if (Object.hasOwn(value, name)) count += 1;
|
|
87
|
+
return count;
|
|
91
88
|
};
|
|
92
89
|
|
|
93
|
-
|
|
94
|
-
|
|
90
|
+
// The length of a value, by what the value is rather than by what it carries
|
|
91
|
+
// (an object with a `size` key is an object): the units of a string, the
|
|
92
|
+
// length of an array, the size of a Set or a Map, the own keys of an object.
|
|
93
|
+
const lengthOf = (value) => {
|
|
94
|
+
if (typeof value === 'string' || Array.isArray(value)) return value.length;
|
|
95
|
+
const name = value.constructor?.name;
|
|
96
|
+
return name === 'Set' || name === 'Map' ? value.size : keyCount(value);
|
|
97
|
+
};
|
|
95
98
|
|
|
99
|
+
// A string field measures its units, or its code points when it asks for
|
|
100
|
+
// them; anything else is measured by what it is. One closure per case, each
|
|
101
|
+
// calling its measure directly: a measure held in a variable is a call site
|
|
102
|
+
// shared by every length rule of the process, which V8 then cannot inline.
|
|
96
103
|
const compileLength = (type) => {
|
|
97
104
|
const { min, max } = type.length;
|
|
98
|
-
if (type.
|
|
105
|
+
if (type.scalar === 'string') {
|
|
106
|
+
if (type.unicode === true) {
|
|
107
|
+
return (value, context, key) => {
|
|
108
|
+
const actual = codePoints(value);
|
|
109
|
+
const short = min !== undefined && actual < min;
|
|
110
|
+
const long = max !== undefined && actual > max;
|
|
111
|
+
if (short || long) issues.length(context, min, max, actual, key);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
99
114
|
return (value, context, key) => {
|
|
100
|
-
const actual =
|
|
115
|
+
const actual = value.length;
|
|
101
116
|
const short = min !== undefined && actual < min;
|
|
102
117
|
const long = max !== undefined && actual > max;
|
|
103
118
|
if (short || long) issues.length(context, min, max, actual, key);
|
|
@@ -138,19 +153,33 @@ const compilePattern = (type) => {
|
|
|
138
153
|
};
|
|
139
154
|
};
|
|
140
155
|
|
|
141
|
-
// The
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
156
|
+
// The rules a field carries, by name, in the order its type lists them, min
|
|
157
|
+
// and max as the one `range`: the order the closures run them in and the JIT
|
|
158
|
+
// emits them in.
|
|
159
|
+
const ruleNames = (type) => {
|
|
160
|
+
const names = [];
|
|
145
161
|
let range = false;
|
|
146
|
-
for (const name of rules) {
|
|
162
|
+
for (const name of type.constructor.rules) {
|
|
147
163
|
if (type[name] === undefined) continue;
|
|
148
|
-
if (name === '
|
|
149
|
-
else
|
|
150
|
-
else if (name === 'min' || name === 'max') range = true;
|
|
164
|
+
if (name === 'min' || name === 'max') range = true;
|
|
165
|
+
else names.push(name);
|
|
151
166
|
}
|
|
152
|
-
if (range)
|
|
167
|
+
if (range) names.push('range');
|
|
168
|
+
return names;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const COMPILERS = Object.assign(Object.create(null), {
|
|
172
|
+
length: compileLength,
|
|
173
|
+
pattern: compilePattern,
|
|
174
|
+
range: compileRange,
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
// The checks of the rules a field carries.
|
|
178
|
+
const compileRules = (type) => {
|
|
179
|
+
const names = ruleNames(type);
|
|
180
|
+
const checks = [];
|
|
181
|
+
for (let index = 0; index < names.length; index += 1) checks.push(COMPILERS[names[index]](type));
|
|
153
182
|
return checks;
|
|
154
183
|
};
|
|
155
184
|
|
|
156
|
-
module.exports = { FORMAT, notApplicable, compileRules, codePoints };
|
|
185
|
+
module.exports = { FORMAT, notApplicable, ruleNames, compileRules, codePoints, lengthOf };
|
package/src/runtime/browser.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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 writeFile = () => Promise.reject(new Error('saveTypes is not available in the browser'));
|
|
5
5
|
|
|
6
|
-
module.exports = {
|
|
6
|
+
module.exports = { writeFile };
|
package/src/runtime/node.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
const fsp = require('node:fs').promises;
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// The one file-system call of the package, behind `saveTypes` of the
|
|
4
|
+
// `./generators` subpath.
|
|
5
|
+
const writeFile = (outputFile, text) => fsp.writeFile(outputFile, text);
|
|
4
6
|
|
|
5
|
-
module.exports = {
|
|
7
|
+
module.exports = { writeFile };
|
package/src/schema.js
CHANGED
|
@@ -1,80 +1,16 @@
|
|
|
1
1
|
const { isFirstUpper } = require('./metautil.js');
|
|
2
2
|
|
|
3
|
-
const { BRAND, INSPECT, RUN, hasBrand } = require('./util.js');
|
|
3
|
+
const { BRAND, INSPECT, RUN, HOOK, hasBrand } = require('./util.js');
|
|
4
4
|
const { createContext } = require('./context.js');
|
|
5
5
|
const { TYPES } = require('./types.js');
|
|
6
6
|
const { Preprocessor } = require('./preprocessor.js');
|
|
7
7
|
const { SchemaMetadata } = require('./metadata.js');
|
|
8
8
|
const { ValidationResult } = require('./result.js');
|
|
9
|
-
const { finalize, runValidate } = require('./issues.js');
|
|
9
|
+
const { finalize, runValidate, settle } = require('./issues.js');
|
|
10
10
|
const { SchemaDefinitionError } = require('./errors.js');
|
|
11
11
|
const { createStruct, isStruct, checkOf } = require('./struct.js');
|
|
12
|
-
const { embeds } = require('./prototypes/reference.js');
|
|
13
12
|
const { warning, lintSchema } = require('./lint.js');
|
|
14
|
-
|
|
15
|
-
const TS_SCALARS = {
|
|
16
|
-
string: 'string',
|
|
17
|
-
number: 'number',
|
|
18
|
-
boolean: 'boolean',
|
|
19
|
-
bigint: 'bigint',
|
|
20
|
-
date: 'Date',
|
|
21
|
-
null: 'null',
|
|
22
|
-
any: 'any',
|
|
23
|
-
unknown: 'unknown',
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
const listOf = (element) => (element.includes(' | ') ? `(${element})[]` : `${element}[]`);
|
|
27
|
-
|
|
28
|
-
// Whether a reference field renders as its id (`companyId: string`) or as
|
|
29
|
-
// the referenced type (`company: Company`): the same rule as `check`, with
|
|
30
|
-
// a target that cannot be resolved taken as stored.
|
|
31
|
-
const asId = (def) => {
|
|
32
|
-
const target = def.root.findReference(def.type);
|
|
33
|
-
if (target === null) return def.embed !== true;
|
|
34
|
-
return !embeds(target, def.embed, 'kind');
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
const tsStruct = (fields) => `{ ${tsFields(fields).join('; ')} }`;
|
|
38
|
-
|
|
39
|
-
// The referenced type: its interface by name, inline when it has none, the
|
|
40
|
-
// name of the reference when it cannot be resolved.
|
|
41
|
-
const tsReference = (def) => {
|
|
42
|
-
const target = def.root.findReference(def.type);
|
|
43
|
-
if (target === null || target.name) return def.type;
|
|
44
|
-
const { fields } = target;
|
|
45
|
-
return hasBrand(fields, 'Struct') ? tsStruct(fields) : tsType(fields);
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
// The TypeScript type of a field. A reference to a stored kind is held as
|
|
49
|
-
// an id, so it renders as a string (an array of them for `many`), a
|
|
50
|
-
// reference to a memory kind as the type itself; a custom scalar with its
|
|
51
|
-
// own check has no known shape and renders as a string.
|
|
52
|
-
const tsType = (def) => {
|
|
53
|
-
const type = tsBase(def);
|
|
54
|
-
return def.nullable === true ? `${type} | null` : type;
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
const tsBase = (def) => {
|
|
58
|
-
if (isFirstUpper(def.type)) {
|
|
59
|
-
const element = asId(def) ? 'string' : tsReference(def);
|
|
60
|
-
return def.many ? listOf(element) : element;
|
|
61
|
-
}
|
|
62
|
-
if (def.enum) return def.enum.map((value) => JSON.stringify(value)).join(' | ');
|
|
63
|
-
if (def.union) return def.union.map(tsType).join(' | ');
|
|
64
|
-
if (def.scalar) return TS_SCALARS[def.scalar] || 'string';
|
|
65
|
-
if (def.schema) return tsStruct(def.schema);
|
|
66
|
-
if (Array.isArray(def.value)) return `[${def.value.map(tsType).join(', ')}]`;
|
|
67
|
-
if (def.key !== undefined && def.value) {
|
|
68
|
-
const entries = `${def.key}, ${tsType(def.value)}`;
|
|
69
|
-
return def.isInstance({}) ? `Record<${entries}>` : `Map<${entries}>`;
|
|
70
|
-
}
|
|
71
|
-
if (def.value) {
|
|
72
|
-
const element = tsType(def.value);
|
|
73
|
-
return def.isInstance([]) ? listOf(element) : `Set<${element}>`;
|
|
74
|
-
}
|
|
75
|
-
if (def.kind === 'struct') return 'unknown';
|
|
76
|
-
return 'string';
|
|
77
|
-
};
|
|
13
|
+
const { PREPARE, FINISH, SERIALIZE, infoOf, apply, looped, hasAsync } = require('./codec.js');
|
|
78
14
|
|
|
79
15
|
// The validation of a schema inside an existing context: `check` starts one,
|
|
80
16
|
// and a reference field checks its target entity within the context of the
|
|
@@ -98,26 +34,29 @@ const compileSchema = (schema) => {
|
|
|
98
34
|
};
|
|
99
35
|
};
|
|
100
36
|
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
return lines;
|
|
37
|
+
const resultOf = (context) => {
|
|
38
|
+
finalize(context.issues, context.messages);
|
|
39
|
+
return new ValidationResult(context);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// What parse returns: the output only for a valid value, the issues always.
|
|
43
|
+
const parsed = (context, output) => {
|
|
44
|
+
finalize(context.issues, context.messages);
|
|
45
|
+
const valid = context.count === 0;
|
|
46
|
+
return { valid, value: valid ? output : undefined, issues: context.issues };
|
|
112
47
|
};
|
|
113
48
|
|
|
49
|
+
// The result of parse read as Standard Schema does.
|
|
50
|
+
const standardize = (result) =>
|
|
51
|
+
result.valid ? { value: result.value } : { issues: result.issues };
|
|
52
|
+
|
|
114
53
|
class Schema extends SchemaMetadata {
|
|
115
54
|
// The merged type table of the attached namespaces, rebuilt only when they
|
|
116
55
|
// change.
|
|
117
56
|
#types = null;
|
|
118
57
|
|
|
119
|
-
// Whether the root value joins the cycle detection:
|
|
120
|
-
// references can reach it again.
|
|
58
|
+
// Whether the root value joins the cycle detection (`context.source`):
|
|
59
|
+
// only a struct with references can reach it again.
|
|
121
60
|
#tracked = false;
|
|
122
61
|
|
|
123
62
|
// The lint of the definition, run on first use: a schema built in a hot
|
|
@@ -127,6 +66,9 @@ class Schema extends SchemaMetadata {
|
|
|
127
66
|
// The Standard Schema props, built on first use.
|
|
128
67
|
#standard = null;
|
|
129
68
|
|
|
69
|
+
// What the passes of parse and serialize know about the schema, on first use.
|
|
70
|
+
#codec = null;
|
|
71
|
+
|
|
130
72
|
static from(source, namespaces) {
|
|
131
73
|
return new Schema('', source, namespaces);
|
|
132
74
|
}
|
|
@@ -167,6 +109,8 @@ class Schema extends SchemaMetadata {
|
|
|
167
109
|
}
|
|
168
110
|
this.#tracked = isSchemaType && this.relations.size > 0;
|
|
169
111
|
this[RUN] = compileSchema(this);
|
|
112
|
+
const hook = Schema[HOOK];
|
|
113
|
+
if (hook !== undefined) hook(this);
|
|
170
114
|
}
|
|
171
115
|
|
|
172
116
|
// What is not wrong enough to throw: `Warning [code]: text` strings.
|
|
@@ -177,17 +121,23 @@ class Schema extends SchemaMetadata {
|
|
|
177
121
|
|
|
178
122
|
// Standard Schema v1 (https://standardschema.dev): the interface tRPC,
|
|
179
123
|
// TanStack Form, Hono and the other consumers of the specification validate
|
|
180
|
-
// through.
|
|
181
|
-
//
|
|
182
|
-
//
|
|
183
|
-
//
|
|
124
|
+
// through. `validate` is `parse` with the policies of the schema: the value
|
|
125
|
+
// that comes back has the defaults and the decoders applied (the value
|
|
126
|
+
// itself when there was nothing to apply), and the issues of an invalid one
|
|
127
|
+
// are the result's own (a message and a path of keys each). A schema with
|
|
128
|
+
// an async validator or decoder validates through parseAsync, as the
|
|
129
|
+
// specification allows. The vendor-specific `libraryOptions` of a call are
|
|
130
|
+
// the options of `parse`. An accessor of the prototype stays out of toJSON,
|
|
184
131
|
// inspect and Object.keys, and `validate` closes over the schema because a
|
|
185
|
-
// consumer calls it unbound.
|
|
132
|
+
// consumer calls it unbound. The `./generators` subpath adds the
|
|
133
|
+
// `jsonSchema` converter of Standard JSON Schema to the props.
|
|
186
134
|
get '~standard'() {
|
|
187
135
|
if (this.#standard === null) {
|
|
136
|
+
const async = hasAsync(this);
|
|
188
137
|
const validate = (value, options) => {
|
|
189
|
-
const
|
|
190
|
-
return
|
|
138
|
+
const libraryOptions = options == null ? undefined : options.libraryOptions;
|
|
139
|
+
if (async) return this.parseAsync(value, libraryOptions).then(standardize);
|
|
140
|
+
return standardize(this.parse(value, libraryOptions));
|
|
191
141
|
};
|
|
192
142
|
this.#standard = { version: 1, vendor: 'alexify.metaschema', validate };
|
|
193
143
|
}
|
|
@@ -197,8 +147,9 @@ class Schema extends SchemaMetadata {
|
|
|
197
147
|
get types() {
|
|
198
148
|
if (this.namespaces.size === 0) return TYPES;
|
|
199
149
|
if (this.#types === null) {
|
|
200
|
-
const types =
|
|
201
|
-
this
|
|
150
|
+
const types = Object.create(null);
|
|
151
|
+
for (const ns of this.namespaces) Object.assign(types, ns.types);
|
|
152
|
+
this.#types = types;
|
|
202
153
|
}
|
|
203
154
|
return this.#types;
|
|
204
155
|
}
|
|
@@ -232,33 +183,101 @@ class Schema extends SchemaMetadata {
|
|
|
232
183
|
// Validates a value: every problem is collected as an issue, and the result
|
|
233
184
|
// never throws because of the value. `options`: root (the label of the
|
|
234
185
|
// error lines, the schema name by default), maxErrors, unknown ('reject'
|
|
235
|
-
// or 'ignore' keys the schema does not have), messages (a
|
|
186
|
+
// or 'ignore' keys the schema does not have), references, messages (a
|
|
187
|
+
// locale). A validator that returns a promise is an error here.
|
|
188
|
+
// `createContext` is called directly in every method here, never through a
|
|
189
|
+
// helper: V8 inlines the allocation into `check` that way (the context is
|
|
190
|
+
// the one allocation of a valid check), and a method in between cost 7%.
|
|
236
191
|
check(source, options) {
|
|
237
192
|
const context = createContext(options, this.name, this.unknown);
|
|
238
|
-
if (this.#tracked
|
|
239
|
-
context.seen = new Set();
|
|
240
|
-
context.seen.add(source);
|
|
241
|
-
}
|
|
193
|
+
if (this.#tracked) context.source = source;
|
|
242
194
|
this[RUN](source, context);
|
|
243
|
-
|
|
244
|
-
|
|
195
|
+
return resultOf(context);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// The same check, with the validators that return a promise settled after
|
|
199
|
+
// the walk, in field order.
|
|
200
|
+
async checkAsync(source, options) {
|
|
201
|
+
const context = createContext(options, this.name, this.unknown);
|
|
202
|
+
context.async = [];
|
|
203
|
+
if (this.#tracked) context.source = source;
|
|
204
|
+
this[RUN](source, context);
|
|
205
|
+
if (context.async.length > 0) await settle(context);
|
|
206
|
+
return resultOf(context);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
#pass(phase, source, context) {
|
|
210
|
+
if (this.#codec === null) this.#codec = infoOf(this);
|
|
211
|
+
return apply(this.#codec, this, source, context, undefined, phase);
|
|
245
212
|
}
|
|
246
213
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
214
|
+
// The defaults of the schema over a value, before its check; the objects
|
|
215
|
+
// met on the way down are not the check's, and a value that loops through
|
|
216
|
+
// its references is checked as it was given.
|
|
217
|
+
#prepare(source, context) {
|
|
218
|
+
const prepared = this.#pass(PREPARE, source, context);
|
|
219
|
+
const value = looped(context) ? source : prepared;
|
|
220
|
+
context.seen = null;
|
|
221
|
+
if (this.#tracked) context.source = value;
|
|
222
|
+
return value;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Validates a value and builds the value of the program from it: the
|
|
226
|
+
// defaults fill the missing keys, the check runs, and a valid value goes
|
|
227
|
+
// through `unknown: 'strip'`, the decoders of its fields (the parts of a
|
|
228
|
+
// value before the value) and the schema's own `parse`. `{ valid, value,
|
|
229
|
+
// issues }`: the value is undefined when invalid, and the value given when
|
|
230
|
+
// there was nothing to apply; the value given is never written to.
|
|
231
|
+
parse(source, options) {
|
|
232
|
+
const context = createContext(options, this.name, this.unknown, true);
|
|
233
|
+
const value = this.#prepare(source, context);
|
|
234
|
+
this[RUN](value, context);
|
|
235
|
+
const output = context.count === 0 ? this.#pass(FINISH, value, context) : undefined;
|
|
236
|
+
return parsed(context, output);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async parseAsync(source, options) {
|
|
240
|
+
const context = createContext(options, this.name, this.unknown, true);
|
|
241
|
+
context.async = [];
|
|
242
|
+
const value = this.#prepare(source, context);
|
|
243
|
+
this[RUN](value, context);
|
|
244
|
+
if (context.async.length > 0) await settle(context);
|
|
245
|
+
let output;
|
|
246
|
+
if (context.count === 0) {
|
|
247
|
+
// Only a promise of the pass is awaited: a thenable in the value is data.
|
|
248
|
+
output = this.#pass(FINISH, value, context);
|
|
249
|
+
if (output instanceof Promise) output = (await output).value;
|
|
250
|
+
}
|
|
251
|
+
return parsed(context, output);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The other direction: the schema's own `serialize`, then the serializers
|
|
255
|
+
// of the fields, from the value down to its parts. `{ value }`, or with
|
|
256
|
+
// `options.check` the verdict of `check` over the result as well.
|
|
257
|
+
serialize(source, options) {
|
|
258
|
+
const context = createContext(options, this.name, this.unknown);
|
|
259
|
+
const value = this.#pass(SERIALIZE, source, context);
|
|
260
|
+
if (options === undefined || options.check !== true) return { value };
|
|
261
|
+
context.seen = null;
|
|
262
|
+
if (this.#tracked) context.source = value;
|
|
263
|
+
this[RUN](value, context);
|
|
264
|
+
finalize(context.issues, context.messages);
|
|
265
|
+
return { valid: context.count === 0, value, issues: context.issues };
|
|
252
266
|
}
|
|
253
267
|
|
|
268
|
+
// The types and the Standard Schema props depend on the namespaces (the
|
|
269
|
+
// latter through the entities an async validator may be in), so both are
|
|
270
|
+
// rebuilt on the next use.
|
|
254
271
|
attach(...namespaces) {
|
|
255
272
|
for (const ns of namespaces) this.namespaces.add(ns);
|
|
256
273
|
this.#types = null;
|
|
274
|
+
this.#standard = null;
|
|
257
275
|
}
|
|
258
276
|
|
|
259
277
|
detach(...namespaces) {
|
|
260
278
|
for (const ns of namespaces) this.namespaces.delete(ns);
|
|
261
279
|
this.#types = null;
|
|
280
|
+
this.#standard = null;
|
|
262
281
|
}
|
|
263
282
|
|
|
264
283
|
toString() {
|
package/src/struct.js
CHANGED
|
@@ -4,11 +4,17 @@ const { SchemaDefinitionError } = require('./errors.js');
|
|
|
4
4
|
|
|
5
5
|
// What a struct computes once at construction, kept on the dictionary under a
|
|
6
6
|
// global symbol like BRAND, so a struct built by another copy of the package
|
|
7
|
-
// exposes it too: { plan, known, check }, the plan being one
|
|
8
|
-
// validated field, `known` the dictionary of
|
|
9
|
-
//
|
|
7
|
+
// exposes it too: { plan, known, calculated, check }, the plan being one
|
|
8
|
+
// frozen entry per validated field, `known` the dictionary of the keys a
|
|
9
|
+
// value may carry, `calculated` the keys of the calculated fields among them,
|
|
10
|
+
// and `check` the compiled check over the plan.
|
|
10
11
|
const STRUCT = Symbol.for('alexify.metaschema.struct');
|
|
11
12
|
|
|
13
|
+
// The functions of a nested definition that are the struct's own validate,
|
|
14
|
+
// decoder and serializer (as they are options at the root): they stay in the
|
|
15
|
+
// fields, where a calculated field lives, but a value has no key by that name.
|
|
16
|
+
const CODEC_KEYS = new Set(['validate', 'parse', 'serialize']);
|
|
17
|
+
|
|
12
18
|
// A field is read with a keyed load, and `Object.hasOwn` is consulted only
|
|
13
19
|
// when the value is undefined, to tell a missing key from one set to
|
|
14
20
|
// undefined. A field named after a member of Object.prototype (`toString`,
|
|
@@ -32,7 +38,7 @@ const scanUnknown = (value, known, context) => {
|
|
|
32
38
|
// more keys than the plan found, so a value with exactly the expected keys is
|
|
33
39
|
// never scanned twice.
|
|
34
40
|
const compileStruct = (plan, known) => (value, context, key) => {
|
|
35
|
-
if (value === null || typeof value !== 'object') {
|
|
41
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
36
42
|
issues.type(context, 'object', value, key);
|
|
37
43
|
return;
|
|
38
44
|
}
|
|
@@ -77,14 +83,18 @@ const createStruct = (defs, prep) => {
|
|
|
77
83
|
const fields = Object.create(null);
|
|
78
84
|
const plan = [];
|
|
79
85
|
const known = Object.create(null);
|
|
86
|
+
const calculated = [];
|
|
80
87
|
for (const key of Object.keys(defs)) {
|
|
81
88
|
const entry = defs[key];
|
|
82
89
|
const { field, required } = formatters.key(key, entry?.required);
|
|
83
90
|
try {
|
|
84
91
|
const { Type, defs: typeDefs } = prep.parse(entry);
|
|
85
92
|
if (!Type) {
|
|
86
|
-
fields[
|
|
87
|
-
|
|
93
|
+
fields[field] = entry;
|
|
94
|
+
if (!CODEC_KEYS.has(field)) {
|
|
95
|
+
known[field] = true;
|
|
96
|
+
calculated.push(field);
|
|
97
|
+
}
|
|
88
98
|
continue;
|
|
89
99
|
}
|
|
90
100
|
// The key ('tags?') and the definition ('?string', required: false)
|
|
@@ -107,7 +117,8 @@ const createStruct = (defs, prep) => {
|
|
|
107
117
|
}
|
|
108
118
|
}
|
|
109
119
|
Object.freeze(plan);
|
|
110
|
-
|
|
120
|
+
Object.freeze(calculated);
|
|
121
|
+
const compiled = Object.freeze({ plan, known, calculated, check: compileStruct(plan, known) });
|
|
111
122
|
Object.defineProperty(fields, BRAND, { value: 'Struct' });
|
|
112
123
|
Object.defineProperty(fields, STRUCT, { value: compiled });
|
|
113
124
|
return fields;
|
package/src/types.js
CHANGED
|
@@ -25,17 +25,14 @@ const customTypeError = (name, reason) =>
|
|
|
25
25
|
|
|
26
26
|
const createType = (name, prototype) => {
|
|
27
27
|
class Type extends AbstractType {
|
|
28
|
-
|
|
28
|
+
// A null-prototype dictionary: a metadata key may be anything.
|
|
29
|
+
static metadata = Object.create(null);
|
|
29
30
|
static type = name;
|
|
30
31
|
static kind = prototype.kind;
|
|
31
32
|
static rules = new Set(prototype.rules);
|
|
32
33
|
// The definition keys the type reads; the lint reports the others.
|
|
33
34
|
static options = new Set(prototype.options);
|
|
34
35
|
|
|
35
|
-
static assign(key, value) {
|
|
36
|
-
this.metadata[key] = value;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
36
|
constructor(def, preprocessor) {
|
|
40
37
|
super(def, preprocessor);
|
|
41
38
|
const { type } = this;
|
|
@@ -61,12 +58,9 @@ const TYPES = createTypes(PROTOTYPES);
|
|
|
61
58
|
|
|
62
59
|
const createRegistry = () => createTypes(PROTOTYPES);
|
|
63
60
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const value = pair[1];
|
|
68
|
-
Type.assign(key, value);
|
|
69
|
-
}
|
|
61
|
+
// The own keys of the metadata given, as data: the table has no prototype.
|
|
62
|
+
const updateTypeMetadata = (Type, metadata) => {
|
|
63
|
+
Object.assign(Type.metadata, metadata);
|
|
70
64
|
};
|
|
71
65
|
|
|
72
66
|
// A custom prototype brings `construct` and `checkType`; a built-in one, reused
|
package/src/util.js
CHANGED
|
@@ -9,11 +9,37 @@ const INSPECT = Symbol.for('nodejs.util.inspect.custom');
|
|
|
9
9
|
|
|
10
10
|
const hasBrand = (value, name) => value?.[BRAND] === name;
|
|
11
11
|
|
|
12
|
+
// A JavaScript identifier: what generated code may write as `object.key` and
|
|
13
|
+
// a TypeScript declaration as a bare name.
|
|
14
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
15
|
+
|
|
16
|
+
// Defines an own data property, so a key such as `__proto__` taken from a
|
|
17
|
+
// path or a definition lands on the object instead of changing its prototype.
|
|
18
|
+
const define = (target, key, value) => {
|
|
19
|
+
Object.defineProperty(target, key, {
|
|
20
|
+
value,
|
|
21
|
+
enumerable: true,
|
|
22
|
+
writable: true,
|
|
23
|
+
configurable: true,
|
|
24
|
+
});
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
|
|
12
28
|
// The method that validates a value inside an existing context, shared by
|
|
13
29
|
// Schema and the reference type that checks its target through it. A global
|
|
14
30
|
// symbol like BRAND, so a schema from another copy of the package has it too.
|
|
15
31
|
const RUN = Symbol.for('alexify.metaschema.run');
|
|
16
32
|
|
|
33
|
+
// A slot on the Schema class for a function to call with every schema built
|
|
34
|
+
// (`Schema[HOOK]`): the `./compile` subpath installs its JIT there, so a
|
|
35
|
+
// program that registered it gets every later schema compiled. Nothing in the
|
|
36
|
+
// core sets it, and it is read once per construction, never per check.
|
|
37
|
+
const HOOK = Symbol.for('alexify.metaschema.hook');
|
|
38
|
+
|
|
39
|
+
// Past this many values an enum is checked through a Set instead of a chain
|
|
40
|
+
// of comparisons, on both backends.
|
|
41
|
+
const ENUM_SET_SIZE = 8;
|
|
42
|
+
|
|
17
43
|
// Key names taken from the value under check go into messages; a huge key
|
|
18
44
|
// must not become a huge message.
|
|
19
45
|
const KEY_LIMIT = 100;
|
|
@@ -23,6 +49,14 @@ const shorten = (key) => {
|
|
|
23
49
|
return name.length > KEY_LIMIT ? `${name.slice(0, KEY_LIMIT)}...` : name;
|
|
24
50
|
};
|
|
25
51
|
|
|
52
|
+
// The text of a value that may have none (a symbol, an object without a
|
|
53
|
+
// prototype), for a message: what a validator threw or returned is anything.
|
|
54
|
+
const safeString = (value) => {
|
|
55
|
+
if (typeof value === 'symbol') return value.toString();
|
|
56
|
+
const bare = value !== null && typeof value === 'object' && typeof value.toString !== 'function';
|
|
57
|
+
return bare ? Object.prototype.toString.call(value) : String(value);
|
|
58
|
+
};
|
|
59
|
+
|
|
26
60
|
const formatters = {
|
|
27
61
|
type: (type, req = true) => {
|
|
28
62
|
const required = !type.startsWith('?');
|
|
@@ -43,7 +77,12 @@ module.exports = {
|
|
|
43
77
|
BRAND,
|
|
44
78
|
INSPECT,
|
|
45
79
|
hasBrand,
|
|
80
|
+
IDENTIFIER,
|
|
81
|
+
define,
|
|
46
82
|
RUN,
|
|
83
|
+
HOOK,
|
|
84
|
+
ENUM_SET_SIZE,
|
|
47
85
|
shorten,
|
|
86
|
+
safeString,
|
|
48
87
|
formatters,
|
|
49
88
|
};
|