@7nohe/openapi-react-query-codegen 3.2.1 → 4.0.0-beta.3

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 (49) hide show
  1. package/AGENTS.md +22 -19
  2. package/README.md +5 -4
  3. package/dist/cli.d.mts +6 -1
  4. package/dist/client/emitSchemas.d.mts +9 -0
  5. package/dist/client/emitSchemas.mjs +130 -0
  6. package/dist/client/emitSdk.d.mts +18 -0
  7. package/dist/client/emitSdk.mjs +253 -0
  8. package/dist/client/emitTransformers.d.mts +19 -0
  9. package/dist/client/emitTransformers.mjs +556 -0
  10. package/dist/client/emitTypes.d.mts +16 -0
  11. package/dist/client/emitTypes.mjs +204 -0
  12. package/dist/client/index.d.mts +44 -0
  13. package/dist/client/index.mjs +126 -0
  14. package/dist/client/naming.d.mts +41 -0
  15. package/dist/client/naming.mjs +175 -0
  16. package/dist/client/operations.d.mts +103 -0
  17. package/dist/client/operations.mjs +352 -0
  18. package/dist/client/runtime/axios.runtime.ts +706 -0
  19. package/dist/client/runtime/fetch.runtime.ts +795 -0
  20. package/dist/client/schema.d.mts +50 -0
  21. package/dist/client/schema.mjs +648 -0
  22. package/dist/client/spec.d.mts +40 -0
  23. package/dist/client/spec.mjs +387 -0
  24. package/dist/client/tsconfig.d.mts +12 -0
  25. package/dist/client/tsconfig.mjs +152 -0
  26. package/dist/common.d.mts +0 -38
  27. package/dist/common.mjs +0 -87
  28. package/dist/constants.d.mts +0 -2
  29. package/dist/constants.mjs +0 -2
  30. package/dist/createSource.d.mts +8 -7
  31. package/dist/createSource.mjs +14 -17
  32. package/dist/format.mjs +0 -1
  33. package/dist/generate.d.mts +9 -9
  34. package/dist/generate.mjs +45 -107
  35. package/dist/runCli.mjs +7 -2
  36. package/dist/tsmorph/buildQueryHooks.mjs +19 -11
  37. package/dist/tsmorph/generateFiles.mjs +105 -161
  38. package/dist/tsmorph/operationNames.d.mts +2 -13
  39. package/dist/tsmorph/operationNames.mjs +4 -24
  40. package/dist/tsmorph/projectFactory.d.mts +7 -2
  41. package/dist/tsmorph/projectFactory.mjs +16 -9
  42. package/dist/types.d.mts +14 -26
  43. package/package.json +7 -8
  44. package/dist/parseOperations.d.mts +0 -10
  45. package/dist/parseOperations.mjs +0 -164
  46. package/dist/service.d.mts +0 -8
  47. package/dist/service.mjs +0 -98
  48. package/dist/util.d.mts +0 -2
  49. package/dist/util.mjs +0 -16
