@7nohe/openapi-react-query-codegen 4.0.0-beta.6 → 4.0.0-beta.8
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/AGENTS.md +35 -7
- package/README.md +60 -13
- package/dist/agentsMd.mjs +3 -1
- package/dist/check.mjs +15 -5
- package/dist/cli.d.mts +2 -0
- package/dist/client/emitMocks.d.mts +23 -0
- package/dist/client/emitMocks.mjs +353 -0
- package/dist/client/emitSdk.mjs +8 -3
- package/dist/client/emitTypes.d.mts +6 -1
- package/dist/client/emitTypes.mjs +16 -7
- package/dist/client/index.d.mts +12 -0
- package/dist/client/index.mjs +12 -0
- package/dist/client/mockValue.d.mts +34 -0
- package/dist/client/mockValue.mjs +796 -0
- package/dist/client/msw.d.mts +11 -0
- package/dist/client/msw.mjs +27 -0
- package/dist/client/operations.d.mts +4 -0
- package/dist/client/operations.mjs +25 -0
- package/dist/client/schema.d.mts +25 -3
- package/dist/client/schema.mjs +36 -24
- package/dist/common.d.mts +1 -0
- package/dist/common.mjs +4 -1
- package/dist/constants.d.mts +1 -0
- package/dist/constants.mjs +1 -0
- package/dist/format.d.mts +3 -1
- package/dist/format.mjs +3 -3
- package/dist/generate.mjs +19 -2
- package/dist/hooks/buildCommon.d.mts +6 -1
- package/dist/hooks/buildCommon.mjs +7 -2
- package/dist/runCli.mjs +2 -1
- package/package.json +22 -13
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
import { propertyKey } from "./naming.mjs";
|
|
2
|
+
import { componentSchemaKey, componentSchemaView, discriminatorValues, hasBinaryContent, hasFlag, hasObjectKeywords, impliedType, inheritedRequired, isDateString, isNullableSchema, isRequiredOnly, OMITTED_PROPERTY, renderSchema, requiresProperty, schemaKinds, } from "./schema.mjs";
|
|
3
|
+
import { getByPointer, refSiblingSchema, resolveRef, } from "./spec.mjs";
|
|
4
|
+
/** What stands for a value of the type `unknown`. */
|
|
5
|
+
const ANY_VALUE = "{}";
|
|
6
|
+
const DATE_TIME = "2024-01-01T00:00:00.000Z";
|
|
7
|
+
/** A fixed value for each `format` of a string. */
|
|
8
|
+
const STRING_FORMATS = {
|
|
9
|
+
"date-time": DATE_TIME,
|
|
10
|
+
date: "2024-01-01",
|
|
11
|
+
time: "00:00:00Z",
|
|
12
|
+
uuid: "00000000-0000-4000-8000-000000000000",
|
|
13
|
+
email: "user@example.com",
|
|
14
|
+
uri: "https://example.com",
|
|
15
|
+
url: "https://example.com",
|
|
16
|
+
hostname: "example.com",
|
|
17
|
+
ipv4: "192.0.2.1",
|
|
18
|
+
ipv6: "2001:db8::1",
|
|
19
|
+
byte: "c3RyaW5n",
|
|
20
|
+
};
|
|
21
|
+
const SIMPLE_TYPES = ["string", "number", "integer", "boolean"];
|
|
22
|
+
function literalKey(name) {
|
|
23
|
+
// `{ __proto__: … }` would set the prototype instead of a property.
|
|
24
|
+
return name === "__proto__" ? '["__proto__"]' : propertyKey(name);
|
|
25
|
+
}
|
|
26
|
+
function objectLiteral(entries, indent) {
|
|
27
|
+
if (entries.length === 0)
|
|
28
|
+
return "{}";
|
|
29
|
+
const lines = entries.map((entry) => "spread" in entry
|
|
30
|
+
? `${indent} ...${entry.spread},`
|
|
31
|
+
: `${indent} ${literalKey(entry.key)}: ${entry.value},`);
|
|
32
|
+
return `{\n${lines.join("\n")}\n${indent}}`;
|
|
33
|
+
}
|
|
34
|
+
/** `items` are written for an array that sits at `indent`. */
|
|
35
|
+
function arrayLiteral(items, indent) {
|
|
36
|
+
if (items.every((item) => !item.includes("\n"))) {
|
|
37
|
+
return `[${items.join(", ")}]`;
|
|
38
|
+
}
|
|
39
|
+
const lines = items.map((item) => `${indent} ${item},`);
|
|
40
|
+
return `[\n${lines.join("\n")}\n${indent}]`;
|
|
41
|
+
}
|
|
42
|
+
/** Any JSON value as an expression, for a place whose type takes anything. */
|
|
43
|
+
function jsonLiteral(value, indent) {
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
return arrayLiteral(value.map((item) => jsonLiteral(item, `${indent} `)), indent);
|
|
46
|
+
}
|
|
47
|
+
if (value && typeof value === "object") {
|
|
48
|
+
return objectLiteral(Object.entries(value).map(([key, item]) => ({
|
|
49
|
+
key,
|
|
50
|
+
value: jsonLiteral(item, `${indent} `),
|
|
51
|
+
})), indent);
|
|
52
|
+
}
|
|
53
|
+
return JSON.stringify(value);
|
|
54
|
+
}
|
|
55
|
+
function print(built, indent) {
|
|
56
|
+
return "expr" in built ? built.expr : objectLiteral(built.entries, indent);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* One object out of the parts of an intersection. What is spread comes first
|
|
60
|
+
* and a property wins over it, as the literal a discriminator pins has to; of
|
|
61
|
+
* two properties with one name the later one stays. A property that several
|
|
62
|
+
* members declare is not left to that: `buildComposed` gives it a part of its
|
|
63
|
+
* own, with a value of all of its declarations.
|
|
64
|
+
*/
|
|
65
|
+
function mergeObjects(parts, indent) {
|
|
66
|
+
const spreads = [];
|
|
67
|
+
const properties = new Map();
|
|
68
|
+
for (const part of parts) {
|
|
69
|
+
if ("expr" in part) {
|
|
70
|
+
// Nothing to add, or what is spread already.
|
|
71
|
+
const repeated = spreads.some((entry) => "spread" in entry && entry.spread === part.expr);
|
|
72
|
+
if (part.expr !== ANY_VALUE && !repeated) {
|
|
73
|
+
spreads.push({ spread: part.expr });
|
|
74
|
+
}
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
for (const entry of part.entries) {
|
|
78
|
+
if ("spread" in entry) {
|
|
79
|
+
spreads.push(entry);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
properties.delete(entry.key);
|
|
83
|
+
properties.set(entry.key, entry.value);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const entries = [
|
|
88
|
+
...spreads,
|
|
89
|
+
...[...properties].map(([key, value]) => ({ key, value })),
|
|
90
|
+
];
|
|
91
|
+
// A lone spread is the value itself.
|
|
92
|
+
if (entries.length === 1 && "spread" in entries[0]) {
|
|
93
|
+
return { expr: entries[0].spread };
|
|
94
|
+
}
|
|
95
|
+
return { expr: objectLiteral(entries, indent) };
|
|
96
|
+
}
|
|
97
|
+
function stringSample(schema) {
|
|
98
|
+
const fixed = STRING_FORMATS[schema.format];
|
|
99
|
+
if (fixed !== undefined)
|
|
100
|
+
return fixed;
|
|
101
|
+
let text = "string";
|
|
102
|
+
if (typeof schema.maxLength === "number" && schema.maxLength < text.length) {
|
|
103
|
+
text = text.slice(0, Math.max(schema.maxLength, 0));
|
|
104
|
+
}
|
|
105
|
+
if (typeof schema.minLength === "number" && schema.minLength > text.length) {
|
|
106
|
+
text = text.padEnd(schema.minLength, "x");
|
|
107
|
+
}
|
|
108
|
+
return text;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The first whole number a fraction goes into: 3 for 0.3, and 3 for 3e-21.
|
|
112
|
+
* An integer that is a multiple of the fraction is a multiple of it. Read off
|
|
113
|
+
* the digits and the exponent of the fraction, so that it is exact however
|
|
114
|
+
* small the fraction is; undefined when the whole number is too large to be
|
|
115
|
+
* one a mock can hold.
|
|
116
|
+
*/
|
|
117
|
+
function wholeMultiple(fraction) {
|
|
118
|
+
const [mantissa, exponent = "0"] = fraction.toString().split("e");
|
|
119
|
+
const [whole, decimals = ""] = mantissa.split(".");
|
|
120
|
+
// The fraction is `numerator / denominator`, with a power of ten for one
|
|
121
|
+
// of them.
|
|
122
|
+
const shift = decimals.length - Number(exponent);
|
|
123
|
+
const power = 10n ** BigInt(Math.abs(shift));
|
|
124
|
+
const numerator = BigInt(whole + decimals) * (shift < 0 ? power : 1n);
|
|
125
|
+
const denominator = shift > 0 ? power : 1n;
|
|
126
|
+
let [a, b] = [numerator, denominator];
|
|
127
|
+
while (b !== 0n)
|
|
128
|
+
[a, b] = [b, a % b];
|
|
129
|
+
const multiple = numerator / a;
|
|
130
|
+
return multiple <= BigInt(Number.MAX_SAFE_INTEGER)
|
|
131
|
+
? Number(multiple)
|
|
132
|
+
: undefined;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* `1`, or where the schema does not allow it, a value in the range it gives
|
|
136
|
+
* that is a multiple of its `multipleOf`.
|
|
137
|
+
*/
|
|
138
|
+
function numberSample(schema) {
|
|
139
|
+
// OpenAPI 3.0 writes an exclusive bound as a flag, 3.1 as the bound itself.
|
|
140
|
+
let min = Number.NEGATIVE_INFINITY;
|
|
141
|
+
let minOpen = false;
|
|
142
|
+
if (typeof schema.minimum === "number") {
|
|
143
|
+
min = schema.minimum;
|
|
144
|
+
minOpen = schema.exclusiveMinimum === true;
|
|
145
|
+
}
|
|
146
|
+
if (typeof schema.exclusiveMinimum === "number" &&
|
|
147
|
+
schema.exclusiveMinimum >= min) {
|
|
148
|
+
min = schema.exclusiveMinimum;
|
|
149
|
+
minOpen = true;
|
|
150
|
+
}
|
|
151
|
+
let max = Number.POSITIVE_INFINITY;
|
|
152
|
+
let maxOpen = false;
|
|
153
|
+
if (typeof schema.maximum === "number") {
|
|
154
|
+
max = schema.maximum;
|
|
155
|
+
maxOpen = schema.exclusiveMaximum === true;
|
|
156
|
+
}
|
|
157
|
+
if (typeof schema.exclusiveMaximum === "number" &&
|
|
158
|
+
schema.exclusiveMaximum <= max) {
|
|
159
|
+
max = schema.exclusiveMaximum;
|
|
160
|
+
maxOpen = true;
|
|
161
|
+
}
|
|
162
|
+
const inRange = (value) => (minOpen ? value > min : value >= min) &&
|
|
163
|
+
(maxOpen ? value < max : value <= max);
|
|
164
|
+
const integer = schema.type === "integer";
|
|
165
|
+
let step = typeof schema.multipleOf === "number" && schema.multipleOf > 0
|
|
166
|
+
? schema.multipleOf
|
|
167
|
+
: integer
|
|
168
|
+
? 1
|
|
169
|
+
: undefined;
|
|
170
|
+
if (integer && step !== undefined && !Number.isInteger(step)) {
|
|
171
|
+
const whole = wholeMultiple(step);
|
|
172
|
+
// With no whole multiple a mock can hold, zero is the only one left.
|
|
173
|
+
// Outside the range, the value is at least an integer inside it.
|
|
174
|
+
if (whole === undefined && inRange(0))
|
|
175
|
+
return 0;
|
|
176
|
+
step = whole ?? 1;
|
|
177
|
+
}
|
|
178
|
+
if (step !== undefined) {
|
|
179
|
+
const size = step;
|
|
180
|
+
// How many steps a bound is. Dividing by a fraction can miss a whole
|
|
181
|
+
// number by the rounding of the division (0.3 / 0.1), which is put
|
|
182
|
+
// right. The allowance is that error and no more: a bound that is not a
|
|
183
|
+
// whole number of steps (1000000000.75) must not become one.
|
|
184
|
+
const steps = (bound) => {
|
|
185
|
+
const exact = bound / size;
|
|
186
|
+
if (Number.isInteger(size))
|
|
187
|
+
return exact;
|
|
188
|
+
const whole = Math.round(exact);
|
|
189
|
+
const error = 8 * Number.EPSILON * Math.max(1, Math.abs(exact));
|
|
190
|
+
return Math.abs(exact - whole) <= Math.min(error, 1e-3) ? whole : exact;
|
|
191
|
+
};
|
|
192
|
+
const lowest = Math.ceil(steps(min));
|
|
193
|
+
const highest = Math.floor(steps(max));
|
|
194
|
+
// The multiple at or above 1, else the lowest in the range, else the
|
|
195
|
+
// highest. With no multiple in the range there is nothing better than the
|
|
196
|
+
// first.
|
|
197
|
+
const candidates = [
|
|
198
|
+
Math.ceil(steps(1)),
|
|
199
|
+
...(Number.isFinite(min)
|
|
200
|
+
? [lowest + (minOpen && lowest === steps(min) ? 1 : 0)]
|
|
201
|
+
: []),
|
|
202
|
+
...(Number.isFinite(max)
|
|
203
|
+
? [highest - (maxOpen && highest === steps(max) ? 1 : 0)]
|
|
204
|
+
: []),
|
|
205
|
+
].map((count) => {
|
|
206
|
+
// A whole step gives the number as it is. A fraction leaves the dust
|
|
207
|
+
// of its multiplication behind (0.1 * 3), which is rounded away, unless
|
|
208
|
+
// that would take a number out of the range it was in.
|
|
209
|
+
const exact = count * size;
|
|
210
|
+
if (Number.isInteger(size))
|
|
211
|
+
return exact;
|
|
212
|
+
const rounded = Number(exact.toPrecision(15));
|
|
213
|
+
return inRange(rounded) || !inRange(exact) ? rounded : exact;
|
|
214
|
+
});
|
|
215
|
+
return candidates.find(inRange) ?? candidates[0];
|
|
216
|
+
}
|
|
217
|
+
if (inRange(1))
|
|
218
|
+
return 1;
|
|
219
|
+
if (Number.isFinite(min) && Number.isFinite(max)) {
|
|
220
|
+
return minOpen || maxOpen ? (min + max) / 2 : min;
|
|
221
|
+
}
|
|
222
|
+
if (Number.isFinite(min))
|
|
223
|
+
return minOpen ? min + 1 : min;
|
|
224
|
+
return maxOpen ? max - 1 : max;
|
|
225
|
+
}
|
|
226
|
+
function buildRef(ref, ctx, indent, seen) {
|
|
227
|
+
const { doc } = ctx.schema;
|
|
228
|
+
const key = componentSchemaKey(ref);
|
|
229
|
+
if (key !== undefined) {
|
|
230
|
+
// A reference to a schema that is not there is typed `unknown`.
|
|
231
|
+
if (!Object.hasOwn(doc.components?.schemas ?? {}, key)) {
|
|
232
|
+
return { expr: ANY_VALUE };
|
|
233
|
+
}
|
|
234
|
+
const call = ctx.callMock(key);
|
|
235
|
+
return call === undefined ? undefined : { expr: call };
|
|
236
|
+
}
|
|
237
|
+
if (seen.has(ref))
|
|
238
|
+
return { expr: ANY_VALUE };
|
|
239
|
+
return build(getByPointer(doc, ref), ctx, indent, new Set(seen).add(ref));
|
|
240
|
+
}
|
|
241
|
+
function buildObject(schema, ctx, indent, seen) {
|
|
242
|
+
const properties = schema.properties ?? {};
|
|
243
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
244
|
+
const entries = [];
|
|
245
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
246
|
+
if (hasFlag(ctx.schema.doc, property, "writeOnly"))
|
|
247
|
+
continue;
|
|
248
|
+
const value = mockValue(property, ctx, `${indent} `, seen);
|
|
249
|
+
if (value === undefined) {
|
|
250
|
+
// Nothing ends here. A property that may be absent is left out.
|
|
251
|
+
if (required.has(name))
|
|
252
|
+
return undefined;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
entries.push({ key: name, value });
|
|
256
|
+
}
|
|
257
|
+
return { entries };
|
|
258
|
+
}
|
|
259
|
+
function buildArray(schema, ctx, indent, seen) {
|
|
260
|
+
const inner = `${indent} `;
|
|
261
|
+
const itemOf = (item) => mockValue(item, ctx, inner, seen);
|
|
262
|
+
const tuple = (schemas) => {
|
|
263
|
+
const items = schemas.map(itemOf);
|
|
264
|
+
return items.some((item) => item === undefined)
|
|
265
|
+
? undefined
|
|
266
|
+
: { expr: arrayLiteral(items, indent) };
|
|
267
|
+
};
|
|
268
|
+
if (Array.isArray(schema.prefixItems))
|
|
269
|
+
return tuple(schema.prefixItems);
|
|
270
|
+
const length = schema.maxItems;
|
|
271
|
+
if (schema.items &&
|
|
272
|
+
typeof length === "number" &&
|
|
273
|
+
length > 0 &&
|
|
274
|
+
length === schema.minItems) {
|
|
275
|
+
return tuple(Array.from({ length }, () => schema.items));
|
|
276
|
+
}
|
|
277
|
+
// An empty array is a value of any array type, and it ends a cycle.
|
|
278
|
+
const item = schema.items === undefined || length === 0
|
|
279
|
+
? undefined
|
|
280
|
+
: itemOf(schema.items);
|
|
281
|
+
if (item === undefined)
|
|
282
|
+
return { expr: "[]" };
|
|
283
|
+
const count = typeof schema.minItems === "number"
|
|
284
|
+
? Math.min(Math.max(schema.minItems, 1), 10)
|
|
285
|
+
: 1;
|
|
286
|
+
return {
|
|
287
|
+
expr: arrayLiteral(Array.from({ length: count }, () => item), indent),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Every declaration of each property in a schema and in what its `allOf` is
|
|
292
|
+
* made of. A member whose discriminator property is replaced
|
|
293
|
+
* (`Omit<Parent, …>`) does not declare that one.
|
|
294
|
+
*/
|
|
295
|
+
function collectDeclarations(ctx, schema, into, omitted = new Set(), visited = new Set()) {
|
|
296
|
+
const { doc } = ctx.schema;
|
|
297
|
+
const resolved = resolveRef(doc, schema);
|
|
298
|
+
if (!resolved || typeof resolved !== "object" || visited.has(resolved)) {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
visited.add(resolved);
|
|
302
|
+
const properties = resolved.properties ?? {};
|
|
303
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
304
|
+
if (omitted.has(name) || hasFlag(doc, property, "writeOnly"))
|
|
305
|
+
continue;
|
|
306
|
+
into.set(name, [...(into.get(name) ?? []), property]);
|
|
307
|
+
}
|
|
308
|
+
for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) {
|
|
309
|
+
const marker = member?.[OMITTED_PROPERTY];
|
|
310
|
+
collectDeclarations(ctx, member, into, typeof marker === "string" ? new Set(omitted).add(marker) : omitted, visited);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* A part of an intersection without the properties in `names`. A property the
|
|
315
|
+
* part writes out is dropped; one that comes with what it spreads (the mock of
|
|
316
|
+
* a referenced schema) is taken out of that.
|
|
317
|
+
*/
|
|
318
|
+
function withoutProperties(part, source, names, ctx) {
|
|
319
|
+
if ("entries" in part) {
|
|
320
|
+
return {
|
|
321
|
+
entries: part.entries.filter((entry) => "spread" in entry || !names.has(entry.key)),
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
const declared = new Map();
|
|
325
|
+
collectDeclarations(ctx, source, declared);
|
|
326
|
+
const present = [...names].filter((name) => declared.has(name));
|
|
327
|
+
if (present.length === 0)
|
|
328
|
+
return part;
|
|
329
|
+
const bindings = present.map((name, index) => `${literalKey(name)}: _${index}`);
|
|
330
|
+
return {
|
|
331
|
+
expr: `(({ ${bindings.join(", ")}, ...rest }) => rest)(${part.expr})`,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
/** The values a schema is limited to by its `const` or `enum`, if it is. */
|
|
335
|
+
function pinnedValues(ctx, schema, depth = 0) {
|
|
336
|
+
const resolved = resolveRef(ctx.schema.doc, schema);
|
|
337
|
+
if (!resolved || typeof resolved !== "object" || depth > 16)
|
|
338
|
+
return undefined;
|
|
339
|
+
if (resolved.const !== undefined)
|
|
340
|
+
return [resolved.const];
|
|
341
|
+
if (Array.isArray(resolved.enum))
|
|
342
|
+
return resolved.enum;
|
|
343
|
+
for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) {
|
|
344
|
+
const pinned = pinnedValues(ctx, member, depth + 1);
|
|
345
|
+
if (pinned)
|
|
346
|
+
return pinned;
|
|
347
|
+
}
|
|
348
|
+
return undefined;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* The value of an intersection that is not an object, from the values of its
|
|
352
|
+
* members (`parts`). Where a member limits the values (`string & "ok"`), only
|
|
353
|
+
* one of those that every member takes is a value of the type. Otherwise it
|
|
354
|
+
* is the value of a member that only allows the kinds every member does: of
|
|
355
|
+
* `(string | number) & number` the number, and of `string & number` nothing.
|
|
356
|
+
* Undefined when there is no value.
|
|
357
|
+
*/
|
|
358
|
+
function buildScalarIntersection(members, parts, ctx, indent) {
|
|
359
|
+
const { doc } = ctx.schema;
|
|
360
|
+
const pinned = members
|
|
361
|
+
.map((member) => pinnedValues(ctx, member))
|
|
362
|
+
.find((values) => values !== undefined);
|
|
363
|
+
if (pinned === undefined) {
|
|
364
|
+
const shared = schemaKinds(doc, { allOf: members });
|
|
365
|
+
const fitting = members.findIndex((member) => [...schemaKinds(doc, member)].every((kind) => shared.has(kind)));
|
|
366
|
+
if (fitting !== -1)
|
|
367
|
+
return parts[fitting];
|
|
368
|
+
// Every member allows more than they share. Only of `null` is the value
|
|
369
|
+
// known without a member to take it from.
|
|
370
|
+
return shared.size === 1 && shared.has("null")
|
|
371
|
+
? { expr: "null" }
|
|
372
|
+
: undefined;
|
|
373
|
+
}
|
|
374
|
+
for (const candidate of pinned) {
|
|
375
|
+
const rendered = members.map((member) => exampleValue(member, candidate, ctx, indent));
|
|
376
|
+
if (rendered.some((value) => value === undefined))
|
|
377
|
+
continue;
|
|
378
|
+
// A member that is a TypeScript enum takes the value asserted to it
|
|
379
|
+
// (`("a" as Status)`). No literal is a value of an enum and of another
|
|
380
|
+
// enum or literal at once, so such an intersection has none.
|
|
381
|
+
const values = rendered;
|
|
382
|
+
const isAsserted = (value) => value.endsWith(")");
|
|
383
|
+
const asserted = values.filter(isAsserted);
|
|
384
|
+
if (asserted.length === 0)
|
|
385
|
+
return { expr: values[0] };
|
|
386
|
+
const pinnedElsewhere = members.some((member, index) => !isAsserted(values[index]) && pinnedValues(ctx, member) !== undefined);
|
|
387
|
+
return asserted.length > 1 || pinnedElsewhere
|
|
388
|
+
? undefined
|
|
389
|
+
: { expr: asserted[0] };
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* A schema composed of others. `allOf` and the schema's own properties make
|
|
395
|
+
* one object; of a `oneOf` or `anyOf` the first member that ends is taken.
|
|
396
|
+
*/
|
|
397
|
+
function buildComposed(schema, ctx, indent, seen) {
|
|
398
|
+
const { doc } = ctx.schema;
|
|
399
|
+
const parts = [];
|
|
400
|
+
const members = Array.isArray(schema.allOf) ? schema.allOf : [];
|
|
401
|
+
if (members.length > 0) {
|
|
402
|
+
// What the `allOf` makes required is written out, as the type repeats it:
|
|
403
|
+
// the member that declares it may leave it out. It goes first, so that a
|
|
404
|
+
// member with a value of its own for the property keeps it.
|
|
405
|
+
const required = inheritedRequired(doc, schema);
|
|
406
|
+
const names = Object.keys(required);
|
|
407
|
+
if (names.length > 0) {
|
|
408
|
+
const part = buildObject({ properties: required, required: names }, ctx, indent, seen);
|
|
409
|
+
if (part === undefined)
|
|
410
|
+
return undefined;
|
|
411
|
+
parts.push(part);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const typed = [];
|
|
415
|
+
const firstTyped = parts.length;
|
|
416
|
+
for (const member of members) {
|
|
417
|
+
// A member that says nothing about the type adds nothing to the value.
|
|
418
|
+
if (isRequiredOnly(member))
|
|
419
|
+
continue;
|
|
420
|
+
if (renderSchema(member, ctx.schema) === "unknown")
|
|
421
|
+
continue;
|
|
422
|
+
const part = buildNullable(member, ctx, indent, seen);
|
|
423
|
+
if (part === undefined)
|
|
424
|
+
return undefined;
|
|
425
|
+
typed.push(member);
|
|
426
|
+
parts.push(part);
|
|
427
|
+
}
|
|
428
|
+
if (hasObjectKeywords(schema)) {
|
|
429
|
+
const own = buildObject(schema, ctx, indent, seen);
|
|
430
|
+
if (own === undefined)
|
|
431
|
+
return undefined;
|
|
432
|
+
parts.push(own);
|
|
433
|
+
}
|
|
434
|
+
const isObject = schemaKinds(doc, schema).has("object");
|
|
435
|
+
if (isObject) {
|
|
436
|
+
// A property that several members declare has to be a value of every
|
|
437
|
+
// declaration (`{ a: { x } } & { a: { y } }`), which neither member's own
|
|
438
|
+
// value of it is. It is built from all of them, and goes after the
|
|
439
|
+
// members so that it replaces theirs.
|
|
440
|
+
const declarations = new Map();
|
|
441
|
+
collectDeclarations(ctx, schema, declarations);
|
|
442
|
+
const shared = [];
|
|
443
|
+
const impossible = new Set();
|
|
444
|
+
for (const [name, schemas] of declarations) {
|
|
445
|
+
if (schemas.length < 2)
|
|
446
|
+
continue;
|
|
447
|
+
const value = mockValue({ allOf: schemas }, ctx, `${indent} `, seen);
|
|
448
|
+
if (value !== undefined) {
|
|
449
|
+
shared.push({ key: name, value });
|
|
450
|
+
}
|
|
451
|
+
else if (requiresProperty(doc, schema, name)) {
|
|
452
|
+
return undefined;
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
// No value is one of every declaration, and the property may be
|
|
456
|
+
// absent: it is taken out of what the members give.
|
|
457
|
+
impossible.add(name);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (impossible.size > 0) {
|
|
461
|
+
const sources = [
|
|
462
|
+
...typed,
|
|
463
|
+
...(parts.length > firstTyped + typed.length ? [schema] : []),
|
|
464
|
+
];
|
|
465
|
+
sources.forEach((source, index) => {
|
|
466
|
+
const at = firstTyped + index;
|
|
467
|
+
parts[at] = withoutProperties(parts[at], source, impossible, ctx);
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
if (shared.length > 0)
|
|
471
|
+
parts.push({ entries: shared });
|
|
472
|
+
}
|
|
473
|
+
else if (typed.length > 1) {
|
|
474
|
+
const scalar = buildScalarIntersection(typed, parts.slice(firstTyped, firstTyped + typed.length), ctx, indent);
|
|
475
|
+
if (scalar === undefined)
|
|
476
|
+
return undefined;
|
|
477
|
+
// It stands for every `allOf` member.
|
|
478
|
+
parts.splice(firstTyped, typed.length, scalar);
|
|
479
|
+
}
|
|
480
|
+
for (const key of ["oneOf", "anyOf"]) {
|
|
481
|
+
const options = Array.isArray(schema[key]) ? schema[key] : [];
|
|
482
|
+
if (options.length === 0)
|
|
483
|
+
continue;
|
|
484
|
+
let chosen;
|
|
485
|
+
for (const option of options) {
|
|
486
|
+
const part = buildNullable(option, ctx, indent, seen);
|
|
487
|
+
if (part === undefined)
|
|
488
|
+
continue;
|
|
489
|
+
const values = discriminatorValues(option, schema.discriminator, ctx.schema);
|
|
490
|
+
chosen = values
|
|
491
|
+
? {
|
|
492
|
+
entries: [
|
|
493
|
+
{ spread: print(part, indent) },
|
|
494
|
+
{
|
|
495
|
+
key: schema.discriminator.propertyName,
|
|
496
|
+
value: jsonLiteral(values[0], `${indent} `),
|
|
497
|
+
},
|
|
498
|
+
],
|
|
499
|
+
}
|
|
500
|
+
: part;
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
if (chosen === undefined)
|
|
504
|
+
return undefined;
|
|
505
|
+
parts.push(chosen);
|
|
506
|
+
}
|
|
507
|
+
if (parts.length === 0)
|
|
508
|
+
return { expr: ANY_VALUE };
|
|
509
|
+
if (parts.length === 1)
|
|
510
|
+
return parts[0];
|
|
511
|
+
// Only objects can be put together. Of anything else the first part stands
|
|
512
|
+
// for the whole.
|
|
513
|
+
return isObject ? mergeObjects(parts, indent) : parts[0];
|
|
514
|
+
}
|
|
515
|
+
function build(schema, ctx, indent, seen) {
|
|
516
|
+
if (schema === false)
|
|
517
|
+
return undefined;
|
|
518
|
+
if (!schema || typeof schema !== "object")
|
|
519
|
+
return { expr: ANY_VALUE };
|
|
520
|
+
if (typeof schema.$ref === "string") {
|
|
521
|
+
if (typeof schema[OMITTED_PROPERTY] !== "string") {
|
|
522
|
+
const siblings = refSiblingSchema(ctx.schema.doc, schema);
|
|
523
|
+
if (siblings) {
|
|
524
|
+
return build({ allOf: [{ $ref: schema.$ref }, siblings] }, ctx, indent, seen);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return buildRef(schema.$ref, ctx, indent, seen);
|
|
528
|
+
}
|
|
529
|
+
// What the specification gives as a value comes before anything made up.
|
|
530
|
+
const examples = [
|
|
531
|
+
schema.example,
|
|
532
|
+
...(Array.isArray(schema.examples) ? schema.examples.slice(0, 1) : []),
|
|
533
|
+
schema.default,
|
|
534
|
+
];
|
|
535
|
+
for (const example of examples) {
|
|
536
|
+
if (example === undefined)
|
|
537
|
+
continue;
|
|
538
|
+
const value = exampleValue(schema, example, ctx, indent);
|
|
539
|
+
if (value !== undefined)
|
|
540
|
+
return { expr: value };
|
|
541
|
+
}
|
|
542
|
+
if (schema.const !== undefined) {
|
|
543
|
+
return { expr: jsonLiteral(schema.const, indent) };
|
|
544
|
+
}
|
|
545
|
+
if (Array.isArray(schema.enum)) {
|
|
546
|
+
return schema.enum.length === 0
|
|
547
|
+
? undefined
|
|
548
|
+
: { expr: jsonLiteral(schema.enum[0], indent) };
|
|
549
|
+
}
|
|
550
|
+
if ((Array.isArray(schema.allOf) && schema.allOf.length > 0) ||
|
|
551
|
+
(Array.isArray(schema.oneOf) && schema.oneOf.length > 0) ||
|
|
552
|
+
(Array.isArray(schema.anyOf) && schema.anyOf.length > 0)) {
|
|
553
|
+
return buildComposed(schema, ctx, indent, seen);
|
|
554
|
+
}
|
|
555
|
+
if (Array.isArray(schema.type)) {
|
|
556
|
+
const types = schema.type.filter((type) => type !== "null");
|
|
557
|
+
for (const type of types) {
|
|
558
|
+
const built = build({ ...schema, type }, ctx, indent, seen);
|
|
559
|
+
if (built !== undefined)
|
|
560
|
+
return built;
|
|
561
|
+
}
|
|
562
|
+
return schema.type.includes("null") ? { expr: "null" } : undefined;
|
|
563
|
+
}
|
|
564
|
+
switch (schema.type) {
|
|
565
|
+
case "string":
|
|
566
|
+
if (schema.format === "binary" || hasBinaryContent(schema)) {
|
|
567
|
+
return { expr: "new Blob()" };
|
|
568
|
+
}
|
|
569
|
+
return ctx.schema.dates && isDateString(schema)
|
|
570
|
+
? { expr: `new Date(${JSON.stringify(DATE_TIME)})` }
|
|
571
|
+
: { expr: JSON.stringify(stringSample(schema)) };
|
|
572
|
+
case "number":
|
|
573
|
+
case "integer":
|
|
574
|
+
return { expr: String(numberSample(schema)) };
|
|
575
|
+
case "boolean":
|
|
576
|
+
return { expr: "true" };
|
|
577
|
+
case "null":
|
|
578
|
+
return { expr: "null" };
|
|
579
|
+
case "array":
|
|
580
|
+
return buildArray(schema, ctx, indent, seen);
|
|
581
|
+
case "object":
|
|
582
|
+
return buildObject(schema, ctx, indent, seen);
|
|
583
|
+
default:
|
|
584
|
+
if (impliedType(schema) === "object") {
|
|
585
|
+
return buildObject(schema, ctx, indent, seen);
|
|
586
|
+
}
|
|
587
|
+
if (impliedType(schema) === "array") {
|
|
588
|
+
return buildArray(schema, ctx, indent, seen);
|
|
589
|
+
}
|
|
590
|
+
return { expr: hasBinaryContent(schema) ? "new Blob()" : ANY_VALUE };
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/** `build`, with `null` where the schema allows it and nothing else ends. */
|
|
594
|
+
function buildNullable(schema, ctx, indent, seen) {
|
|
595
|
+
const built = build(schema, ctx, indent, seen);
|
|
596
|
+
if (built !== undefined)
|
|
597
|
+
return built;
|
|
598
|
+
// `renderSchema` ignores `nullable` next to a `$ref` and on an `enum`.
|
|
599
|
+
const nullable = schema &&
|
|
600
|
+
typeof schema === "object" &&
|
|
601
|
+
typeof schema.$ref !== "string" &&
|
|
602
|
+
!Array.isArray(schema.enum) &&
|
|
603
|
+
isNullableSchema(schema);
|
|
604
|
+
return nullable ? { expr: "null" } : undefined;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* An expression for a value of the schema, written for a place at `indent`.
|
|
608
|
+
* Undefined when no value ends: the schema allows none, or holds itself
|
|
609
|
+
* through a mock that is still being built.
|
|
610
|
+
*/
|
|
611
|
+
export function mockValue(schema, ctx, indent = "", seen = new Set()) {
|
|
612
|
+
const built = buildNullable(schema, ctx, indent, seen);
|
|
613
|
+
return built === undefined ? undefined : print(built, indent);
|
|
614
|
+
}
|
|
615
|
+
function sameJson(a, b) {
|
|
616
|
+
return a === b || JSON.stringify(a) === JSON.stringify(b);
|
|
617
|
+
}
|
|
618
|
+
function exampleArray(schema, value, ctx, indent, depth) {
|
|
619
|
+
if (!Array.isArray(value))
|
|
620
|
+
return undefined;
|
|
621
|
+
const prefix = Array.isArray(schema.prefixItems)
|
|
622
|
+
? schema.prefixItems
|
|
623
|
+
: [];
|
|
624
|
+
const open = schema.items !== undefined && schema.items !== false;
|
|
625
|
+
if (Array.isArray(schema.prefixItems)) {
|
|
626
|
+
// A tuple has every one of its items, and no more unless it is open.
|
|
627
|
+
if (value.length < prefix.length)
|
|
628
|
+
return undefined;
|
|
629
|
+
if (!open && value.length > prefix.length)
|
|
630
|
+
return undefined;
|
|
631
|
+
}
|
|
632
|
+
else if (schema.items &&
|
|
633
|
+
typeof schema.maxItems === "number" &&
|
|
634
|
+
schema.maxItems > 0 &&
|
|
635
|
+
schema.maxItems === schema.minItems &&
|
|
636
|
+
value.length !== schema.maxItems) {
|
|
637
|
+
return undefined;
|
|
638
|
+
}
|
|
639
|
+
const items = value.map((item, index) => exampleValue(index < prefix.length ? prefix[index] : schema.items, item, ctx, `${indent} `, depth + 1));
|
|
640
|
+
return items.some((item) => item === undefined)
|
|
641
|
+
? undefined
|
|
642
|
+
: arrayLiteral(items, indent);
|
|
643
|
+
}
|
|
644
|
+
function exampleObject(schema, value, ctx, indent, depth) {
|
|
645
|
+
if (typeof value !== "object" || Array.isArray(value))
|
|
646
|
+
return undefined;
|
|
647
|
+
const inner = `${indent} `;
|
|
648
|
+
const properties = schema.properties ?? {};
|
|
649
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
650
|
+
const entries = [];
|
|
651
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
652
|
+
if (hasFlag(ctx.schema.doc, property, "writeOnly"))
|
|
653
|
+
continue;
|
|
654
|
+
if (!Object.hasOwn(value, name)) {
|
|
655
|
+
if (required.has(name))
|
|
656
|
+
return undefined;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
const rendered = exampleValue(property, value[name], ctx, inner, depth + 1);
|
|
660
|
+
if (rendered === undefined)
|
|
661
|
+
return undefined;
|
|
662
|
+
entries.push({ key: name, value: rendered });
|
|
663
|
+
}
|
|
664
|
+
// The type only takes other keys where it has an index signature.
|
|
665
|
+
const additional = schema.additionalProperties;
|
|
666
|
+
const typed = additional && typeof additional === "object";
|
|
667
|
+
const open = Object.keys(properties).length === 0
|
|
668
|
+
? additional !== false
|
|
669
|
+
: additional === true || typed;
|
|
670
|
+
if (open) {
|
|
671
|
+
for (const [name, extra] of Object.entries(value)) {
|
|
672
|
+
if (Object.hasOwn(properties, name))
|
|
673
|
+
continue;
|
|
674
|
+
const rendered = typed
|
|
675
|
+
? exampleValue(additional, extra, ctx, inner, depth + 1)
|
|
676
|
+
: jsonLiteral(extra, inner);
|
|
677
|
+
if (rendered === undefined)
|
|
678
|
+
return undefined;
|
|
679
|
+
entries.push({ key: name, value: rendered });
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return objectLiteral(entries, indent);
|
|
683
|
+
}
|
|
684
|
+
function exampleOfType(schema, value, ctx, indent, depth) {
|
|
685
|
+
const type = SIMPLE_TYPES.includes(schema.type) ||
|
|
686
|
+
schema.type === "array" ||
|
|
687
|
+
schema.type === "object"
|
|
688
|
+
? schema.type
|
|
689
|
+
: impliedType(schema);
|
|
690
|
+
switch (type) {
|
|
691
|
+
case "string":
|
|
692
|
+
if (typeof value !== "string")
|
|
693
|
+
return undefined;
|
|
694
|
+
if (schema.format === "binary" || hasBinaryContent(schema)) {
|
|
695
|
+
return undefined;
|
|
696
|
+
}
|
|
697
|
+
if (ctx.schema.dates && isDateString(schema)) {
|
|
698
|
+
return Number.isNaN(Date.parse(value))
|
|
699
|
+
? undefined
|
|
700
|
+
: `new Date(${JSON.stringify(value)})`;
|
|
701
|
+
}
|
|
702
|
+
return JSON.stringify(value);
|
|
703
|
+
case "number":
|
|
704
|
+
case "integer":
|
|
705
|
+
return typeof value === "number" &&
|
|
706
|
+
Number.isFinite(value) &&
|
|
707
|
+
(type === "number" || Number.isInteger(value))
|
|
708
|
+
? String(value)
|
|
709
|
+
: undefined;
|
|
710
|
+
case "boolean":
|
|
711
|
+
return typeof value === "boolean" ? String(value) : undefined;
|
|
712
|
+
case "array":
|
|
713
|
+
return exampleArray(schema, value, ctx, indent, depth);
|
|
714
|
+
case "object":
|
|
715
|
+
return exampleObject(schema, value, ctx, indent, depth);
|
|
716
|
+
default:
|
|
717
|
+
// The type is `unknown`, which takes any value.
|
|
718
|
+
return hasBinaryContent(schema) ? undefined : jsonLiteral(value, indent);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* An example from the specification as an expression of the schema's type, or
|
|
723
|
+
* undefined when it is not a value of that type. Examples drift from their
|
|
724
|
+
* schemas, and one that did would not compile. A composed schema is not
|
|
725
|
+
* checked: its example is passed over, and the value is made up instead.
|
|
726
|
+
*/
|
|
727
|
+
export function exampleValue(schema, value, ctx, indent = "", depth = 0) {
|
|
728
|
+
if (schema === false || value === undefined || depth > 32)
|
|
729
|
+
return undefined;
|
|
730
|
+
if (!schema || typeof schema !== "object")
|
|
731
|
+
return jsonLiteral(value, indent);
|
|
732
|
+
const { doc } = ctx.schema;
|
|
733
|
+
if (typeof schema.$ref === "string") {
|
|
734
|
+
if (refSiblingSchema(doc, schema))
|
|
735
|
+
return undefined;
|
|
736
|
+
const target = getByPointer(doc, schema.$ref);
|
|
737
|
+
if (target === undefined)
|
|
738
|
+
return undefined;
|
|
739
|
+
const key = componentSchemaKey(schema.$ref);
|
|
740
|
+
if (key === undefined) {
|
|
741
|
+
return exampleValue(target, value, ctx, indent, depth + 1);
|
|
742
|
+
}
|
|
743
|
+
const rendered = exampleValue(componentSchemaView(target, key, ctx.schema), value, ctx, indent, depth + 1);
|
|
744
|
+
const cast = ctx.enumCast(key);
|
|
745
|
+
return rendered !== undefined && cast !== undefined
|
|
746
|
+
? `(${rendered} as ${cast})`
|
|
747
|
+
: rendered;
|
|
748
|
+
}
|
|
749
|
+
if (schema.oneOf !== undefined ||
|
|
750
|
+
schema.anyOf !== undefined ||
|
|
751
|
+
schema.not !== undefined ||
|
|
752
|
+
schema.discriminator !== undefined ||
|
|
753
|
+
schema.patternProperties !== undefined) {
|
|
754
|
+
return undefined;
|
|
755
|
+
}
|
|
756
|
+
if (Array.isArray(schema.allOf)) {
|
|
757
|
+
// `allOf` around one schema is how OpenAPI 3.0 documents a reference or
|
|
758
|
+
// makes it nullable.
|
|
759
|
+
// What the wrapper adds, the value would have to be checked against too.
|
|
760
|
+
if (schema.allOf.length !== 1 ||
|
|
761
|
+
hasObjectKeywords(schema) ||
|
|
762
|
+
(Array.isArray(schema.required) && schema.required.length > 0)) {
|
|
763
|
+
return undefined;
|
|
764
|
+
}
|
|
765
|
+
if (value === null)
|
|
766
|
+
return isNullableSchema(schema) ? "null" : undefined;
|
|
767
|
+
return exampleValue(schema.allOf[0], value, ctx, indent, depth + 1);
|
|
768
|
+
}
|
|
769
|
+
if (schema.const !== undefined) {
|
|
770
|
+
if (sameJson(schema.const, value))
|
|
771
|
+
return jsonLiteral(value, indent);
|
|
772
|
+
return value === null && isNullableSchema(schema) ? "null" : undefined;
|
|
773
|
+
}
|
|
774
|
+
if (Array.isArray(schema.enum)) {
|
|
775
|
+
return schema.enum.some((member) => sameJson(member, value))
|
|
776
|
+
? jsonLiteral(value, indent)
|
|
777
|
+
: undefined;
|
|
778
|
+
}
|
|
779
|
+
const types = Array.isArray(schema.type)
|
|
780
|
+
? schema.type
|
|
781
|
+
: [schema.type];
|
|
782
|
+
if (value === null) {
|
|
783
|
+
const untyped = schema.type === undefined && !impliedType(schema);
|
|
784
|
+
return isNullableSchema(schema) || types.includes("null") || untyped
|
|
785
|
+
? "null"
|
|
786
|
+
: undefined;
|
|
787
|
+
}
|
|
788
|
+
for (const type of types) {
|
|
789
|
+
if (type === "null")
|
|
790
|
+
continue;
|
|
791
|
+
const rendered = exampleOfType({ ...schema, type }, value, ctx, indent, depth);
|
|
792
|
+
if (rendered !== undefined)
|
|
793
|
+
return rendered;
|
|
794
|
+
}
|
|
795
|
+
return undefined;
|
|
796
|
+
}
|