@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.
Files changed (51) hide show
  1. package/CHANGELOG.md +443 -1
  2. package/README.md +124 -12
  3. package/SECURITY.md +27 -8
  4. package/index.d.ts +537 -84
  5. package/package.json +25 -6
  6. package/src/codec.js +544 -0
  7. package/src/compile/code.js +92 -0
  8. package/src/compile/emit.js +540 -0
  9. package/src/compile/index.d.ts +38 -0
  10. package/src/compile/index.js +176 -0
  11. package/src/context.js +68 -19
  12. package/src/errors.js +19 -1
  13. package/src/generators/fromjsonschema.js +520 -0
  14. package/src/generators/index.d.ts +46 -0
  15. package/src/generators/index.js +95 -0
  16. package/src/generators/jsonschema.js +535 -0
  17. package/src/generators/typescript.js +237 -0
  18. package/src/index.js +0 -2
  19. package/src/issues.js +117 -22
  20. package/src/kinds.js +9 -12
  21. package/src/lint.js +31 -14
  22. package/src/locales/en.js +10 -2
  23. package/src/locales/uk.js +7 -2
  24. package/src/metadata.js +41 -44
  25. package/src/metautil.js +8 -1
  26. package/src/model/data.js +122 -0
  27. package/src/model/diff.js +438 -0
  28. package/src/model/index.d.ts +56 -0
  29. package/src/model/index.js +42 -0
  30. package/src/model/merge.js +254 -0
  31. package/src/model/pattern.js +322 -0
  32. package/src/model/restore.js +226 -0
  33. package/src/model/sample.js +394 -0
  34. package/src/model.js +18 -15
  35. package/src/preprocessor.js +9 -11
  36. package/src/prototypes/abstract.js +14 -1
  37. package/src/prototypes/collections.js +20 -3
  38. package/src/prototypes/reference.js +17 -3
  39. package/src/prototypes/scalars.js +1 -3
  40. package/src/prototypes/schema.js +15 -2
  41. package/src/prototypes/tuple.js +14 -9
  42. package/src/prototypes/union.js +57 -18
  43. package/src/result.js +5 -14
  44. package/src/rules.js +55 -26
  45. package/src/runtime/browser.js +2 -2
  46. package/src/runtime/node.js +4 -2
  47. package/src/schema.js +129 -101
  48. package/src/snapshot.js +111 -0
  49. package/src/struct.js +80 -23
  50. package/src/types.js +5 -11
  51. package/src/util.js +39 -0