@@ -0,0 +1,50 @@
1
+ import { type Doc, type Json } from "./spec.mjs";
2
+ export interface SchemaCtx {
3
+ doc: Doc;
4
+ /** Component schema key → generated TypeScript type name. */
5
+ names: Map<string, string>;
6
+ /**
7
+ * `read` (default) describes what the API returns: `readOnly` properties
8
+ * are marked `readonly` and `writeOnly` ones are left out. `write` describes
9
+ * what a request sends: `readOnly` properties are left out.
10
+ */
11
+ mode?: "read" | "write";
12
+ /** Component schema key → name of its request-side (`write`) variant. */
13
+ writableNames?: Map<string, string>;
14
+ /** Type `date` and `date-time` strings as `Date` (`--useDateType`). */
15
+ dates?: boolean;
16
+ }
17
+ /** Name of the type generated for `#/components/schemas/<key>`, if any. */
18
+ export declare function componentSchemaKey(ref: string): string | undefined;
19
+ /** Render a JSDoc block, or an empty string when there is nothing to say. */
20
+ export declare function docComment(parts: {
21
+ description?: string;
22
+ deprecated?: boolean;
23
+ }, indent?: string): string;
24
+ /** `title` and `description` of a schema, as one documentation text. */
25
+ export declare function schemaDescription(schema: Json): string | undefined;
26
+ type Seen = ReadonlySet<string>;
27
+ /**
28
+ * Render a component schema. A subtype that builds on a schema with a
29
+ * discriminator gets its own value of the discriminator property, from the
30
+ * mapping or else its name, so that a union of subtypes narrows on it.
31
+ */
32
+ export declare function renderComponentSchema(schema: Json, key: string, ctx: SchemaCtx): string;
33
+ /** Render the TypeScript type for an OpenAPI schema object. */
34
+ export declare function renderSchema(schema: Json, ctx: SchemaCtx, indent?: string, seen?: Seen): string;
35
+ /** Whether a string schema holds a date, which `--useDateType` makes a `Date`. */
36
+ export declare function isDateString(schema: Json): boolean;
37
+ /**
38
+ * The values of the discriminator property that a value of `member` has, or
39
+ * undefined when nothing tells the member apart.
40
+ */
41
+ export declare function discriminatorValues(member: Json, discriminator: Json, ctx: SchemaCtx): unknown[] | undefined;
42
+ /** A flag on a property, next to its `$ref` or on what the `$ref` points to. */
43
+ export declare function hasFlag(doc: Doc, property: Json, flag: "readOnly" | "writeOnly"): boolean;
44
+ /**
45
+ * Component schemas that need a separate request-side type: the ones with a
46
+ * `readOnly`/`writeOnly` property, directly or through the schemas they
47
+ * reference.
48
+ */
49
+ export declare function findReadWriteOnlyKeys(doc: Doc): Set<string>;
50
+ export {};
@@ -0,0 +1,648 @@
1
+ import { propertyKey, toTypeName } from "./naming.mjs";
2
+ import { getByPointer, refSiblingSchema, resolveRef, } from "./spec.mjs";
3
+ const COMPONENT_SCHEMA_PREFIX = "#/components/schemas/";
4
+ /** Name of the type generated for `#/components/schemas/<key>`, if any. */
5
+ export function componentSchemaKey(ref) {
6
+ if (!ref.startsWith(COMPONENT_SCHEMA_PREFIX))
7
+ return undefined;
8
+ const rest = ref.slice(COMPONENT_SCHEMA_PREFIX.length);
9
+ if (rest.includes("/"))
10
+ return undefined;
11
+ return decodeURIComponent(rest).replaceAll("~1", "/").replaceAll("~0", "~");
12
+ }
13
+ /** Whether a discriminator mapping target, a `$ref` or a name, is the schema. */
14
+ function isMappingTarget(target, key) {
15
+ if (target === key || target === `${COMPONENT_SCHEMA_PREFIX}${key}`) {
16
+ return true;
17
+ }
18
+ try {
19
+ return componentSchemaKey(target) === key;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ /** Render a JSDoc block, or an empty string when there is nothing to say. */
26
+ export function docComment(parts, indent = "") {
27
+ const lines = [];
28
+ if (parts.description) {
29
+ lines.push(...parts.description.replace(/\*\//g, "*\\/").split("\n"));
30
+ }
31
+ if (parts.deprecated) {
32
+ if (lines.length > 0)
33
+ lines.push("");
34
+ lines.push("@deprecated");
35
+ }
36
+ if (lines.length === 0)
37
+ return "";
38
+ const body = lines
39
+ .map((line) => (line.trim() === "" ? `${indent} *` : `${indent} * ${line}`))
40
+ .join("\n");
41
+ return `${indent}/**\n${body}\n${indent} */\n`;
42
+ }
43
+ /** `title` and `description` of a schema, as one documentation text. */
44
+ export function schemaDescription(schema) {
45
+ if (!schema || typeof schema !== "object")
46
+ return undefined;
47
+ const { title, description } = schema;
48
+ if (typeof title === "string" && title && typeof description === "string") {
49
+ return `${title}\n\n${description}`;
50
+ }
51
+ return ((typeof description === "string" ? description : undefined) ??
52
+ (typeof title === "string" && title ? title : undefined));
53
+ }
54
+ function literal(value) {
55
+ if (value === null)
56
+ return "null";
57
+ if (typeof value === "string")
58
+ return JSON.stringify(value);
59
+ if (typeof value === "number" || typeof value === "boolean") {
60
+ return String(value);
61
+ }
62
+ return "unknown";
63
+ }
64
+ /**
65
+ * True when `type` contains a `|` that is not nested in brackets or quotes, or
66
+ * in a doc comment, whose text is free to have unbalanced ones.
67
+ */
68
+ function hasTopLevelUnion(type) {
69
+ let depth = 0;
70
+ let quote;
71
+ for (let i = 0; i < type.length; i++) {
72
+ const char = type[i];
73
+ if (quote) {
74
+ if (char === "\\")
75
+ i += 1;
76
+ else if (char === quote)
77
+ quote = undefined;
78
+ continue;
79
+ }
80
+ if (char === "/" && type[i + 1] === "*") {
81
+ const end = type.indexOf("*/", i + 2);
82
+ if (end === -1)
83
+ return false;
84
+ i = end + 1;
85
+ }
86
+ else if (char === '"' || char === "'" || char === "`")
87
+ quote = char;
88
+ else if ("{[(<".includes(char))
89
+ depth += 1;
90
+ else if ("}])>".includes(char))
91
+ depth -= 1;
92
+ else if (char === "|" && depth === 0)
93
+ return true;
94
+ }
95
+ return false;
96
+ }
97
+ function union(types) {
98
+ const unique = [...new Set(types)];
99
+ if (unique.length === 0)
100
+ return "never";
101
+ if (unique.includes("unknown"))
102
+ return "unknown";
103
+ return unique.join(" | ");
104
+ }
105
+ function intersection(types) {
106
+ const unique = [...new Set(types)].filter((type) => type !== "unknown");
107
+ if (unique.length === 0)
108
+ return "unknown";
109
+ return unique
110
+ .map((type) => unique.length > 1 && hasTopLevelUnion(type) ? `(${type})` : type)
111
+ .join(" & ");
112
+ }
113
+ function isNullableSchema(schema) {
114
+ return (schema.nullable === true ||
115
+ (Array.isArray(schema.type) && schema.type.includes("null")));
116
+ }
117
+ function addNull(type, schema) {
118
+ if (!isNullableSchema(schema) || type === "null")
119
+ return type;
120
+ return `${type} | null`;
121
+ }
122
+ /**
123
+ * A global type the output refers to. Schemas named `Blob` and `File` are common
124
+ * enough to keep their names, so the global is qualified when one exists.
125
+ */
126
+ function globalTypeRef(name, ctx) {
127
+ return [...ctx.names.values()].includes(name) ? `globalThis.${name}` : name;
128
+ }
129
+ /** Marks a `$ref` member of an `allOf` whose discriminator literal is replaced. */
130
+ const OMITTED_PROPERTY = "x-orqc-omit";
131
+ /** The discriminator of what an `allOf` builds on, if any. */
132
+ function findInheritedDiscriminator(doc, schema, visited = new Set()) {
133
+ const members = Array.isArray(schema?.allOf) ? schema.allOf : [];
134
+ for (const member of members) {
135
+ const resolved = resolveRef(doc, member);
136
+ if (!resolved || typeof resolved !== "object" || visited.has(resolved)) {
137
+ continue;
138
+ }
139
+ visited.add(resolved);
140
+ if (typeof resolved.discriminator?.propertyName === "string") {
141
+ return resolved.discriminator;
142
+ }
143
+ const found = findInheritedDiscriminator(doc, resolved, visited);
144
+ if (found)
145
+ return found;
146
+ }
147
+ return undefined;
148
+ }
149
+ /** True when a schema or what it is composed of requires `name`. */
150
+ function requiresProperty(doc, schema, name, visited = new Set()) {
151
+ const resolved = resolveRef(doc, schema);
152
+ if (!resolved || typeof resolved !== "object" || visited.has(resolved)) {
153
+ return false;
154
+ }
155
+ visited.add(resolved);
156
+ if (Array.isArray(resolved.required) && resolved.required.includes(name)) {
157
+ return true;
158
+ }
159
+ const members = Array.isArray(resolved.allOf) ? resolved.allOf : [];
160
+ return members.some((member) => requiresProperty(doc, member, name, visited));
161
+ }
162
+ /**
163
+ * Render a component schema. A subtype that builds on a schema with a
164
+ * discriminator gets its own value of the discriminator property, from the
165
+ * mapping or else its name, so that a union of subtypes narrows on it.
166
+ */
167
+ export function renderComponentSchema(schema, key, ctx) {
168
+ const discriminator = schema?.discriminator
169
+ ? undefined
170
+ : findInheritedDiscriminator(ctx.doc, schema);
171
+ if (!discriminator)
172
+ return renderSchema(schema, ctx);
173
+ const property = discriminator.propertyName;
174
+ const pinned = pinnedValues(schema, property, ctx);
175
+ const mapped = Object.entries((discriminator.mapping ?? {}))
176
+ .filter(([, target]) => isMappingTarget(target, key))
177
+ .map(([value]) => value);
178
+ const named = mapped.length > 0 ? mapped : [key];
179
+ const allowed = pinned
180
+ ? named.filter((value) => pinned.includes(value))
181
+ : named;
182
+ if (allowed.length === 0 || pinned?.length === 1)
183
+ return renderSchema(schema, ctx);
184
+ const members = schema.allOf.map((member) =>
185
+ // A parent that is a subtype itself has a value of its own to replace.
186
+ typeof member?.$ref === "string" &&
187
+ findInheritedDiscriminator(ctx.doc, resolveRef(ctx.doc, member))
188
+ ? { ...member, [OMITTED_PROPERTY]: property }
189
+ : member);
190
+ const tag = {
191
+ type: "object",
192
+ required: requiresProperty(ctx.doc, schema, property) ? [property] : [],
193
+ properties: { [property]: { enum: allowed } },
194
+ };
195
+ return renderSchema({ ...schema, allOf: [...members, tag] }, ctx);
196
+ }
197
+ /** Render the TypeScript type for an OpenAPI schema object. */
198
+ export function renderSchema(schema, ctx, indent = "", seen = new Set()) {
199
+ if (schema === true || schema === undefined || schema === null) {
200
+ return "unknown";
201
+ }
202
+ if (schema === false)
203
+ return "never";
204
+ if (typeof schema !== "object")
205
+ return "unknown";
206
+ if (typeof schema.$ref === "string") {
207
+ if (typeof schema[OMITTED_PROPERTY] === "string") {
208
+ const parent = renderRef(schema.$ref, ctx, indent, seen);
209
+ return `Omit<${parent}, ${JSON.stringify(schema[OMITTED_PROPERTY])}>`;
210
+ }
211
+ const siblings = refSiblingSchema(ctx.doc, schema);
212
+ return siblings
213
+ ? renderSchema({ allOf: [{ $ref: schema.$ref }, siblings] }, ctx, indent, seen)
214
+ : renderRef(schema.$ref, ctx, indent, seen);
215
+ }
216
+ if (schema.const !== undefined) {
217
+ return addNull(literal(schema.const), schema);
218
+ }
219
+ if (Array.isArray(schema.enum)) {
220
+ // OpenAPI 3.0 only allows null in an enum that lists it, whatever
221
+ // `nullable` says, so `nullable` is deliberately not applied here.
222
+ return union(schema.enum.map(literal));
223
+ }
224
+ // A value has to match every keyword, so `oneOf` and `anyOf` narrow what
225
+ // `allOf` and the schema's own properties describe.
226
+ const unions = ["oneOf", "anyOf"]
227
+ .map((key) => schema[key])
228
+ .filter((options) => Array.isArray(options) && options.length > 0)
229
+ .map((options) => union(options.map((member) => withDiscriminator(member, renderSchema(member, ctx, indent, seen), schema.discriminator, ctx))));
230
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
231
+ const members = schema.allOf
232
+ .filter((member) => !isRequiredOnly(member))
233
+ .map((member) => renderSchema(member, ctx, indent, seen));
234
+ members.push(...unions);
235
+ if (schema.properties ||
236
+ schema.patternProperties ||
237
+ schema.additionalProperties) {
238
+ members.push(renderObject(schema, ctx, indent, seen));
239
+ }
240
+ const required = renderInheritedRequired(schema, ctx, indent, seen);
241
+ if (required !== "{}")
242
+ members.push(required);
243
+ return addNull(intersection(members), schema);
244
+ }
245
+ if (unions.length > 0) {
246
+ const members = schema.properties || schema.additionalProperties
247
+ ? [...unions, renderObject(schema, ctx, indent, seen)]
248
+ : unions;
249
+ return addNull(intersection(members), schema);
250
+ }
251
+ if (Array.isArray(schema.type)) {
252
+ const types = schema.type.filter((type) => type !== "null");
253
+ const rendered = types.map((type) => renderSchema({ ...schema, type }, ctx, indent, seen));
254
+ if (schema.type.includes("null"))
255
+ rendered.push("null");
256
+ return union(rendered);
257
+ }
258
+ let type;
259
+ switch (schema.type) {
260
+ case "string":
261
+ type =
262
+ schema.format === "binary" || hasBinaryContent(schema)
263
+ ? fileType(ctx)
264
+ : ctx.dates && isDateString(schema)
265
+ ? globalTypeRef("Date", ctx)
266
+ : "string";
267
+ break;
268
+ case "number":
269
+ case "integer":
270
+ type = "number";
271
+ break;
272
+ case "boolean":
273
+ type = "boolean";
274
+ break;
275
+ case "null":
276
+ return "null";
277
+ case "array":
278
+ type = renderArray(schema, ctx, indent, seen);
279
+ break;
280
+ case "object":
281
+ type = renderObject(schema, ctx, indent, seen);
282
+ break;
283
+ default:
284
+ if (schema.properties ||
285
+ schema.patternProperties ||
286
+ schema.additionalProperties !== undefined) {
287
+ type = renderObject(schema, ctx, indent, seen);
288
+ }
289
+ else if (schema.items || schema.prefixItems) {
290
+ type = renderArray(schema, ctx, indent, seen);
291
+ }
292
+ else if (hasBinaryContent(schema)) {
293
+ type = fileType(ctx);
294
+ }
295
+ else {
296
+ type = "unknown";
297
+ }
298
+ }
299
+ return addNull(type, schema);
300
+ }
301
+ /** Whether a string schema holds a date, which `--useDateType` makes a `Date`. */
302
+ export function isDateString(schema) {
303
+ return ((schema.format === "date" || schema.format === "date-time") &&
304
+ !hasBinaryContent(schema));
305
+ }
306
+ function fileType(ctx) {
307
+ return `${globalTypeRef("Blob", ctx)} | ${globalTypeRef("File", ctx)}`;
308
+ }
309
+ /** Media types whose content is text, which a string can hold as it is. */
310
+ const TEXT_MEDIA_TYPE = /^(text|multipart)\/|(json|xml|yaml|javascript|ecmascript|html|graphql|x-www-form-urlencoded)$/;
311
+ /**
312
+ * Whether the schema is a file the way OpenAPI 3.1 writes one: a media type
313
+ * that is not text, and no `contentEncoding` making a string of it.
314
+ */
315
+ function hasBinaryContent(schema) {
316
+ const mediaType = schema.contentMediaType;
317
+ return (typeof mediaType === "string" &&
318
+ schema.contentEncoding === undefined &&
319
+ !TEXT_MEDIA_TYPE.test(mediaType.toLowerCase().split(";")[0].trim()));
320
+ }
321
+ /** Keywords that give a schema a type of its own. */
322
+ const TYPE_KEYWORDS = [
323
+ "$ref",
324
+ "additionalProperties",
325
+ "anyOf",
326
+ "const",
327
+ "enum",
328
+ "items",
329
+ "oneOf",
330
+ "prefixItems",
331
+ "properties",
332
+ ];
333
+ /** An `allOf` member that declares nothing and only makes properties required. */
334
+ function isRequiredOnly(member) {
335
+ if (!member ||
336
+ typeof member !== "object" ||
337
+ (member.type !== undefined && member.type !== "object") ||
338
+ TYPE_KEYWORDS.some((key) => member[key] !== undefined)) {
339
+ return false;
340
+ }
341
+ return Array.isArray(member.allOf)
342
+ ? member.allOf.every(isRequiredOnly)
343
+ : Array.isArray(member.required);
344
+ }
345
+ /** The declaration of `name` in a schema or in what it is composed of. */
346
+ function findDeclaredProperty(doc, schema, name, visited = new Set()) {
347
+ const resolved = resolveRef(doc, schema);
348
+ if (!resolved || typeof resolved !== "object" || visited.has(resolved)) {
349
+ return undefined;
350
+ }
351
+ visited.add(resolved);
352
+ if (Object.hasOwn(resolved.properties ?? {}, name)) {
353
+ return resolved.properties[name];
354
+ }
355
+ for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) {
356
+ const found = findDeclaredProperty(doc, member, name, visited);
357
+ if (found !== undefined)
358
+ return found;
359
+ }
360
+ return undefined;
361
+ }
362
+ /**
363
+ * What a schema requires without declaring it, in itself or in what it is
364
+ * composed of. Only the `allOf` around it can know the type of such a property.
365
+ */
366
+ function undeclaredRequired(doc, schema, visited = new Set()) {
367
+ const resolved = resolveRef(doc, schema);
368
+ if (!resolved || typeof resolved !== "object" || visited.has(resolved)) {
369
+ return [];
370
+ }
371
+ visited.add(resolved);
372
+ const own = Array.isArray(resolved.required)
373
+ ? resolved.required
374
+ : [];
375
+ const members = Array.isArray(resolved.allOf) ? resolved.allOf : [];
376
+ return [
377
+ ...own.filter((name) => findDeclaredProperty(doc, resolved, name) === undefined),
378
+ ...members.flatMap((member) => undeclaredRequired(doc, member, visited)),
379
+ ];
380
+ }
381
+ /**
382
+ * The properties an `allOf` requires while another of its members declares them.
383
+ * They are repeated with their own type, because an optional property
384
+ * intersected with `unknown` would stay `undefined`-able. The result is `{}`
385
+ * when there are none.
386
+ */
387
+ function renderInheritedRequired(schema, ctx, indent, seen) {
388
+ const own = Array.isArray(schema.required) ? schema.required : [];
389
+ const names = new Set([
390
+ ...own.filter((name) => !Object.hasOwn(schema.properties ?? {}, name)),
391
+ ...schema.allOf.flatMap((member) => {
392
+ const required = undeclaredRequired(ctx.doc, member);
393
+ // A named schema drops what it requires and nobody declares, so an
394
+ // `allOf` around it does too.
395
+ return member?.$ref
396
+ ? required.filter((name) => findDeclaredProperty(ctx.doc, schema, name) !== undefined)
397
+ : required;
398
+ }),
399
+ ]);
400
+ const properties = Object.fromEntries([...names].map((name) => [
401
+ name,
402
+ findDeclaredProperty(ctx.doc, schema, name) ?? {},
403
+ ]));
404
+ return names.size === 0
405
+ ? "{}"
406
+ : renderObject({ properties, required: [...names] }, ctx, indent, seen);
407
+ }
408
+ function renderRef(ref, ctx, indent, seen) {
409
+ const key = componentSchemaKey(ref);
410
+ if (key !== undefined) {
411
+ // A reference to a schema that is not there has no type to name.
412
+ const schemas = ctx.doc.components?.schemas ?? {};
413
+ if (!Object.hasOwn(schemas, key) && !ctx.names.has(key))
414
+ return "unknown";
415
+ const writable = ctx.writableNames?.get(key);
416
+ if (ctx.mode === "write" && writable !== undefined)
417
+ return writable;
418
+ return ctx.names.get(key) ?? toTypeName(key);
419
+ }
420
+ if (seen.has(ref))
421
+ return "unknown";
422
+ return renderSchema(getByPointer(ctx.doc, ref), ctx, indent, new Set(seen).add(ref));
423
+ }
424
+ /** The literal values the schema pins `property` to (enum or const), if any. */
425
+ function pinnedValues(schema, property, ctx, depth = 0) {
426
+ const resolved = resolveRef(ctx.doc, schema);
427
+ if (!resolved || typeof resolved !== "object" || depth > 16)
428
+ return undefined;
429
+ const declared = resolved.properties?.[property];
430
+ if (declared !== undefined) {
431
+ const target = resolveRef(ctx.doc, declared);
432
+ if (target?.const !== undefined)
433
+ return [target.const];
434
+ return Array.isArray(target?.enum) ? target.enum : undefined;
435
+ }
436
+ for (const member of Array.isArray(resolved.allOf) ? resolved.allOf : []) {
437
+ const pinned = pinnedValues(member, property, ctx, depth + 1);
438
+ if (pinned)
439
+ return pinned;
440
+ }
441
+ return undefined;
442
+ }
443
+ /**
444
+ * What tells a `oneOf`/`anyOf` member apart: the values its discriminator
445
+ * property may take (`allowed`), and the literals the member pins the property
446
+ * to itself, if it does.
447
+ */
448
+ function discriminatorChoice(member, discriminator, ctx) {
449
+ const property = discriminator?.propertyName;
450
+ if (typeof property !== "string" || typeof member?.$ref !== "string") {
451
+ return undefined;
452
+ }
453
+ const key = componentSchemaKey(member.$ref);
454
+ if (key === undefined)
455
+ return undefined;
456
+ // Only object members can carry the property (an array or a primitive
457
+ // intersected with `{ kind: … }` would be unusable).
458
+ const target = ctx.doc.components?.schemas?.[key];
459
+ if (typeof target?.type === "string" && target.type !== "object") {
460
+ return undefined;
461
+ }
462
+ const values = Object.entries((discriminator.mapping ?? {}))
463
+ .filter(([, target]) => isMappingTarget(target, key) || target.endsWith(`/${key}`))
464
+ .map(([value]) => value);
465
+ // A member that pins the property keeps it, unless it inherits an enum of all
466
+ // the subtypes, which the discriminator then narrows down.
467
+ const pinned = pinnedValues(member, property, ctx);
468
+ const named = values.length > 0 ? values : [key];
469
+ const allowed = pinned
470
+ ? named.filter((value) => pinned.includes(value))
471
+ : named;
472
+ return { allowed, pinned };
473
+ }
474
+ /**
475
+ * Intersect a `oneOf`/`anyOf` member with its discriminator value so the
476
+ * union narrows on the discriminator property. Members that already pin the
477
+ * property to other literals are left alone: adding a second literal (from an
478
+ * implicit mapping by schema name) could only make them unreachable.
479
+ */
480
+ function withDiscriminator(member, rendered, discriminator, ctx) {
481
+ const choice = discriminatorChoice(member, discriminator, ctx);
482
+ if (!choice || choice.allowed.length === 0 || choice.pinned?.length === 1) {
483
+ return rendered;
484
+ }
485
+ const literals = choice.allowed.map((value) => JSON.stringify(value));
486
+ return `({ ${propertyKey(discriminator.propertyName)}: ${literals.join(" | ")} } & ${rendered})`;
487
+ }
488
+ /**
489
+ * The values of the discriminator property that a value of `member` has, or
490
+ * undefined when nothing tells the member apart.
491
+ */
492
+ export function discriminatorValues(member, discriminator, ctx) {
493
+ const choice = discriminatorChoice(member, discriminator, ctx);
494
+ if (!choice)
495
+ return undefined;
496
+ if (choice.pinned?.length === 1)
497
+ return choice.pinned;
498
+ return choice.allowed.length > 0 ? choice.allowed : undefined;
499
+ }
500
+ function renderArray(schema, ctx, indent, seen) {
501
+ if (Array.isArray(schema.prefixItems)) {
502
+ const items = schema.prefixItems.map((item) => renderSchema(item, ctx, indent, seen));
503
+ if (schema.items !== undefined && schema.items !== false) {
504
+ items.push(`...Array<${renderSchema(schema.items, ctx, indent, seen)}>`);
505
+ }
506
+ return `[${items.join(", ")}]`;
507
+ }
508
+ // A fixed-length array (`minItems` equals `maxItems`) is a tuple.
509
+ const length = schema.maxItems;
510
+ if (schema.items &&
511
+ typeof length === "number" &&
512
+ length > 0 &&
513
+ length === schema.minItems) {
514
+ const item = renderSchema(schema.items, ctx, indent, seen);
515
+ return `[${Array.from({ length }, () => item).join(", ")}]`;
516
+ }
517
+ return `Array<${renderSchema(schema.items, ctx, indent, seen)}>`;
518
+ }
519
+ /** A flag on a property, next to its `$ref` or on what the `$ref` points to. */
520
+ export function hasFlag(doc, property, flag) {
521
+ return (property?.[flag] === true || resolveRef(doc, property)?.[flag] === true);
522
+ }
523
+ function renderObject(schema, ctx, indent, seen) {
524
+ const properties = schema.properties ?? {};
525
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
526
+ const inner = `${indent} `;
527
+ const lines = [];
528
+ const propertyTypes = [];
529
+ let hasOptional = false;
530
+ const writing = ctx.mode === "write";
531
+ for (const [name, value] of Object.entries(properties)) {
532
+ if (hasFlag(ctx.doc, value, writing ? "readOnly" : "writeOnly"))
533
+ continue;
534
+ const resolved = value && typeof value === "object" && typeof value.$ref === "string"
535
+ ? undefined
536
+ : value;
537
+ const comment = docComment({
538
+ description: schemaDescription(resolved) ?? value?.description,
539
+ deprecated: resolved?.deprecated ?? value?.deprecated,
540
+ }, inner);
541
+ const type = renderSchema(value, ctx, inner, seen);
542
+ const optional = !required.has(name);
543
+ if (optional)
544
+ hasOptional = true;
545
+ propertyTypes.push(type);
546
+ const modifier = !writing && value?.readOnly === true ? "readonly " : "";
547
+ lines.push(`${comment}${inner}${modifier}${propertyKey(name)}${optional ? "?" : ""}: ${type};`);
548
+ }
549
+ const additional = schema.additionalProperties;
550
+ const hasProperties = lines.length > 0;
551
+ const patterns = Object.values((schema.patternProperties ?? {}));
552
+ const hasAdditional = additional === true || (additional && typeof additional === "object");
553
+ if (hasAdditional || patterns.length > 0) {
554
+ const additionalType = !hasAdditional ||
555
+ additional === true ||
556
+ Object.keys(additional).length === 0
557
+ ? undefined
558
+ : renderSchema(additional, ctx, inner, seen);
559
+ // What no pattern matches is free unless `additionalProperties` says not.
560
+ const openEnded = additional !== false && additionalType === undefined ? ["unknown"] : [];
561
+ let valueType = union([
562
+ ...patterns.map((pattern) => renderSchema(pattern, ctx, inner, seen)),
563
+ ...(additionalType ? [additionalType] : []),
564
+ ...openEnded,
565
+ ]);
566
+ if (hasProperties && valueType !== "unknown") {
567
+ valueType = union([
568
+ valueType,
569
+ ...propertyTypes,
570
+ ...(hasOptional ? ["undefined"] : []),
571
+ ]);
572
+ }
573
+ lines.push(`${inner}[key: string]: ${valueType};`);
574
+ }
575
+ else if (Object.keys(properties).length === 0 && additional !== false) {
576
+ lines.push(`${inner}[key: string]: unknown;`);
577
+ }
578
+ // A closed object without properties only accepts `{}`, which the `{}` type
579
+ // does not express: that one accepts anything but null and undefined.
580
+ if (Object.keys(properties).length === 0 &&
581
+ additional === false &&
582
+ patterns.length === 0) {
583
+ return "{ [key: string]: never }";
584
+ }
585
+ if (lines.length === 0)
586
+ return "{}";
587
+ return `{\n${lines.join("\n")}\n${indent}}`;
588
+ }
589
+ function scanReadWriteOnly(doc, schema, found, depth = 0) {
590
+ if (!schema || typeof schema !== "object" || depth > 64)
591
+ return;
592
+ if (typeof schema.$ref === "string") {
593
+ const key = componentSchemaKey(schema.$ref);
594
+ if (key !== undefined)
595
+ found.refs.add(key);
596
+ }
597
+ for (const value of Object.values((schema.properties ?? {}))) {
598
+ if (hasFlag(doc, value, "readOnly") || hasFlag(doc, value, "writeOnly")) {
599
+ found.direct = true;
600
+ }
601
+ scanReadWriteOnly(doc, value, found, depth + 1);
602
+ }
603
+ for (const value of Object.values((schema.patternProperties ?? {}))) {
604
+ scanReadWriteOnly(doc, value, found, depth + 1);
605
+ }
606
+ for (const key of ["allOf", "oneOf", "anyOf", "prefixItems"]) {
607
+ if (Array.isArray(schema[key])) {
608
+ for (const member of schema[key]) {
609
+ scanReadWriteOnly(doc, member, found, depth + 1);
610
+ }
611
+ }
612
+ }
613
+ scanReadWriteOnly(doc, schema.items, found, depth + 1);
614
+ scanReadWriteOnly(doc, schema.additionalProperties, found, depth + 1);
615
+ }
616
+ /**
617
+ * Component schemas that need a separate request-side type: the ones with a
618
+ * `readOnly`/`writeOnly` property, directly or through the schemas they
619
+ * reference.
620
+ */
621
+ export function findReadWriteOnlyKeys(doc) {
622
+ const schemas = (doc.components?.schemas ?? {});
623
+ const direct = new Set();
624
+ const references = new Map();
625
+ for (const [key, schema] of Object.entries(schemas)) {
626
+ const found = { direct: false, refs: new Set() };
627
+ scanReadWriteOnly(doc, schema, found);
628
+ if (found.direct)
629
+ direct.add(key);
630
+ references.set(key, found.refs);
631
+ }
632
+ let changed = true;
633
+ while (changed) {
634
+ changed = false;
635
+ for (const [key, refs] of references) {
636
+ if (direct.has(key))
637
+ continue;
638
+ for (const ref of refs) {
639
+ if (direct.has(ref)) {
640
+ direct.add(key);
641
+ changed = true;
642
+ break;
643
+ }
644
+ }
645
+ }
646
+ }
647
+ return direct;
648
+ }