@alexify/metaschema 3.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 +120 -1
- package/README.md +11 -4
- package/index.d.ts +219 -2
- package/package.json +6 -2
- package/src/codec.js +88 -34
- package/src/compile/emit.js +28 -0
- package/src/compile/index.js +2 -2
- package/src/context.js +3 -0
- package/src/errors.js +10 -1
- package/src/generators/fromjsonschema.js +520 -0
- package/src/generators/index.d.ts +19 -2
- package/src/generators/index.js +14 -9
- package/src/lint.js +12 -3
- 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 +8 -0
- package/src/preprocessor.js +4 -1
- package/src/prototypes/schema.js +6 -5
- package/src/schema.js +11 -2
- package/src/snapshot.js +111 -0
- package/src/struct.js +63 -17
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
// The other direction of the JSON Schema generator: a definition (or a
|
|
2
|
+
// Schema) from a JSON Schema document, for the subset a validation schema is
|
|
3
|
+
// made of: types, properties and required, enum and const, items and tuples,
|
|
4
|
+
// anyOf/oneOf as a union, `$ref` into the definitions, the rules (`minLength`,
|
|
5
|
+
// `maximum`, `minItems`, ...), null as nullable or optional, and the
|
|
6
|
+
// annotations. A keyword outside it (`allOf` with several schemas, `not`,
|
|
7
|
+
// `if`, `patternProperties`, `exclusiveMinimum`, ...) is ERR_UNSUPPORTED_SCHEMA
|
|
8
|
+
// with its place in the document, or dropped with `unsupported: 'ignore'`.
|
|
9
|
+
// The document is untrusted input: a pointer reads own keys only, a `$ref` is
|
|
10
|
+
// converted once per pointer, and the nesting is bounded.
|
|
11
|
+
const { isFirstUpper } = require('../metautil.js');
|
|
12
|
+
const { define } = require('../util.js');
|
|
13
|
+
const { Schema } = require('../schema.js');
|
|
14
|
+
const { TYPES } = require('../types.js');
|
|
15
|
+
const { SchemaDefinitionError, invalidTarget } = require('../errors.js');
|
|
16
|
+
|
|
17
|
+
const invalidOptions = (reason) => new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
|
|
18
|
+
|
|
19
|
+
// The keys of a JSON object are strings, so a number key is this pattern.
|
|
20
|
+
const NUMBER_KEY = '^-?\\d+(\\.\\d+)?$';
|
|
21
|
+
|
|
22
|
+
// Keywords that say nothing about the value: identifiers, comments and the
|
|
23
|
+
// annotations with no counterpart (`format` is an annotation in JSON Schema
|
|
24
|
+
// unless the dialect asserts it, and metaschema has `pattern` for that).
|
|
25
|
+
const IGNORED = new Set([
|
|
26
|
+
'$schema',
|
|
27
|
+
'$id',
|
|
28
|
+
'$comment',
|
|
29
|
+
'$defs',
|
|
30
|
+
'definitions',
|
|
31
|
+
'components',
|
|
32
|
+
'format',
|
|
33
|
+
'readOnly',
|
|
34
|
+
'writeOnly',
|
|
35
|
+
'contentMediaType',
|
|
36
|
+
'contentEncoding',
|
|
37
|
+
'additionalProperties',
|
|
38
|
+
'nullable',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
const ANNOTATIONS = ['title', 'description', 'default', 'examples', 'deprecated'];
|
|
42
|
+
|
|
43
|
+
// The types a node may name: those of JSON Schema, and the two the keywords
|
|
44
|
+
// of a node without a `type` are read as.
|
|
45
|
+
const KNOWN = new Set([
|
|
46
|
+
'string',
|
|
47
|
+
'number',
|
|
48
|
+
'integer',
|
|
49
|
+
'boolean',
|
|
50
|
+
'null',
|
|
51
|
+
'object',
|
|
52
|
+
'array',
|
|
53
|
+
'any',
|
|
54
|
+
'json',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
// How deep a document may nest: past it the conversion stops whatever the
|
|
58
|
+
// mode, since a lenient conversion must not recurse without end either.
|
|
59
|
+
const MAX_DEPTH = 128;
|
|
60
|
+
|
|
61
|
+
const option = (options, name, allowed) => {
|
|
62
|
+
const value = options[name];
|
|
63
|
+
if (value === undefined) return allowed[0];
|
|
64
|
+
if (!allowed.includes(value)) {
|
|
65
|
+
let list = '';
|
|
66
|
+
for (let index = 0; index < allowed.length; index += 1) {
|
|
67
|
+
list += `${index === 0 ? '' : ', '}${JSON.stringify(allowed[index])}`;
|
|
68
|
+
}
|
|
69
|
+
throw invalidOptions(`Option "${name}" must be one of ${list}, got ${JSON.stringify(value)}`);
|
|
70
|
+
}
|
|
71
|
+
return value;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const createContext = (document, options) => {
|
|
75
|
+
if (options === null || typeof options !== 'object') {
|
|
76
|
+
throw invalidOptions('Options must be an object');
|
|
77
|
+
}
|
|
78
|
+
const { name = '', onUnsupported } = options;
|
|
79
|
+
if (typeof name !== 'string') throw invalidOptions('Option "name" must be a string');
|
|
80
|
+
if (onUnsupported !== undefined && typeof onUnsupported !== 'function') {
|
|
81
|
+
throw invalidOptions('Option "onUnsupported" must be a function');
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
document,
|
|
85
|
+
name,
|
|
86
|
+
as: option(options, 'as', ['definition', 'schema']),
|
|
87
|
+
references: option(options, 'references', ['inline', 'name']),
|
|
88
|
+
lenient: option(options, 'unsupported', ['throw', 'ignore']) === 'ignore',
|
|
89
|
+
onUnsupported,
|
|
90
|
+
// The place in the document, as the segments of a JSON pointer.
|
|
91
|
+
path: [],
|
|
92
|
+
// How many nodes the conversion is inside.
|
|
93
|
+
depth: 0,
|
|
94
|
+
// The pointers of the definitions being inlined, so that a cycle is found.
|
|
95
|
+
stack: new Set(),
|
|
96
|
+
// The definitions inlined so far, by pointer: a `$ref` met again is the
|
|
97
|
+
// same definition, not a second walk of the document.
|
|
98
|
+
cache: new Map(),
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// The place in the document as a JSON pointer (RFC 6901).
|
|
103
|
+
const pointerOf = (path) => {
|
|
104
|
+
let pointer = '';
|
|
105
|
+
for (const segment of path) {
|
|
106
|
+
pointer += `/${String(segment).replace(/~/g, '~0').replace(/\//g, '~1')}`;
|
|
107
|
+
}
|
|
108
|
+
return pointer;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// A node outside the subset: the error with its place, or a drop that
|
|
112
|
+
// `onUnsupported` is told of (in the throw mode the error carries both).
|
|
113
|
+
const unsupported = (context, what) => {
|
|
114
|
+
const where = pointerOf(context.path);
|
|
115
|
+
if (context.lenient) {
|
|
116
|
+
if (context.onUnsupported !== undefined) context.onUnsupported(what, where);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const reason = `${what} is not supported in a JSON Schema at "${where}"`;
|
|
120
|
+
throw new SchemaDefinitionError('ERR_UNSUPPORTED_SCHEMA', reason);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
124
|
+
|
|
125
|
+
// A JSON Schema pattern is ECMA-262 without the `u` flag, and the rule of a
|
|
126
|
+
// field compiles with it, so a pattern that does not compile under the flag
|
|
127
|
+
// has no form here.
|
|
128
|
+
const compilesWithU = (pattern) => {
|
|
129
|
+
try {
|
|
130
|
+
RegExp(pattern, 'u');
|
|
131
|
+
return true;
|
|
132
|
+
} catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// A struct key that the first-key rule reads as something else needs the
|
|
138
|
+
// `schema` shorthand around the struct.
|
|
139
|
+
const safeFirstKey = (fields) => {
|
|
140
|
+
const first = Object.keys(fields)[0];
|
|
141
|
+
if (first === undefined) return true;
|
|
142
|
+
const key = first.endsWith('?') ? first.slice(0, -1) : first;
|
|
143
|
+
return key !== 'type' && TYPES[key] === undefined && !isFirstUpper(key);
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// A definition of a type with no other key is its name.
|
|
147
|
+
const compact = (def, required) => {
|
|
148
|
+
const keys = Object.keys(def);
|
|
149
|
+
if (keys.length === 1 && typeof def.type === 'string') {
|
|
150
|
+
return required ? def.type : `?${def.type}`;
|
|
151
|
+
}
|
|
152
|
+
if (!required) def.required = false;
|
|
153
|
+
return def;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const annotate = (def, node) => {
|
|
157
|
+
for (const name of ANNOTATIONS) if (node[name] !== undefined) def[name] = node[name];
|
|
158
|
+
if (node.example !== undefined && def.examples === undefined) def.examples = [node.example];
|
|
159
|
+
return def;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// A JSON pointer into the document (RFC 6901 as a URI fragment): `#`, or
|
|
163
|
+
// `#/$defs/Name` and the like, read through own keys only, so that
|
|
164
|
+
// `#/__proto__` or `#/constructor` finds nothing. The target is known by its
|
|
165
|
+
// decoded pointer, under which `A` and `%41` are one name, and two pointers
|
|
166
|
+
// that end alike are two.
|
|
167
|
+
const resolve = (context, ref) => {
|
|
168
|
+
if (typeof ref !== 'string' || (ref !== '#' && !ref.startsWith('#/'))) {
|
|
169
|
+
unsupported(context, `The reference ${JSON.stringify(ref)}`);
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
if (ref === '#') return { pointer: '', name: context.name, node: context.document };
|
|
173
|
+
const segments = ref.slice(2).split('/');
|
|
174
|
+
const keys = [];
|
|
175
|
+
let node = context.document;
|
|
176
|
+
for (const segment of segments) {
|
|
177
|
+
let key;
|
|
178
|
+
try {
|
|
179
|
+
key = decodeURIComponent(segment);
|
|
180
|
+
} catch {
|
|
181
|
+
unsupported(context, `The reference ${JSON.stringify(ref)} (a bad escape)`);
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
key = key.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
185
|
+
keys.push(key);
|
|
186
|
+
node = isObject(node) && Object.hasOwn(node, key) ? node[key] : undefined;
|
|
187
|
+
}
|
|
188
|
+
if (node === undefined) {
|
|
189
|
+
unsupported(context, `The reference ${JSON.stringify(ref)} (nothing there)`);
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
return { pointer: pointerOf(keys), name: keys[keys.length - 1], node };
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// A `$ref` inlined is converted once per pointer: the places that inline it
|
|
196
|
+
// share the converted subtree and get a copy of its top-level object, which
|
|
197
|
+
// is the one the annotations, `nullable` and `required` of the place are
|
|
198
|
+
// written to. A copy of the subtree would be as large as the output, which a
|
|
199
|
+
// diamond of definitions makes exponential.
|
|
200
|
+
const reference = (context, node) => {
|
|
201
|
+
const target = resolve(context, node.$ref);
|
|
202
|
+
if (target === null) return 'any';
|
|
203
|
+
const { pointer, name } = target;
|
|
204
|
+
if (context.references === 'name' || target.node === context.document) {
|
|
205
|
+
if (!isFirstUpper(name)) {
|
|
206
|
+
unsupported(context, `The reference ${JSON.stringify(node.$ref)} (not an entity name)`);
|
|
207
|
+
return 'any';
|
|
208
|
+
}
|
|
209
|
+
return name;
|
|
210
|
+
}
|
|
211
|
+
let def = context.cache.get(pointer);
|
|
212
|
+
if (def === undefined) {
|
|
213
|
+
if (context.stack.has(pointer)) {
|
|
214
|
+
unsupported(context, `The recursive reference ${JSON.stringify(node.$ref)}`);
|
|
215
|
+
return 'any';
|
|
216
|
+
}
|
|
217
|
+
context.stack.add(pointer);
|
|
218
|
+
def = longOf(context, target.node);
|
|
219
|
+
context.stack.delete(pointer);
|
|
220
|
+
context.cache.set(pointer, def);
|
|
221
|
+
}
|
|
222
|
+
return { ...def };
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const structOf = (context, node, used) => {
|
|
226
|
+
const { properties, required = [] } = node;
|
|
227
|
+
used.add('properties');
|
|
228
|
+
used.add('required');
|
|
229
|
+
if (!Array.isArray(required)) unsupported(context, 'A "required" that is not a list');
|
|
230
|
+
const fields = {};
|
|
231
|
+
context.path.push('properties');
|
|
232
|
+
for (const key of Object.keys(properties)) {
|
|
233
|
+
context.path.push(key);
|
|
234
|
+
const def = convert(
|
|
235
|
+
context,
|
|
236
|
+
properties[key],
|
|
237
|
+
Array.isArray(required) && required.includes(key),
|
|
238
|
+
);
|
|
239
|
+
context.path.pop();
|
|
240
|
+
define(fields, key, def);
|
|
241
|
+
}
|
|
242
|
+
context.path.pop();
|
|
243
|
+
return fields;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// A JSON Schema type as a definition: the rules of the type, then the rest.
|
|
247
|
+
const typed = (context, node, type, used) => {
|
|
248
|
+
const def = { type };
|
|
249
|
+
const take = (name) => {
|
|
250
|
+
used.add(name);
|
|
251
|
+
return node[name];
|
|
252
|
+
};
|
|
253
|
+
if (type === 'string') {
|
|
254
|
+
const min = take('minLength');
|
|
255
|
+
const max = take('maxLength');
|
|
256
|
+
if (min !== undefined || max !== undefined) def.length = { min, max };
|
|
257
|
+
const pattern = take('pattern');
|
|
258
|
+
if (pattern !== undefined) {
|
|
259
|
+
if (typeof pattern !== 'string') unsupported(context, 'A "pattern" that is not a string');
|
|
260
|
+
else if (compilesWithU(pattern)) def.pattern = pattern;
|
|
261
|
+
else {
|
|
262
|
+
const shown = JSON.stringify(pattern);
|
|
263
|
+
unsupported(context, `The pattern ${shown} (not a valid pattern under the u flag)`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return def;
|
|
267
|
+
}
|
|
268
|
+
if (type === 'number' || type === 'integer') {
|
|
269
|
+
const min = take('minimum');
|
|
270
|
+
const max = take('maximum');
|
|
271
|
+
if (min !== undefined) def.min = min;
|
|
272
|
+
if (max !== undefined) def.max = max;
|
|
273
|
+
return def;
|
|
274
|
+
}
|
|
275
|
+
if (type === 'array') {
|
|
276
|
+
const items = take('items');
|
|
277
|
+
const prefix = take('prefixItems');
|
|
278
|
+
const min = take('minItems');
|
|
279
|
+
const max = take('maxItems');
|
|
280
|
+
const elements = Array.isArray(prefix) ? prefix : Array.isArray(items) ? items : null;
|
|
281
|
+
if (elements !== null) {
|
|
282
|
+
// A tuple: the elements up to minItems are required, the rest optional.
|
|
283
|
+
take('additionalItems');
|
|
284
|
+
if (items !== false && !Array.isArray(items) && items !== undefined) {
|
|
285
|
+
unsupported(context, 'A tuple with more items');
|
|
286
|
+
}
|
|
287
|
+
def.type = 'tuple';
|
|
288
|
+
def.value = [];
|
|
289
|
+
const key = Array.isArray(prefix) ? 'prefixItems' : 'items';
|
|
290
|
+
context.path.push(key);
|
|
291
|
+
for (let index = 0; index < elements.length; index += 1) {
|
|
292
|
+
context.path.push(index);
|
|
293
|
+
def.value.push(convert(context, elements[index], min === undefined || index < min));
|
|
294
|
+
context.path.pop();
|
|
295
|
+
}
|
|
296
|
+
context.path.pop();
|
|
297
|
+
return def;
|
|
298
|
+
}
|
|
299
|
+
def.type = take('uniqueItems') === true ? 'set' : 'array';
|
|
300
|
+
context.path.push('items');
|
|
301
|
+
def.value = items === undefined ? 'any' : convert(context, items);
|
|
302
|
+
context.path.pop();
|
|
303
|
+
if (min !== undefined || max !== undefined) def.length = { min, max };
|
|
304
|
+
return def;
|
|
305
|
+
}
|
|
306
|
+
if (type === 'object') {
|
|
307
|
+
const min = take('minProperties');
|
|
308
|
+
const max = take('maxProperties');
|
|
309
|
+
if (isObject(node.properties)) {
|
|
310
|
+
def.type = 'schema';
|
|
311
|
+
def.schema = structOf(context, node, used);
|
|
312
|
+
if (min !== undefined || max !== undefined) {
|
|
313
|
+
unsupported(context, 'A struct with minProperties or maxProperties');
|
|
314
|
+
}
|
|
315
|
+
return def;
|
|
316
|
+
}
|
|
317
|
+
const { additionalProperties: values } = node;
|
|
318
|
+
if (values === undefined || values === true) return { type: 'json' };
|
|
319
|
+
if (values === false) unsupported(context, 'An object with no properties');
|
|
320
|
+
def.type = 'object';
|
|
321
|
+
def.key = 'string';
|
|
322
|
+
const names = take('propertyNames');
|
|
323
|
+
if (names !== undefined) {
|
|
324
|
+
if (isObject(names) && names.pattern === NUMBER_KEY) def.key = 'number';
|
|
325
|
+
else unsupported(context, 'A "propertyNames" other than the number key pattern');
|
|
326
|
+
}
|
|
327
|
+
context.path.push('additionalProperties');
|
|
328
|
+
def.value = convert(context, values);
|
|
329
|
+
context.path.pop();
|
|
330
|
+
if (min !== undefined || max !== undefined) def.length = { min, max };
|
|
331
|
+
return def;
|
|
332
|
+
}
|
|
333
|
+
return def;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// The branches of an anyOf or oneOf: null among them makes the value
|
|
337
|
+
// nullable, one branch is that branch, more are a union (with OpenAPI's
|
|
338
|
+
// discriminator when the node has one).
|
|
339
|
+
const branches = (context, node, key, used) => {
|
|
340
|
+
used.add(key);
|
|
341
|
+
const list = node[key];
|
|
342
|
+
const defs = [];
|
|
343
|
+
let nullable = false;
|
|
344
|
+
context.path.push(key);
|
|
345
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
346
|
+
const branch = list[index];
|
|
347
|
+
if (isObject(branch) && branch.type === 'null' && Object.keys(branch).length === 1) {
|
|
348
|
+
nullable = true;
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
context.path.push(index);
|
|
352
|
+
defs.push(longOf(context, branch));
|
|
353
|
+
context.path.pop();
|
|
354
|
+
}
|
|
355
|
+
context.path.pop();
|
|
356
|
+
if (defs.length === 0) return { def: { type: 'null' }, nullable: false };
|
|
357
|
+
if (defs.length === 1) return { def: defs[0], nullable };
|
|
358
|
+
const def = { type: 'union', union: [] };
|
|
359
|
+
for (const branch of defs) def.union.push(compactDef(branch, true));
|
|
360
|
+
const { discriminator } = node;
|
|
361
|
+
if (discriminator !== undefined) {
|
|
362
|
+
used.add('discriminator');
|
|
363
|
+
if (isObject(discriminator) && typeof discriminator.propertyName === 'string') {
|
|
364
|
+
def.discriminator = discriminator.propertyName;
|
|
365
|
+
} else unsupported(context, 'A discriminator without a propertyName');
|
|
366
|
+
}
|
|
367
|
+
return { def, nullable };
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// A node of the document as a definition object `{ type, ... }`.
|
|
371
|
+
const nodeOf = (context, node, used) => {
|
|
372
|
+
if (node.$ref !== undefined) {
|
|
373
|
+
used.add('$ref');
|
|
374
|
+
const def = reference(context, node);
|
|
375
|
+
return typeof def === 'string' ? { type: def } : def;
|
|
376
|
+
}
|
|
377
|
+
if (Array.isArray(node.allOf)) {
|
|
378
|
+
used.add('allOf');
|
|
379
|
+
if (node.allOf.length !== 1) {
|
|
380
|
+
unsupported(context, 'An "allOf" of several schemas');
|
|
381
|
+
return { type: 'any' };
|
|
382
|
+
}
|
|
383
|
+
context.path.push('allOf', 0);
|
|
384
|
+
const def = longOf(context, node.allOf[0]);
|
|
385
|
+
context.path.splice(-2, 2);
|
|
386
|
+
return def;
|
|
387
|
+
}
|
|
388
|
+
if (Array.isArray(node.anyOf) || Array.isArray(node.oneOf)) {
|
|
389
|
+
const key = Array.isArray(node.anyOf) ? 'anyOf' : 'oneOf';
|
|
390
|
+
const { def, nullable } = branches(context, node, key, used);
|
|
391
|
+
if (nullable) def.nullable = true;
|
|
392
|
+
return def;
|
|
393
|
+
}
|
|
394
|
+
if (node.enum !== undefined || node.const !== undefined) {
|
|
395
|
+
used.add('enum');
|
|
396
|
+
used.add('const');
|
|
397
|
+
const values = node.enum === undefined ? [node.const] : node.enum;
|
|
398
|
+
if (!Array.isArray(values)) {
|
|
399
|
+
unsupported(context, 'An "enum" that is not a list');
|
|
400
|
+
return { type: 'any' };
|
|
401
|
+
}
|
|
402
|
+
const def = { type: 'enum', enum: [] };
|
|
403
|
+
for (const value of values) {
|
|
404
|
+
if (value === null) def.nullable = true;
|
|
405
|
+
else def.enum.push(value);
|
|
406
|
+
}
|
|
407
|
+
if (def.enum.length === 0) return { type: 'null' };
|
|
408
|
+
return def;
|
|
409
|
+
}
|
|
410
|
+
used.add('type');
|
|
411
|
+
let { type } = node;
|
|
412
|
+
let nullable = false;
|
|
413
|
+
if (Array.isArray(type)) {
|
|
414
|
+
const rest = [];
|
|
415
|
+
for (const name of type) if (name !== 'null') rest.push(name);
|
|
416
|
+
nullable = rest.length !== type.length;
|
|
417
|
+
for (const name of rest) {
|
|
418
|
+
if (!KNOWN.has(name)) {
|
|
419
|
+
unsupported(context, `The type ${JSON.stringify(name)}`);
|
|
420
|
+
return { type: 'any' };
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (rest.length === 2 && rest.includes('object') && rest.includes('array')) type = 'json';
|
|
424
|
+
else if (rest.length === 1) type = rest[0];
|
|
425
|
+
else if (rest.length === 0) type = 'null';
|
|
426
|
+
else {
|
|
427
|
+
const def = { type: 'union', union: [] };
|
|
428
|
+
for (const name of rest) def.union.push(typed(context, node, name, used));
|
|
429
|
+
if (nullable) def.nullable = true;
|
|
430
|
+
return def;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (type === undefined) {
|
|
434
|
+
if (isObject(node.properties)) type = 'object';
|
|
435
|
+
else if (node.items !== undefined || node.prefixItems !== undefined) type = 'array';
|
|
436
|
+
else if (
|
|
437
|
+
node.pattern !== undefined ||
|
|
438
|
+
node.minLength !== undefined ||
|
|
439
|
+
node.maxLength !== undefined
|
|
440
|
+
) {
|
|
441
|
+
type = 'string';
|
|
442
|
+
} else if (node.minimum !== undefined || node.maximum !== undefined) type = 'number';
|
|
443
|
+
else type = 'any';
|
|
444
|
+
}
|
|
445
|
+
if (!KNOWN.has(type)) {
|
|
446
|
+
unsupported(context, `The type ${JSON.stringify(type)}`);
|
|
447
|
+
return { type: 'any' };
|
|
448
|
+
}
|
|
449
|
+
const def = type === 'json' ? { type: 'json' } : typed(context, node, type, used);
|
|
450
|
+
if (nullable) def.nullable = true;
|
|
451
|
+
return def;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// A node as a definition in the long form `{ type, ... }`: the type and its
|
|
455
|
+
// rules, null as `nullable`, the annotations, and the keywords left over
|
|
456
|
+
// reported. Every nested node comes through here, so this is where the
|
|
457
|
+
// nesting is counted.
|
|
458
|
+
const longOf = (context, node) => {
|
|
459
|
+
if (context.depth > MAX_DEPTH) {
|
|
460
|
+
const where = pointerOf(context.path);
|
|
461
|
+
const reason = `Nesting deeper than ${MAX_DEPTH} levels at "${where}"`;
|
|
462
|
+
throw new SchemaDefinitionError('ERR_UNSUPPORTED_SCHEMA', reason);
|
|
463
|
+
}
|
|
464
|
+
if (node === true || (isObject(node) && Object.keys(node).length === 0)) return { type: 'any' };
|
|
465
|
+
if (node === false) {
|
|
466
|
+
unsupported(context, 'The schema false');
|
|
467
|
+
return { type: 'any' };
|
|
468
|
+
}
|
|
469
|
+
if (!isObject(node)) {
|
|
470
|
+
unsupported(context, `A schema that is ${JSON.stringify(node)}`);
|
|
471
|
+
return { type: 'any' };
|
|
472
|
+
}
|
|
473
|
+
const used = new Set(ANNOTATIONS);
|
|
474
|
+
used.add('example');
|
|
475
|
+
context.depth += 1;
|
|
476
|
+
const def = nodeOf(context, node, used);
|
|
477
|
+
context.depth -= 1;
|
|
478
|
+
for (const key of Object.keys(node)) {
|
|
479
|
+
if (!used.has(key) && !IGNORED.has(key)) unsupported(context, `The keyword "${key}"`);
|
|
480
|
+
}
|
|
481
|
+
if (node.nullable === true) def.nullable = true;
|
|
482
|
+
return annotate(def, node);
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
// A definition as a field holds it: a nested struct as its fields (unless
|
|
486
|
+
// its first key would read as something else), a type with no other key as
|
|
487
|
+
// its name, an optional field as `?name` or `required: false`; an optional
|
|
488
|
+
// field accepts null anyway, so `nullable` is dropped from it.
|
|
489
|
+
const compactDef = (def, required) => {
|
|
490
|
+
if (def.nullable === true && !required) delete def.nullable;
|
|
491
|
+
if (def.type === 'schema' && Object.keys(def).length === 2) {
|
|
492
|
+
const { schema } = def;
|
|
493
|
+
if (safeFirstKey(schema)) return required ? schema : { schema, required: false };
|
|
494
|
+
return required ? { schema } : { schema, required: false };
|
|
495
|
+
}
|
|
496
|
+
return compact(def, required);
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
const convert = (context, node, required = true) => compactDef(longOf(context, node), required);
|
|
500
|
+
|
|
501
|
+
// The root: a struct with its kind, the unknown-keys policy
|
|
502
|
+
// (`additionalProperties: false` closes it, as the generator writes it) and
|
|
503
|
+
// its annotations as the metadata of the kind, or the definition of one type.
|
|
504
|
+
const fromJSONSchema = (document, options = {}) => {
|
|
505
|
+
const context = createContext(document, options);
|
|
506
|
+
if (!isObject(document) && document !== true) {
|
|
507
|
+
throw invalidTarget('A JSON Schema document (an object) is expected');
|
|
508
|
+
}
|
|
509
|
+
const def = longOf(context, document);
|
|
510
|
+
let definition;
|
|
511
|
+
if (def.type === 'schema') {
|
|
512
|
+
const { schema, type, nullable, ...rest } = def;
|
|
513
|
+
const meta = document.additionalProperties === false ? rest : { unknown: 'ignore', ...rest };
|
|
514
|
+
definition = { Struct: meta };
|
|
515
|
+
for (const key of Object.keys(schema)) define(definition, key, schema[key]);
|
|
516
|
+
} else definition = compact(def, true);
|
|
517
|
+
return context.as === 'schema' ? new Schema(context.name, definition) : definition;
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
module.exports = { fromJSONSchema };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type {
|
|
2
|
+
FromJSONSchemaOptions,
|
|
2
3
|
InterfaceOptions,
|
|
3
4
|
JSONSchema,
|
|
4
5
|
JSONSchemaOptions,
|
|
@@ -23,7 +24,23 @@ export function saveTypes(
|
|
|
23
24
|
options?: InterfaceOptions,
|
|
24
25
|
): Promise<void>;
|
|
25
26
|
|
|
27
|
+
// A definition from a JSON Schema document (a Schema with `as: 'schema'`),
|
|
28
|
+
// for the subset a validation schema is made of; a keyword outside it is
|
|
29
|
+
// `ERR_UNSUPPORTED_SCHEMA` with its place in the document, or dropped with
|
|
30
|
+
// `unsupported: 'ignore'` (and told to `onUnsupported`). The document is
|
|
31
|
+
// untrusted input: a `$ref` is converted once per pointer, a pointer reads
|
|
32
|
+
// own keys only, and a nesting deeper than 128 levels is refused in both
|
|
33
|
+
// modes.
|
|
34
|
+
export function fromJSONSchema(
|
|
35
|
+
document: JSONSchema | true,
|
|
36
|
+
options: FromJSONSchemaOptions & { as: 'schema' },
|
|
37
|
+
): Schema;
|
|
38
|
+
export function fromJSONSchema(
|
|
39
|
+
document: JSONSchema | true,
|
|
40
|
+
options?: FromJSONSchemaOptions,
|
|
41
|
+
): object | string;
|
|
42
|
+
|
|
26
43
|
// Installs `schema.toJSONSchema`, `schema.toInterface`, `model.toJSONSchema`,
|
|
27
|
-
// `model.toTypeScript`, `model.dts` and
|
|
28
|
-
// Once per process; later calls do nothing.
|
|
44
|
+
// `model.toTypeScript`, `model.dts`, `Schema.fromJSONSchema` and
|
|
45
|
+
// `schema['~standard'].jsonSchema`. Once per process; later calls do nothing.
|
|
29
46
|
export function register(): void;
|
package/src/generators/index.js
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
// The `./generators` subpath: what a schema or a model is rendered into
|
|
2
|
-
// (JSON Schema, TypeScript)
|
|
3
|
-
//
|
|
4
|
-
// Model; `register()` installs them as
|
|
5
|
-
// converter on `~standard`, for the
|
|
2
|
+
// (JSON Schema, TypeScript) and read from (a JSON Schema document), kept out
|
|
3
|
+
// of the core entry so that a program that only validates does not carry
|
|
4
|
+
// it. The functions take a Schema or a Model; `register()` installs them as
|
|
5
|
+
// methods, and the Standard JSON Schema converter on `~standard`, for the
|
|
6
|
+
// programs that want the methods.
|
|
6
7
|
const { hasBrand } = require('../util.js');
|
|
8
|
+
const { invalidTarget } = require('../errors.js');
|
|
7
9
|
const { Schema } = require('../schema.js');
|
|
8
10
|
const { Model } = require('../model.js');
|
|
9
11
|
const { writeFile } = require('../runtime/node.js');
|
|
10
12
|
const generators = require('./jsonschema.js');
|
|
11
13
|
const typescript = require('./typescript.js');
|
|
14
|
+
const { fromJSONSchema } = require('./fromjsonschema.js');
|
|
12
15
|
|
|
13
16
|
const isModel = (target) => {
|
|
14
17
|
if (hasBrand(target, 'Schema')) return false;
|
|
15
18
|
if (hasBrand(target, 'Model')) return true;
|
|
16
|
-
throw
|
|
19
|
+
throw invalidTarget('A Schema or a Model is expected');
|
|
17
20
|
};
|
|
18
21
|
|
|
19
22
|
// The JSON Schema document of a schema, or of a model (every entity as a
|
|
@@ -69,14 +72,16 @@ const install = (prototype, members) => {
|
|
|
69
72
|
let registered = false;
|
|
70
73
|
|
|
71
74
|
// Adds `toJSONSchema` and `toInterface` to every schema, `toJSONSchema`,
|
|
72
|
-
// `toTypeScript` and `dts` to every model, and the
|
|
73
|
-
// Standard JSON Schema to `schema['~standard']`
|
|
74
|
-
// top of the props the core builds). Once per
|
|
75
|
+
// `toTypeScript` and `dts` to every model, `Schema.fromJSONSchema`, and the
|
|
76
|
+
// `jsonSchema` converter of Standard JSON Schema to `schema['~standard']`
|
|
77
|
+
// (built once per schema, on top of the props the core builds). Once per
|
|
78
|
+
// process.
|
|
75
79
|
const register = () => {
|
|
76
80
|
if (registered) return;
|
|
77
81
|
registered = true;
|
|
78
82
|
install(Schema.prototype, schemaMethods);
|
|
79
83
|
install(Model.prototype, modelMethods);
|
|
84
|
+
install(Schema, { fromJSONSchema });
|
|
80
85
|
const standard = Object.getOwnPropertyDescriptor(Schema.prototype, '~standard');
|
|
81
86
|
const { get } = standard;
|
|
82
87
|
standard.get = function withConverter() {
|
|
@@ -87,4 +92,4 @@ const register = () => {
|
|
|
87
92
|
Object.defineProperty(Schema.prototype, '~standard', standard);
|
|
88
93
|
};
|
|
89
94
|
|
|
90
|
-
module.exports = { toJSONSchema, toTypeScript, saveTypes, register };
|
|
95
|
+
module.exports = { toJSONSchema, toTypeScript, saveTypes, fromJSONSchema, register };
|
package/src/lint.js
CHANGED
|
@@ -26,19 +26,28 @@ const KNOWN = new Set([
|
|
|
26
26
|
'description',
|
|
27
27
|
'examples',
|
|
28
28
|
'deprecated',
|
|
29
|
+
'aliases',
|
|
29
30
|
]);
|
|
30
31
|
|
|
31
32
|
const isCustom = (Type) => Type.source !== undefined && Type.source.js === undefined;
|
|
32
33
|
|
|
33
|
-
|
|
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) => {
|
|
34
38
|
const Type = field.constructor;
|
|
35
39
|
if (!isCustom(Type)) {
|
|
36
40
|
for (const key of Object.keys(field)) {
|
|
37
41
|
if (KNOWN.has(key) || Type.options.has(key)) continue;
|
|
42
|
+
if (element && key === 'name') continue;
|
|
38
43
|
const text = `option "${key}" of "${path}" is not known to type "${field.type}"`;
|
|
39
44
|
warnings.push(warning('unknown-option', text));
|
|
40
45
|
}
|
|
41
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
|
+
}
|
|
42
51
|
if (field.pattern !== undefined && field.length?.max === undefined) {
|
|
43
52
|
const text = `"${path}" has a pattern without length.max (see the note on ReDoS)`;
|
|
44
53
|
warnings.push(warning('unbounded-pattern', text));
|
|
@@ -48,7 +57,7 @@ const lintField = (field, path, warnings) => {
|
|
|
48
57
|
if (value !== undefined) {
|
|
49
58
|
if (Array.isArray(value)) {
|
|
50
59
|
for (let index = 0; index < value.length; index += 1) {
|
|
51
|
-
lintField(value[index], `${path}[${index}]`, warnings);
|
|
60
|
+
lintField(value[index], `${path}[${index}]`, warnings, true);
|
|
52
61
|
}
|
|
53
62
|
} else {
|
|
54
63
|
lintField(value, `${path}[]`, warnings);
|
|
@@ -69,7 +78,7 @@ const lintStruct = (fields, prefix, warnings) => {
|
|
|
69
78
|
for (const key of Object.keys(fields)) {
|
|
70
79
|
const field = fields[key];
|
|
71
80
|
if (!hasBrand(field, 'Type')) continue;
|
|
72
|
-
lintField(field, prefix ? `${prefix}.${key}` : key, warnings);
|
|
81
|
+
lintField(field, prefix ? `${prefix}.${key}` : key, warnings, false, true);
|
|
73
82
|
}
|
|
74
83
|
};
|
|
75
84
|
|