@@ -0,0 +1,535 @@
1
+ // The JSON Schema generator of the `./generators` subpath: the rules of
2
+ // `check`, written out as a document of a target dialect. A struct is an object with its
3
+ // required keys and no others, an optional field accepts null, a rule is the
4
+ // matching keyword, and a reference is an id or the record by the kind of its
5
+ // target. What has no JSON form (a bigint, a Date or a Set on the way out, a
6
+ // custom type without metadata) throws, or renders as `{}` when the call says
7
+ // `unrepresentable: 'any'`.
8
+ const { hasBrand, define } = require('../util.js');
9
+ const { isStruct } = require('../struct.js');
10
+ const { SchemaDefinitionError } = require('../errors.js');
11
+ const { embeds } = require('../prototypes/reference.js');
12
+
13
+ // What differs between the dialects: the keyword of a type, where the
14
+ // definitions live, whether `const`, tuples, `propertyNames` and siblings of
15
+ // `$ref` exist, how null is allowed (OpenAPI 3.0 has `nullable`), which
16
+ // annotations pass through and whether the strict profile applies. The
17
+ // tables of this file are null-prototype dictionaries: a type or a target is
18
+ // looked up by a name that may be `constructor`.
19
+ const TARGETS = Object.assign(Object.create(null), {
20
+ 'draft-2020-12': {
21
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
22
+ definitions: '#/$defs/',
23
+ tuple: 'prefixItems',
24
+ const: true,
25
+ names: true,
26
+ siblings: true,
27
+ strict: true,
28
+ annotations: ['title', 'description', 'default', 'examples', 'deprecated'],
29
+ },
30
+ 'draft-07': {
31
+ $schema: 'http://json-schema.org/draft-07/schema#',
32
+ definitions: '#/definitions/',
33
+ tuple: 'items',
34
+ const: true,
35
+ names: true,
36
+ strict: true,
37
+ annotations: ['title', 'description', 'default', 'examples'],
38
+ },
39
+ 'openapi-3.0': {
40
+ definitions: '#/components/schemas/',
41
+ nullable: true,
42
+ oneOf: true,
43
+ annotations: ['title', 'description', 'default', 'example', 'deprecated'],
44
+ },
45
+ mongodb: {
46
+ tuple: 'items',
47
+ annotations: ['title', 'description'],
48
+ },
49
+ });
50
+
51
+ const TARGET_NAMES = Object.keys(TARGETS);
52
+
53
+ // BSON type names where they differ from the JSON Schema ones.
54
+ const BSON = Object.assign(Object.create(null), {
55
+ boolean: 'bool',
56
+ integer: ['int', 'long'],
57
+ bigint: 'long',
58
+ });
59
+
60
+ // The name of an entity inside a JSON pointer (RFC 6901) in a URI fragment.
61
+ const escapePointer = (name) => encodeURIComponent(name.replace(/~/g, '~0').replace(/\//g, '~1'));
62
+
63
+ // The keys of a JSON object are strings, so a number key is a pattern.
64
+ const NUMBER_KEY = '^-?\\d+(\\.\\d+)?$';
65
+
66
+ // The key every stored MongoDB document has.
67
+ const ID = '_id';
68
+
69
+ const invalidOptions = (reason) => new SchemaDefinitionError('ERR_INVALID_OPTIONS', reason);
70
+
71
+ const option = (options, name, allowed) => {
72
+ const value = options[name];
73
+ if (value === undefined) return allowed[0];
74
+ if (!allowed.includes(value)) {
75
+ let list = '';
76
+ for (let index = 0; index < allowed.length; index += 1) {
77
+ list += `${index === 0 ? '' : ', '}${JSON.stringify(allowed[index])}`;
78
+ }
79
+ const got = JSON.stringify(value);
80
+ throw invalidOptions(`JSON Schema option "${name}" must be one of ${list}, got ${got}`);
81
+ }
82
+ return value;
83
+ };
84
+
85
+ const isPointer = (value) =>
86
+ typeof value === 'string' && value.length > 3 && value.startsWith('#/') && value.endsWith('/');
87
+
88
+ // The state of one export: the target and the options, the definitions met
89
+ // so far (by entity name, in the order they were met), the entities being
90
+ // inlined (the mongodb target has no `$ref`, so a cycle is an error), the
91
+ // root schema (a reference to it is `#`) and the schema being rendered (for
92
+ // the location of an error).
93
+ const createContext = (options, unknown) => {
94
+ if (options === null || typeof options !== 'object') {
95
+ throw invalidOptions('JSON Schema options must be an object');
96
+ }
97
+ const name = option(options, 'target', TARGET_NAMES);
98
+ const target = TARGETS[name];
99
+ const io = option(options, 'io', ['input', 'output']);
100
+ const any = option(options, 'unrepresentable', ['throw', 'any']) === 'any';
101
+ const references = option(options, 'references', ['kind', 'embed', 'id']);
102
+ const { profile, definitions = target.definitions } = options;
103
+ if (profile !== undefined && profile !== 'strict') {
104
+ const got = JSON.stringify(profile);
105
+ throw invalidOptions(`JSON Schema option "profile" must be "strict", got ${got}`);
106
+ }
107
+ const strict = profile === 'strict';
108
+ if (strict && target.strict !== true) {
109
+ throw invalidOptions(
110
+ `Profile "strict" needs target "draft-2020-12" or "draft-07", got "${name}"`,
111
+ );
112
+ }
113
+ const mongo = name === 'mongodb';
114
+ if (!mongo && !isPointer(definitions)) {
115
+ throw invalidOptions('JSON Schema option "definitions" must be a pointer such as "#/$defs/"');
116
+ }
117
+ return {
118
+ name,
119
+ target,
120
+ key: mongo ? 'bsonType' : 'type',
121
+ mongo,
122
+ // A BSON document is the stored value itself, so the mongodb target has
123
+ // no input side and no output side.
124
+ input: mongo || io === 'input',
125
+ any,
126
+ references,
127
+ strict,
128
+ closed: strict || unknown !== 'ignore',
129
+ prefix: mongo ? null : definitions,
130
+ defs: new Map(),
131
+ stack: new Set(),
132
+ root: null,
133
+ owner: '',
134
+ };
135
+ };
136
+
137
+ const unrepresentable = (context, what) => {
138
+ if (context.any) return {};
139
+ const reason = `${what} cannot be represented in JSON Schema target "${context.name}"`;
140
+ throw new SchemaDefinitionError('ERR_UNREPRESENTABLE', reason);
141
+ };
142
+
143
+ const typed = (name, context) =>
144
+ context.mongo ? { bsonType: BSON[name] || name } : { type: name };
145
+
146
+ // A field that accepts null: the type takes 'null' beside it, an enum takes
147
+ // the value, anything else (a $ref, a union) goes into an anyOf with null.
148
+ // OpenAPI 3.0 has no type lists and says `nullable: true` instead.
149
+ const withNull = (json, context) => {
150
+ const { key } = context;
151
+ if (context.target.nullable === true) {
152
+ const wrapped = json.$ref === undefined ? json : { allOf: [json] };
153
+ if (wrapped.enum !== undefined && !wrapped.enum.includes(null)) {
154
+ wrapped.enum = wrapped.enum.concat([null]);
155
+ }
156
+ wrapped.nullable = true;
157
+ return wrapped;
158
+ }
159
+ if (json.const !== undefined) return { enum: [json.const, null] };
160
+ if (json.enum !== undefined && !json.enum.includes(null)) json.enum = json.enum.concat([null]);
161
+ const type = json[key];
162
+ if (typeof type === 'string') {
163
+ if (type !== 'null') json[key] = [type, 'null'];
164
+ return json;
165
+ }
166
+ if (Array.isArray(type)) {
167
+ if (!type.includes('null')) json[key] = type.concat(['null']);
168
+ return json;
169
+ }
170
+ if (json.enum !== undefined) return json;
171
+ if (json.anyOf !== undefined) {
172
+ // A copy: the list may be the one of a custom type's metadata.
173
+ json.anyOf = json.anyOf.concat([{ [key]: 'null' }]);
174
+ return json;
175
+ }
176
+ return Object.keys(json).length === 0 ? json : { anyOf: [json, { [key]: 'null' }] };
177
+ };
178
+
179
+ // The annotations of the field, by the names the target knows; OpenAPI 3.0
180
+ // has one `example`, the first of `examples`. Draft-07 and OpenAPI ignore the
181
+ // siblings of a `$ref`, so a bare reference carries none.
182
+ const annotate = (json, field, context) => {
183
+ if (json.$ref !== undefined && context.target.siblings !== true) return json;
184
+ for (const name of context.target.annotations) {
185
+ const key = name === 'example' ? 'examples' : name;
186
+ let value = field[key];
187
+ if (value === undefined) continue;
188
+ if (key !== name) {
189
+ if (!Array.isArray(value) || value.length === 0) continue;
190
+ value = value[0];
191
+ }
192
+ // `deprecated` is a boolean in every dialect; a note is not copied.
193
+ if (name === 'deprecated' && value !== true) continue;
194
+ json[name] = value;
195
+ }
196
+ return json;
197
+ };
198
+
199
+ const bounds = (json, length, min, max) => {
200
+ if (length === undefined) return;
201
+ if (length.min !== undefined) json[min] = length.min;
202
+ if (length.max !== undefined) json[max] = length.max;
203
+ };
204
+
205
+ // A bigint bound of a number field is written as a number.
206
+ const ranged = (json, field, context) => {
207
+ if (context.strict) return json;
208
+ if (field.min !== undefined) json.minimum = Number(field.min);
209
+ if (field.max !== undefined) json.maximum = Number(field.max);
210
+ return json;
211
+ };
212
+
213
+ const list = (field, context) => {
214
+ const json = { [context.key]: 'array', items: render(field.value, context) };
215
+ if (!context.strict) bounds(json, field.length, 'minItems', 'maxItems');
216
+ return json;
217
+ };
218
+
219
+ // The LLM dialects of the strict profile accept no value without a type
220
+ // and no object without its properties listed.
221
+ const unconstrained = (context, name) =>
222
+ context.strict ? unrepresentable(context, `Type "${name}" (profile strict)`) : null;
223
+
224
+ // An `object` or `map`: free keys with values of one type. A required one
225
+ // must not be empty, as in `check`.
226
+ const dictionary = (field, context) => {
227
+ if (context.strict) return unconstrained(context, field.type);
228
+ const json = { [context.key]: 'object', additionalProperties: render(field.value, context) };
229
+ if (field.key === 'number' && context.target.names === true) {
230
+ json.propertyNames = { pattern: NUMBER_KEY };
231
+ }
232
+ bounds(json, field.length, 'minProperties', 'maxProperties');
233
+ if (field.required && !(json.minProperties >= 1)) json.minProperties = 1;
234
+ return json;
235
+ };
236
+
237
+ const isJSON = (value) =>
238
+ value === null || (typeof value !== 'object' && typeof value !== 'bigint');
239
+
240
+ const enumeration = (field, context) => {
241
+ const values = field.enum;
242
+ const copy = [];
243
+ for (let index = 0; index < values.length; index += 1) {
244
+ const value = values[index];
245
+ if (!isJSON(value)) return unrepresentable(context, `Enum value ${String(value)}`);
246
+ copy.push(value);
247
+ }
248
+ if (copy.length === 1 && context.target.const === true) return { const: copy[0] };
249
+ return { enum: copy };
250
+ };
251
+
252
+ // A tuple is `prefixItems` in 2020-12 and an `items` list before it; OpenAPI
253
+ // 3.0 has neither. The elements up to the last required one must be there.
254
+ const tuple = (field, context) => {
255
+ const form = context.target.tuple;
256
+ if (form === undefined) return unrepresentable(context, 'Type "tuple"');
257
+ const elements = field.value;
258
+ const items = [];
259
+ // The elements, and the position of the last required one in one pass.
260
+ let min = 0;
261
+ for (let index = 0; index < elements.length; index += 1) {
262
+ const element = elements[index];
263
+ items.push(render(element, context));
264
+ if (element.required) min = index + 1;
265
+ }
266
+ const json = { [context.key]: 'array' };
267
+ if (form === 'prefixItems') {
268
+ json.prefixItems = items;
269
+ json.items = false;
270
+ } else {
271
+ json.items = items;
272
+ json.additionalItems = false;
273
+ }
274
+ if (context.strict) return json;
275
+ if (min > 0) json.minItems = min;
276
+ return json;
277
+ };
278
+
279
+ const union = (field, context) => {
280
+ const branches = [];
281
+ for (let index = 0; index < field.union.length; index += 1) {
282
+ branches.push(render(field.union[index], context));
283
+ }
284
+ if (field.discriminator !== undefined && context.target.oneOf === true) {
285
+ return { oneOf: branches, discriminator: { propertyName: field.discriminator } };
286
+ }
287
+ return { anyOf: branches };
288
+ };
289
+
290
+ // A reference by the rule of `check`: an id (a string) for a stored kind,
291
+ // the record for a memory kind, `embed` on the field and the `references`
292
+ // option deciding otherwise. A target that cannot be resolved is held as
293
+ // an id, as the dts does, unless the field embeds it.
294
+ const reference = (field, context) => {
295
+ const name = field.type;
296
+ const target = field.root.findReference(name);
297
+ let json;
298
+ if (target === null) {
299
+ if (field.embed === true) json = unrepresentable(context, `Reference "${name}" (embed)`);
300
+ else json = typed('string', context);
301
+ } else if (!embeds(target, field.embed, context.references)) {
302
+ json = typed('string', context);
303
+ } else {
304
+ json = definition(target, context);
305
+ }
306
+ return field.many === undefined ? json : { [context.key]: 'array', items: json };
307
+ };
308
+
309
+ // A referenced entity: `#` for the root of the document, a `$ref` into the
310
+ // definitions (rendered once) otherwise, and inline where the target has no
311
+ // `$ref` (mongodb), where a cycle has no form.
312
+ const definition = (schema, context) => {
313
+ const { name } = schema;
314
+ if (context.prefix === null) {
315
+ if (context.stack.has(name)) return unrepresentable(context, `Recursive reference "${name}"`);
316
+ context.stack.add(name);
317
+ const json = renderSchema(schema, context);
318
+ context.stack.delete(name);
319
+ return json;
320
+ }
321
+ if (schema === context.root) return { $ref: '#' };
322
+ if (!context.defs.has(name)) {
323
+ context.defs.set(name, null);
324
+ context.defs.set(name, renderSchema(schema, context));
325
+ }
326
+ return { $ref: context.prefix + escapePointer(name) };
327
+ };
328
+
329
+ const RENDER = Object.assign(Object.create(null), {
330
+ string: (field, context) => {
331
+ const json = typed('string', context);
332
+ if (context.strict) return json;
333
+ bounds(json, field.length, 'minLength', 'maxLength');
334
+ if (field.pattern !== undefined) json.pattern = field.pattern.source;
335
+ return json;
336
+ },
337
+ number: (field, context) => ranged(typed('number', context), field, context),
338
+ integer: (field, context) => ranged(typed('integer', context), field, context),
339
+ bigint: (field, context) =>
340
+ context.mongo ? typed('bigint', context) : unrepresentable(context, 'Type "bigint"'),
341
+ boolean: (field, context) => typed('boolean', context),
342
+ date: (field, context) => {
343
+ if (context.mongo) return typed('date', context);
344
+ if (context.input) return { type: 'string', format: 'date-time' };
345
+ return unrepresentable(context, 'Type "date" (output)');
346
+ },
347
+ null: (field, context) => typed('null', context),
348
+ any: (field, context) => unconstrained(context, 'any') || {},
349
+ unknown: (field, context) => unconstrained(context, 'unknown') || {},
350
+ json: (field, context) =>
351
+ unconstrained(context, 'json') || { [context.key]: ['object', 'array'] },
352
+ enum: enumeration,
353
+ array: list,
354
+ set: (field, context) => {
355
+ if (!context.input || context.mongo) return unrepresentable(context, 'Type "set"');
356
+ const json = list(field, context);
357
+ if (!context.strict) json.uniqueItems = true;
358
+ return json;
359
+ },
360
+ object: dictionary,
361
+ map: (field, context) =>
362
+ context.input ? dictionary(field, context) : unrepresentable(context, 'Type "map" (output)'),
363
+ tuple,
364
+ union,
365
+ schema: (field, context) =>
366
+ isStruct(field.schema) ? struct(field.schema, context) : render(field.schema, context),
367
+ reference,
368
+ one: reference,
369
+ many: reference,
370
+ });
371
+
372
+ // The built-in type a field validates as: its own, or the one its alias
373
+ // chain ends in.
374
+ const baseOf = (field) => {
375
+ const { types } = field.root;
376
+ let Type = field.constructor;
377
+ while (Type.source !== undefined && Type.source.js !== undefined) Type = types[Type.source.js];
378
+ return Type.type;
379
+ };
380
+
381
+ // The schema of the type of a field: the metadata of a custom type when it
382
+ // says (`jsonSchema`, or `bson` for mongodb), else the built-in it is or
383
+ // aliases, else nothing.
384
+ const renderType = (field, context) => {
385
+ const { metadata } = field.constructor;
386
+ if (context.mongo) {
387
+ if (metadata.bson !== undefined) return { bsonType: metadata.bson };
388
+ } else if (metadata.jsonSchema !== undefined) {
389
+ return { ...metadata.jsonSchema };
390
+ }
391
+ const renderer = RENDER[baseOf(field)];
392
+ if (renderer !== undefined) return renderer(field, context);
393
+ const hint = context.mongo ? 'bson' : 'jsonSchema';
394
+ return unrepresentable(context, `Type "${field.type}" (without metadata.${hint})`);
395
+ };
396
+
397
+ // A field: its type, null when the field is nullable or optional (`check`
398
+ // accepts null for an optional field), then its annotations.
399
+ const render = (field, context) => {
400
+ let json = renderType(field, context);
401
+ if (field.nullable === true || field.required === false) json = withNull(json, context);
402
+ return annotate(json, field, context);
403
+ };
404
+
405
+ // A struct: its validated fields as properties (a calculated field is a
406
+ // function and has no schema), the required ones listed, no other keys
407
+ // unless the schema ignores them. The strict profile lists every property.
408
+ const struct = (fields, context) => {
409
+ const properties = {};
410
+ const required = [];
411
+ // A struct is a null-prototype dictionary: its own keys, in order; a key
412
+ // such as `__proto__` is defined as data on the document.
413
+ for (const key in fields) {
414
+ const field = fields[key];
415
+ if (!hasBrand(field, 'Type')) continue;
416
+ try {
417
+ define(properties, key, render(field, context));
418
+ } catch (error) {
419
+ const own = error.field === '' || error.schema === context.owner;
420
+ if (error instanceof SchemaDefinitionError && own) error.locate(context.owner, key);
421
+ throw error;
422
+ }
423
+ if (field.required || context.strict) required.push(key);
424
+ }
425
+ const json = { [context.key]: 'object', properties };
426
+ if (required.length > 0) json.required = required;
427
+ if (context.closed) json.additionalProperties = false;
428
+ return json;
429
+ };
430
+
431
+ // The schema being rendered owns the location of an error met in it, and
432
+ // is restored when the rendering leaves it, thrown out of or not.
433
+ const renderSchema = (schema, context) => {
434
+ const { owner } = context;
435
+ const { fields } = schema;
436
+ context.owner = schema.name;
437
+ try {
438
+ return isStruct(fields) ? struct(fields, context) : render(fields, context);
439
+ } finally {
440
+ context.owner = owner;
441
+ }
442
+ };
443
+
444
+ // The document of one schema: its own unknown-keys policy applies to the
445
+ // whole document, as it does to a check.
446
+ const renderRoot = (schema, context) => {
447
+ context.closed = context.strict || schema.unknown !== 'ignore';
448
+ if (context.strict && !isStruct(schema.fields)) {
449
+ throw invalidOptions(
450
+ `Profile "strict" needs a struct at the root, got "${schema.fields.type}"`,
451
+ );
452
+ }
453
+ const json = renderSchema(schema, context);
454
+ // Every stored document has an `_id`; a closed mongodb root must let it in.
455
+ if (context.mongo && json.additionalProperties === false && json.properties[ID] === undefined) {
456
+ json.properties[ID] = {};
457
+ }
458
+ return json;
459
+ };
460
+
461
+ // The documents of a model by entity name, the names defined as data.
462
+ const documentsOf = (documents) => {
463
+ const out = {};
464
+ for (const pair of documents) define(out, pair[0], pair[1]);
465
+ return out;
466
+ };
467
+
468
+ // The definitions go where the `definitions` pointer says: `$defs`,
469
+ // `definitions` or `components.schemas`, into the object already there when
470
+ // the document has one on the way.
471
+ const place = (document, context) => {
472
+ if (context.target.$schema !== undefined) document.$schema = context.target.$schema;
473
+ if (context.defs.size === 0) return document;
474
+ const path = context.prefix.slice(2, -1).split('/');
475
+ let node = document;
476
+ for (let index = 0; index < path.length; index += 1) {
477
+ const name = path[index];
478
+ const existing = Object.hasOwn(node, name) ? node[name] : undefined;
479
+ const isObject = existing !== null && typeof existing === 'object' && !Array.isArray(existing);
480
+ node = isObject ? existing : define(node, name, {});
481
+ }
482
+ for (const pair of context.defs) define(node, pair[0], pair[1]);
483
+ return document;
484
+ };
485
+
486
+ const toJSONSchema = (schema, options = {}) => {
487
+ const context = createContext(options, schema.unknown);
488
+ context.root = schema;
489
+ const json = renderRoot(schema, context);
490
+ if (context.mongo) return json;
491
+ const document = context.target.$schema === undefined ? {} : { $schema: '' };
492
+ return place(Object.assign(document, json), context);
493
+ };
494
+
495
+ // The model as one document of definitions, one per entity in dependency
496
+ // order, or the document of the entity `root` with the definitions it needs.
497
+ // The mongodb target has no definitions: one document per entity, inline.
498
+ const modelToJSONSchema = (model, options = {}) => {
499
+ const { root, ...rest } = options;
500
+ if (root !== undefined) {
501
+ const entity = model.entities.get(root);
502
+ if (entity === undefined) throw invalidOptions(`Entity "${root}" is not in the model`);
503
+ return toJSONSchema(entity, rest);
504
+ }
505
+ const context = createContext(rest, 'reject');
506
+ if (context.strict) throw invalidOptions('Profile "strict" needs a root entity');
507
+ const { entities, order } = model;
508
+ const documents = new Map();
509
+ for (const name of order) documents.set(name, null);
510
+ for (const name of order) {
511
+ context.defs = context.mongo ? new Map() : documents;
512
+ documents.set(name, renderRoot(entities.get(name), context));
513
+ }
514
+ if (context.mongo) return documentsOf(documents);
515
+ context.defs = documents;
516
+ return place({}, context);
517
+ };
518
+
519
+ const STANDARD_TARGETS = ['draft-2020-12', 'draft-07', 'openapi-3.0'];
520
+
521
+ // The converter of Standard JSON Schema: `input` and `output` take the
522
+ // target (one of the three JSON ones) and the other options as
523
+ // `libraryOptions`.
524
+ const standardConverter = (schema) => {
525
+ const convert = (io) => (options) => {
526
+ const target = options === null || typeof options !== 'object' ? undefined : options.target;
527
+ if (!STANDARD_TARGETS.includes(target)) {
528
+ throw invalidOptions(`JSON Schema target ${JSON.stringify(target)} is not supported`);
529
+ }
530
+ return toJSONSchema(schema, { ...options.libraryOptions, target, io });
531
+ };
532
+ return { input: convert('input'), output: convert('output') };
533
+ };
534
+
535
+ module.exports = { toJSONSchema, modelToJSONSchema, standardConverter };