@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.
- package/AGENTS.md +22 -19
- package/README.md +5 -4
- package/dist/cli.d.mts +6 -1
- package/dist/client/emitSchemas.d.mts +9 -0
- package/dist/client/emitSchemas.mjs +130 -0
- package/dist/client/emitSdk.d.mts +18 -0
- package/dist/client/emitSdk.mjs +253 -0
- package/dist/client/emitTransformers.d.mts +19 -0
- package/dist/client/emitTransformers.mjs +556 -0
- package/dist/client/emitTypes.d.mts +16 -0
- package/dist/client/emitTypes.mjs +204 -0
- package/dist/client/index.d.mts +44 -0
- package/dist/client/index.mjs +126 -0
- package/dist/client/naming.d.mts +41 -0
- package/dist/client/naming.mjs +175 -0
- package/dist/client/operations.d.mts +103 -0
- package/dist/client/operations.mjs +352 -0
- package/dist/client/runtime/axios.runtime.ts +706 -0
- package/dist/client/runtime/fetch.runtime.ts +795 -0
- package/dist/client/schema.d.mts +50 -0
- package/dist/client/schema.mjs +648 -0
- package/dist/client/spec.d.mts +40 -0
- package/dist/client/spec.mjs +387 -0
- package/dist/client/tsconfig.d.mts +12 -0
- package/dist/client/tsconfig.mjs +152 -0
- package/dist/common.d.mts +0 -38
- package/dist/common.mjs +0 -87
- package/dist/constants.d.mts +0 -2
- package/dist/constants.mjs +0 -2
- package/dist/createSource.d.mts +8 -7
- package/dist/createSource.mjs +14 -17
- package/dist/format.mjs +0 -1
- package/dist/generate.d.mts +9 -9
- package/dist/generate.mjs +45 -107
- package/dist/runCli.mjs +7 -2
- package/dist/tsmorph/buildQueryHooks.mjs +19 -11
- package/dist/tsmorph/generateFiles.mjs +105 -161
- package/dist/tsmorph/operationNames.d.mts +2 -13
- package/dist/tsmorph/operationNames.mjs +4 -24
- package/dist/tsmorph/projectFactory.d.mts +7 -2
- package/dist/tsmorph/projectFactory.mjs +16 -9
- package/dist/types.d.mts +14 -26
- package/package.json +7 -8
- package/dist/parseOperations.d.mts +0 -10
- package/dist/parseOperations.mjs +0 -164
- package/dist/service.d.mts +0 -8
- package/dist/service.mjs +0 -98
- package/dist/util.d.mts +0 -2
- package/dist/util.mjs +0 -16
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type Json = any;
|
|
2
|
+
export type Doc = Record<string, Json>;
|
|
3
|
+
/**
|
|
4
|
+
* A specification that could not be loaded: because it, or a document it
|
|
5
|
+
* refers to, could not be read (`not-found`), or because what was read is not
|
|
6
|
+
* a JSON or YAML object (`parse`).
|
|
7
|
+
*/
|
|
8
|
+
export declare class SpecError extends Error {
|
|
9
|
+
readonly reason: "not-found" | "parse";
|
|
10
|
+
constructor(reason: "not-found" | "parse", message: string, options?: {
|
|
11
|
+
cause?: unknown;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
export type LoadedSpec = {
|
|
15
|
+
doc: Doc;
|
|
16
|
+
/** Path or URL the document came from; undefined for inline content. */
|
|
17
|
+
location: string | undefined;
|
|
18
|
+
};
|
|
19
|
+
/** Load a specification from a file path, a URL or inline JSON/YAML content. */
|
|
20
|
+
export declare function loadSpec(input: string): Promise<LoadedSpec>;
|
|
21
|
+
/** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
|
|
22
|
+
export declare function getByPointer(root: Json, pointer: string): Json;
|
|
23
|
+
/**
|
|
24
|
+
* The part of a schema that sits next to its `$ref` and changes the type, as a
|
|
25
|
+
* schema of its own. OpenAPI 3.1 applies such keywords together with the
|
|
26
|
+
* reference, while 3.0 says they are ignored.
|
|
27
|
+
*/
|
|
28
|
+
export declare function refSiblingSchema(doc: Doc, node: Json): Json | undefined;
|
|
29
|
+
/** Follow a chain of `$ref`s. The result is undefined if one dangles. */
|
|
30
|
+
export declare function resolveRef(doc: Doc, node: Json, depth?: number): Json;
|
|
31
|
+
/**
|
|
32
|
+
* Bundle every external `$ref` (relative files and URLs) into the root
|
|
33
|
+
* document. Internal `$ref`s of the root document stay untouched.
|
|
34
|
+
*
|
|
35
|
+
* An external schema becomes a named entry of `components.schemas` and the
|
|
36
|
+
* reference an internal one, so that it is one type however often it is used,
|
|
37
|
+
* a recursive one included. Everything else (parameters, responses, path
|
|
38
|
+
* items) is inlined.
|
|
39
|
+
*/
|
|
40
|
+
export declare function bundleExternalRefs(loaded: LoadedSpec): Promise<Doc>;
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parse as parseYaml } from "yaml";
|
|
6
|
+
import { uniqueName } from "./naming.mjs";
|
|
7
|
+
const URL_RE = /^https?:\/\//i;
|
|
8
|
+
/**
|
|
9
|
+
* A specification that could not be loaded: because it, or a document it
|
|
10
|
+
* refers to, could not be read (`not-found`), or because what was read is not
|
|
11
|
+
* a JSON or YAML object (`parse`).
|
|
12
|
+
*/
|
|
13
|
+
export class SpecError extends Error {
|
|
14
|
+
reason;
|
|
15
|
+
constructor(reason, message, options) {
|
|
16
|
+
super(message, options);
|
|
17
|
+
this.name = "SpecError";
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** JSON when it is, which is much faster to parse than YAML. */
|
|
22
|
+
function parseJsonOrYaml(text) {
|
|
23
|
+
if (text.startsWith("{")) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(text);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// A document in YAML's flow style starts the same way.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return parseYaml(text, { maxAliasCount: -1 });
|
|
32
|
+
}
|
|
33
|
+
function parseText(text, source) {
|
|
34
|
+
const trimmed = text.trim();
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = parseJsonOrYaml(trimmed);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw new SpecError("parse", `Failed to parse the OpenAPI specification (${source}): ${error.message}`, { cause: error });
|
|
41
|
+
}
|
|
42
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
43
|
+
throw new SpecError("parse", `The OpenAPI specification (${source}) must be a JSON/YAML object.`);
|
|
44
|
+
}
|
|
45
|
+
return parsed;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Read a document. `location` in the result is where it really came from, which
|
|
49
|
+
* after a redirect is not the URL asked for and is what its relative `$ref`s
|
|
50
|
+
* resolve against.
|
|
51
|
+
*/
|
|
52
|
+
async function readLocation(location) {
|
|
53
|
+
const unreadable = (verb, cause) => new SpecError("not-found", `Failed to ${verb} ${location}: ${cause.message}`, { cause });
|
|
54
|
+
if (URL_RE.test(location)) {
|
|
55
|
+
const response = await fetch(location).catch((cause) => {
|
|
56
|
+
throw unreadable("fetch", cause);
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
throw new SpecError("not-found", `Failed to fetch ${location}: ${response.status} ${response.statusText}`);
|
|
60
|
+
}
|
|
61
|
+
return { text: await response.text(), location: response.url || location };
|
|
62
|
+
}
|
|
63
|
+
const text = await readFile(location, "utf-8").catch((cause) => {
|
|
64
|
+
throw unreadable("read", cause);
|
|
65
|
+
});
|
|
66
|
+
return { text, location };
|
|
67
|
+
}
|
|
68
|
+
async function loadDocument(location) {
|
|
69
|
+
const read = await readLocation(location);
|
|
70
|
+
return { doc: parseText(read.text, location), location: read.location };
|
|
71
|
+
}
|
|
72
|
+
/** Load a specification from a file path, a URL or inline JSON/YAML content. */
|
|
73
|
+
export async function loadSpec(input) {
|
|
74
|
+
if (URL_RE.test(input))
|
|
75
|
+
return loadDocument(input);
|
|
76
|
+
if (input.startsWith("file:")) {
|
|
77
|
+
return loadDocument(path.resolve(fileURLToPath(input)));
|
|
78
|
+
}
|
|
79
|
+
const looksInline = input.includes("\n") || input.trimStart().startsWith("{");
|
|
80
|
+
if (!looksInline && existsSync(input)) {
|
|
81
|
+
return loadDocument(path.resolve(input));
|
|
82
|
+
}
|
|
83
|
+
if (!looksInline) {
|
|
84
|
+
throw new SpecError("not-found", `OpenAPI specification not found: ${input}`);
|
|
85
|
+
}
|
|
86
|
+
return { doc: parseText(input, "inline content"), location: undefined };
|
|
87
|
+
}
|
|
88
|
+
/** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
|
|
89
|
+
export function getByPointer(root, pointer) {
|
|
90
|
+
const clean = pointer.startsWith("#") ? pointer.slice(1) : pointer;
|
|
91
|
+
if (clean === "" || clean === "/")
|
|
92
|
+
return root;
|
|
93
|
+
let current = root;
|
|
94
|
+
for (const rawSegment of clean.replace(/^\//, "").split("/")) {
|
|
95
|
+
const segment = decodeURIComponent(rawSegment)
|
|
96
|
+
.replaceAll("~1", "/")
|
|
97
|
+
.replaceAll("~0", "~");
|
|
98
|
+
if (current === null || typeof current !== "object")
|
|
99
|
+
return undefined;
|
|
100
|
+
current = current[segment];
|
|
101
|
+
}
|
|
102
|
+
return current;
|
|
103
|
+
}
|
|
104
|
+
const REF_SIBLING_KEYWORDS = [
|
|
105
|
+
"additionalProperties",
|
|
106
|
+
"allOf",
|
|
107
|
+
"anyOf",
|
|
108
|
+
"const",
|
|
109
|
+
"enum",
|
|
110
|
+
"items",
|
|
111
|
+
"oneOf",
|
|
112
|
+
"prefixItems",
|
|
113
|
+
"properties",
|
|
114
|
+
"required",
|
|
115
|
+
];
|
|
116
|
+
/**
|
|
117
|
+
* The part of a schema that sits next to its `$ref` and changes the type, as a
|
|
118
|
+
* schema of its own. OpenAPI 3.1 applies such keywords together with the
|
|
119
|
+
* reference, while 3.0 says they are ignored.
|
|
120
|
+
*/
|
|
121
|
+
export function refSiblingSchema(doc, node) {
|
|
122
|
+
if (typeof doc.openapi !== "string" || doc.openapi.startsWith("3.0")) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
if (!REF_SIBLING_KEYWORDS.some((key) => node[key] !== undefined)) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const { $ref: _ref, ...siblings } = node;
|
|
129
|
+
return siblings;
|
|
130
|
+
}
|
|
131
|
+
/** Follow a chain of `$ref`s. The result is undefined if one dangles. */
|
|
132
|
+
export function resolveRef(doc, node, depth = 0) {
|
|
133
|
+
return typeof node?.$ref === "string" && depth < 32
|
|
134
|
+
? resolveRef(doc, getByPointer(doc, node.$ref), depth + 1)
|
|
135
|
+
: node;
|
|
136
|
+
}
|
|
137
|
+
/** Keywords holding data, where a `$ref` key is not a reference. */
|
|
138
|
+
const DATA_KEYWORDS = new Set([
|
|
139
|
+
"const",
|
|
140
|
+
"default",
|
|
141
|
+
"enum",
|
|
142
|
+
"example",
|
|
143
|
+
"examples",
|
|
144
|
+
]);
|
|
145
|
+
/**
|
|
146
|
+
* Keywords whose keys are names the author chose, so that a property called
|
|
147
|
+
* `example` or a `default` response is not mistaken for a data keyword.
|
|
148
|
+
*/
|
|
149
|
+
const NAME_MAP_KEYWORDS = new Set([
|
|
150
|
+
"$defs",
|
|
151
|
+
"callbacks",
|
|
152
|
+
"definitions",
|
|
153
|
+
"dependentSchemas",
|
|
154
|
+
"encoding",
|
|
155
|
+
"headers",
|
|
156
|
+
"links",
|
|
157
|
+
"parameters",
|
|
158
|
+
"pathItems",
|
|
159
|
+
"paths",
|
|
160
|
+
"patternProperties",
|
|
161
|
+
"properties",
|
|
162
|
+
"requestBodies",
|
|
163
|
+
"responses",
|
|
164
|
+
"schemas",
|
|
165
|
+
"securitySchemes",
|
|
166
|
+
"webhooks",
|
|
167
|
+
]);
|
|
168
|
+
/** The name maps among them whose values are schemas. */
|
|
169
|
+
const SCHEMA_MAP_KEYWORDS = new Set([
|
|
170
|
+
"$defs",
|
|
171
|
+
"definitions",
|
|
172
|
+
"dependentSchemas",
|
|
173
|
+
"patternProperties",
|
|
174
|
+
"properties",
|
|
175
|
+
"schemas",
|
|
176
|
+
]);
|
|
177
|
+
function childPosition(position, key) {
|
|
178
|
+
if (position === "schemaMap")
|
|
179
|
+
return "schema";
|
|
180
|
+
if (position === "nameMap")
|
|
181
|
+
return "other";
|
|
182
|
+
if (SCHEMA_MAP_KEYWORDS.has(key))
|
|
183
|
+
return "schemaMap";
|
|
184
|
+
if (position === "schema")
|
|
185
|
+
return "schema";
|
|
186
|
+
if (key === "schema")
|
|
187
|
+
return "schema";
|
|
188
|
+
return NAME_MAP_KEYWORDS.has(key) ? "nameMap" : "other";
|
|
189
|
+
}
|
|
190
|
+
function resolveLocation(base, target) {
|
|
191
|
+
if (URL_RE.test(target))
|
|
192
|
+
return target;
|
|
193
|
+
if (target.startsWith("file:"))
|
|
194
|
+
return fileURLToPath(target);
|
|
195
|
+
if (!base) {
|
|
196
|
+
throw new Error(`Cannot resolve the external $ref "${target}" because the specification was passed as inline content.`);
|
|
197
|
+
}
|
|
198
|
+
if (URL_RE.test(base))
|
|
199
|
+
return new URL(target, base).toString();
|
|
200
|
+
return path.resolve(path.dirname(base), decodeReference(target));
|
|
201
|
+
}
|
|
202
|
+
/** A `$ref` is a URI reference, so a file name in it can be percent-encoded. */
|
|
203
|
+
function decodeReference(reference) {
|
|
204
|
+
try {
|
|
205
|
+
return decodeURIComponent(reference);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return reference;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** The file a `$ref` points into and the pointer inside it. */
|
|
212
|
+
function locateRef(ref, nodeLocation) {
|
|
213
|
+
const hashIndex = ref.indexOf("#");
|
|
214
|
+
const filePart = hashIndex === -1 ? ref : ref.slice(0, hashIndex);
|
|
215
|
+
const pointer = hashIndex === -1 ? "" : ref.slice(hashIndex);
|
|
216
|
+
const location = filePart
|
|
217
|
+
? resolveLocation(nodeLocation, filePart)
|
|
218
|
+
: nodeLocation;
|
|
219
|
+
return { location, pointer, key: `${location}${pointer}` };
|
|
220
|
+
}
|
|
221
|
+
/** What an external schema is called: its key, or else the name of its file. */
|
|
222
|
+
function externalSchemaName(location, pointer) {
|
|
223
|
+
const last = pointer.slice(pointer.lastIndexOf("/") + 1);
|
|
224
|
+
if (pointer.includes("/") && last) {
|
|
225
|
+
return decodeReference(last).replaceAll("~1", "/").replaceAll("~0", "~");
|
|
226
|
+
}
|
|
227
|
+
const file = path.basename(location.replace(/[?#].*$/, ""));
|
|
228
|
+
return file.replace(/\.[^.]+$/, "") || "Schema";
|
|
229
|
+
}
|
|
230
|
+
function componentSchemaRef(name) {
|
|
231
|
+
const segment = name.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
232
|
+
return `#/components/schemas/${encodeURIComponent(segment)}`;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Bundle every external `$ref` (relative files and URLs) into the root
|
|
236
|
+
* document. Internal `$ref`s of the root document stay untouched.
|
|
237
|
+
*
|
|
238
|
+
* An external schema becomes a named entry of `components.schemas` and the
|
|
239
|
+
* reference an internal one, so that it is one type however often it is used,
|
|
240
|
+
* a recursive one included. Everything else (parameters, responses, path
|
|
241
|
+
* items) is inlined.
|
|
242
|
+
*/
|
|
243
|
+
export async function bundleExternalRefs(loaded) {
|
|
244
|
+
const { doc, location: rootLocation } = loaded;
|
|
245
|
+
const cache = new Map();
|
|
246
|
+
if (rootLocation) {
|
|
247
|
+
cache.set(rootLocation, Promise.resolve({ doc, location: rootLocation }));
|
|
248
|
+
}
|
|
249
|
+
/** The name in `components.schemas` of each external schema. */
|
|
250
|
+
const hoisted = new Map();
|
|
251
|
+
const hoistedSchemas = new Map();
|
|
252
|
+
/** Discriminator mappings, whose targets are rewritten once all are named. */
|
|
253
|
+
const mappings = [];
|
|
254
|
+
const rootSchemas = doc.components?.schemas ?? {};
|
|
255
|
+
const usedNames = new Set(Object.keys(rootSchemas));
|
|
256
|
+
// A root schema that is nothing but an external reference names its target,
|
|
257
|
+
// rather than being an alias of a second type with a made-up name.
|
|
258
|
+
for (const [name, schema] of Object.entries(rootSchemas)) {
|
|
259
|
+
const ref = schema?.$ref;
|
|
260
|
+
if (typeof ref !== "string" || ref.startsWith("#"))
|
|
261
|
+
continue;
|
|
262
|
+
if (Object.keys(schema).length > 1)
|
|
263
|
+
continue;
|
|
264
|
+
const target = locateRef(ref, rootLocation);
|
|
265
|
+
if (target.location !== rootLocation && !hoisted.has(target.key)) {
|
|
266
|
+
hoisted.set(target.key, name);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function loadFile(location) {
|
|
270
|
+
let file = cache.get(location);
|
|
271
|
+
if (!file) {
|
|
272
|
+
file = loadDocument(location);
|
|
273
|
+
cache.set(location, file);
|
|
274
|
+
}
|
|
275
|
+
return file;
|
|
276
|
+
}
|
|
277
|
+
async function loadTarget(target, ref) {
|
|
278
|
+
const file = await loadFile(target.location);
|
|
279
|
+
const node = getByPointer(file.doc, target.pointer);
|
|
280
|
+
if (node === undefined) {
|
|
281
|
+
throw new Error(`Unresolvable $ref: ${ref}`);
|
|
282
|
+
}
|
|
283
|
+
return { node, location: file.location };
|
|
284
|
+
}
|
|
285
|
+
/** Make the target a named schema of the root, once, and refer to it. */
|
|
286
|
+
async function hoist(target, ref, stack) {
|
|
287
|
+
let name = hoisted.get(target.key);
|
|
288
|
+
if (name === undefined) {
|
|
289
|
+
name = uniqueName(externalSchemaName(target.location, target.pointer), usedNames);
|
|
290
|
+
hoisted.set(target.key, name);
|
|
291
|
+
}
|
|
292
|
+
if (!hoistedSchemas.has(name)) {
|
|
293
|
+
// Taken before the target is read, so that the schemas come out in the
|
|
294
|
+
// order they are first used and a recursive one refers to itself.
|
|
295
|
+
hoistedSchemas.set(name, {});
|
|
296
|
+
const { node, location } = await loadTarget(target, ref);
|
|
297
|
+
hoistedSchemas.set(name, await walk(node, location, new Set(stack).add(target.key), "schema"));
|
|
298
|
+
}
|
|
299
|
+
return componentSchemaRef(name);
|
|
300
|
+
}
|
|
301
|
+
// One node after the other, so that the names given to hoisted schemas do
|
|
302
|
+
// not depend on which file happens to be read first.
|
|
303
|
+
async function walk(node, nodeLocation, stack, position) {
|
|
304
|
+
if (Array.isArray(node)) {
|
|
305
|
+
const itemPosition = childPosition(position, "");
|
|
306
|
+
const items = [];
|
|
307
|
+
for (const item of node) {
|
|
308
|
+
items.push(await walk(item, nodeLocation, stack, itemPosition));
|
|
309
|
+
}
|
|
310
|
+
return items;
|
|
311
|
+
}
|
|
312
|
+
if (node === null || typeof node !== "object")
|
|
313
|
+
return node;
|
|
314
|
+
const ref = node.$ref;
|
|
315
|
+
const isExternalFile = nodeLocation !== rootLocation;
|
|
316
|
+
if (typeof ref === "string" && (!ref.startsWith("#") || isExternalFile)) {
|
|
317
|
+
const target = locateRef(ref, nodeLocation);
|
|
318
|
+
const isBackReference = target.location === rootLocation && target.pointer !== "";
|
|
319
|
+
// A file pointing back into the root keeps the root's named type, and an
|
|
320
|
+
// external schema gets one. What sits next to the reference stays there,
|
|
321
|
+
// as it does next to an internal one.
|
|
322
|
+
if (isBackReference || position === "schema" || stack.has(target.key)) {
|
|
323
|
+
const { $ref: _ref, ...rest } = node;
|
|
324
|
+
const siblings = Object.keys(rest).length > 0
|
|
325
|
+
? await walk(rest, nodeLocation, stack, position)
|
|
326
|
+
: undefined;
|
|
327
|
+
return {
|
|
328
|
+
...siblings,
|
|
329
|
+
$ref: isBackReference
|
|
330
|
+
? target.pointer
|
|
331
|
+
: await hoist(target, ref, stack),
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
const loadedTarget = await loadTarget(target, ref);
|
|
335
|
+
return walk(loadedTarget.node, loadedTarget.location, new Set(stack).add(target.key), position);
|
|
336
|
+
}
|
|
337
|
+
const isNameMap = position === "schemaMap" || position === "nameMap";
|
|
338
|
+
const result = {};
|
|
339
|
+
for (const [key, value] of Object.entries(node)) {
|
|
340
|
+
const isData = !isNameMap && (DATA_KEYWORDS.has(key) || key.startsWith("x-"));
|
|
341
|
+
result[key] = isData
|
|
342
|
+
? value
|
|
343
|
+
: await walk(value, nodeLocation, stack, childPosition(position, key));
|
|
344
|
+
}
|
|
345
|
+
const mapping = result.discriminator?.mapping;
|
|
346
|
+
if (!isNameMap && mapping !== null && typeof mapping === "object") {
|
|
347
|
+
mappings.push({ mapping, location: nodeLocation });
|
|
348
|
+
}
|
|
349
|
+
return result;
|
|
350
|
+
}
|
|
351
|
+
const bundled = (await walk(doc, rootLocation, new Set(), "other"));
|
|
352
|
+
// A mapping names its targets the way a `$ref` does, or by schema name.
|
|
353
|
+
for (const { mapping, location } of mappings) {
|
|
354
|
+
for (const [value, target] of Object.entries(mapping)) {
|
|
355
|
+
if (typeof target !== "string")
|
|
356
|
+
continue;
|
|
357
|
+
if (target.startsWith("#") && location === rootLocation)
|
|
358
|
+
continue;
|
|
359
|
+
let name;
|
|
360
|
+
try {
|
|
361
|
+
const located = locateRef(target, location);
|
|
362
|
+
if (located.location === rootLocation && located.pointer !== "") {
|
|
363
|
+
mapping[value] = located.pointer;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
name =
|
|
367
|
+
hoisted.get(located.key) ??
|
|
368
|
+
hoisted.get(`${location}${componentSchemaRef(target)}`) ??
|
|
369
|
+
hoisted.get(`${location}#/components/schemas/${target}`);
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
// Not a reference that can be resolved, so a schema name.
|
|
373
|
+
}
|
|
374
|
+
if (name !== undefined && hoistedSchemas.has(name)) {
|
|
375
|
+
mapping[value] = componentSchemaRef(name);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (hoistedSchemas.size > 0) {
|
|
380
|
+
bundled.components ??= {};
|
|
381
|
+
bundled.components.schemas = {
|
|
382
|
+
...bundled.components.schemas,
|
|
383
|
+
...Object.fromEntries(hoistedSchemas),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
return bundled;
|
|
387
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Find the tsconfig that applies to the generated output by walking up from
|
|
3
|
+
* `startDir`. Anchoring the search at the caller's directory finds the
|
|
4
|
+
* tsconfig the caller's own `tsc` will use.
|
|
5
|
+
*/
|
|
6
|
+
export declare function findNearestTsConfigPath(startDir: string): string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Relative imports must spell out `.js` under Node16/NodeNext module
|
|
9
|
+
* resolution and must not under bundler-style resolution. Read the caller's
|
|
10
|
+
* tsconfig to pick the matching convention.
|
|
11
|
+
*/
|
|
12
|
+
export declare function detectImportExtension(startDir: string): "" | ".js";
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* Find the tsconfig that applies to the generated output by walking up from
|
|
6
|
+
* `startDir`. Anchoring the search at the caller's directory finds the
|
|
7
|
+
* tsconfig the caller's own `tsc` will use.
|
|
8
|
+
*/
|
|
9
|
+
export function findNearestTsConfigPath(startDir) {
|
|
10
|
+
let dir = startDir;
|
|
11
|
+
while (true) {
|
|
12
|
+
const candidates = readdirSync(dir).filter((file) => file.startsWith("tsconfig") && file.endsWith(".json"));
|
|
13
|
+
if (candidates.length > 0) {
|
|
14
|
+
candidates.sort((a) => (a === "tsconfig.json" ? -1 : 1));
|
|
15
|
+
return path.join(dir, candidates[0]);
|
|
16
|
+
}
|
|
17
|
+
const parent = path.dirname(dir);
|
|
18
|
+
if (parent === dir)
|
|
19
|
+
return undefined;
|
|
20
|
+
dir = parent;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Parse a tsconfig, which is JSON with comments and trailing commas. Done here
|
|
25
|
+
* and not with the `typescript` package, so that the generator works with
|
|
26
|
+
* whatever TypeScript the project has: version 7 has no API to read a config.
|
|
27
|
+
*/
|
|
28
|
+
function parseJsonWithComments(text) {
|
|
29
|
+
let json = "";
|
|
30
|
+
let index = text.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
31
|
+
while (index < text.length) {
|
|
32
|
+
const char = text[index];
|
|
33
|
+
const next = text[index + 1];
|
|
34
|
+
if (char === '"') {
|
|
35
|
+
// A string, copied as it is so that nothing inside it is touched.
|
|
36
|
+
let end = index + 1;
|
|
37
|
+
while (end < text.length && text[end] !== '"') {
|
|
38
|
+
end += text[end] === "\\" ? 2 : 1;
|
|
39
|
+
}
|
|
40
|
+
json += text.slice(index, end + 1);
|
|
41
|
+
index = end + 1;
|
|
42
|
+
}
|
|
43
|
+
else if (char === "/" && next === "/") {
|
|
44
|
+
const end = text.indexOf("\n", index);
|
|
45
|
+
index = end === -1 ? text.length : end;
|
|
46
|
+
}
|
|
47
|
+
else if (char === "/" && next === "*") {
|
|
48
|
+
const end = text.indexOf("*/", index + 2);
|
|
49
|
+
index = end === -1 ? text.length : end + 2;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
json += char;
|
|
53
|
+
index += 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// The comments are gone, so a comma before a closing bracket is a trailing
|
|
57
|
+
// one. Strings are skipped as a whole by the first alternative.
|
|
58
|
+
return JSON.parse(json.replace(/("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g, (_match, string, close) => string === undefined ? close : string));
|
|
59
|
+
}
|
|
60
|
+
/** Where an `extends` entry points to, the way TypeScript looks it up. */
|
|
61
|
+
function resolveExtends(target, from) {
|
|
62
|
+
if (target.startsWith(".") || path.isAbsolute(target)) {
|
|
63
|
+
const file = path.resolve(path.dirname(from), target);
|
|
64
|
+
return [file, `${file}.json`].find((candidate) => candidate.endsWith(".json") && existsSync(candidate));
|
|
65
|
+
}
|
|
66
|
+
// A package: its `exports`, or else the file itself or its tsconfig.json.
|
|
67
|
+
const require = createRequire(from);
|
|
68
|
+
for (const candidate of [
|
|
69
|
+
target,
|
|
70
|
+
`${target}.json`,
|
|
71
|
+
`${target}/tsconfig.json`,
|
|
72
|
+
]) {
|
|
73
|
+
try {
|
|
74
|
+
const file = require.resolve(candidate);
|
|
75
|
+
if (file.endsWith(".json"))
|
|
76
|
+
return file;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// Not this spelling.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
/** `module` and `moduleResolution` of a tsconfig, with what it extends. */
|
|
85
|
+
function readModuleOptions(configPath,
|
|
86
|
+
// The files on the way here, so that a circle of `extends` ends.
|
|
87
|
+
chain = new Set()) {
|
|
88
|
+
if (chain.has(configPath))
|
|
89
|
+
return {};
|
|
90
|
+
const config = parseJsonWithComments(readFileSync(configPath, "utf-8"));
|
|
91
|
+
if (!config || typeof config !== "object")
|
|
92
|
+
return {};
|
|
93
|
+
const options = {};
|
|
94
|
+
const apply = (source) => {
|
|
95
|
+
for (const key of ["module", "moduleResolution"]) {
|
|
96
|
+
if (source[key] !== undefined)
|
|
97
|
+
options[key] = source[key];
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
// Later entries win over earlier ones, and the file itself over all of them.
|
|
101
|
+
const parents = Array.isArray(config.extends)
|
|
102
|
+
? config.extends
|
|
103
|
+
: [config.extends];
|
|
104
|
+
for (const parent of parents) {
|
|
105
|
+
if (typeof parent !== "string")
|
|
106
|
+
continue;
|
|
107
|
+
const file = resolveExtends(parent, configPath);
|
|
108
|
+
if (file === undefined)
|
|
109
|
+
continue;
|
|
110
|
+
try {
|
|
111
|
+
apply(readModuleOptions(file, new Set(chain).add(configPath)));
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// A parent that cannot be read adds nothing.
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const own = config.compilerOptions ?? {};
|
|
118
|
+
apply({
|
|
119
|
+
module: typeof own.module === "string" ? own.module.toLowerCase() : undefined,
|
|
120
|
+
moduleResolution: typeof own.moduleResolution === "string"
|
|
121
|
+
? own.moduleResolution.toLowerCase()
|
|
122
|
+
: undefined,
|
|
123
|
+
});
|
|
124
|
+
return options;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Relative imports must spell out `.js` under Node16/NodeNext module
|
|
128
|
+
* resolution and must not under bundler-style resolution. Read the caller's
|
|
129
|
+
* tsconfig to pick the matching convention.
|
|
130
|
+
*/
|
|
131
|
+
export function detectImportExtension(startDir) {
|
|
132
|
+
const configPath = findNearestTsConfigPath(startDir);
|
|
133
|
+
if (!configPath)
|
|
134
|
+
return "";
|
|
135
|
+
let options;
|
|
136
|
+
try {
|
|
137
|
+
options = readModuleOptions(configPath);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// A tsconfig that cannot be read: fall back to the bundler convention
|
|
141
|
+
// rather than failing the whole run.
|
|
142
|
+
return "";
|
|
143
|
+
}
|
|
144
|
+
if (options.moduleResolution !== undefined) {
|
|
145
|
+
return options.moduleResolution === "node16" ||
|
|
146
|
+
options.moduleResolution === "nodenext"
|
|
147
|
+
? ".js"
|
|
148
|
+
: "";
|
|
149
|
+
}
|
|
150
|
+
// `node16`, `node18`, `node20` and later ones resolve the Node way.
|
|
151
|
+
return /^node(1[6-9]|[2-9]\d|next)$/.test(options.module ?? "") ? ".js" : "";
|
|
152
|
+
}
|
package/dist/common.d.mts
CHANGED
|
@@ -1,24 +1,6 @@
|
|
|
1
1
|
import type { PathLike } from "node:fs";
|
|
2
|
-
import { type ClassDeclaration, type ParameterDeclaration, type SourceFile, type VariableDeclaration } from "ts-morph";
|
|
3
|
-
import ts from "typescript";
|
|
4
2
|
import type { LimitedUserConfig } from "./cli.mjs";
|
|
5
|
-
export declare const capitalizeFirstLetter: (str: string) => string;
|
|
6
|
-
export declare const lowercaseFirstLetter: (str: string) => string;
|
|
7
|
-
export declare const getVariableArrowFunctionParameters: (variable: VariableDeclaration) => ParameterDeclaration[];
|
|
8
|
-
export declare const getNameFromVariable: (variable: VariableDeclaration) => string;
|
|
9
|
-
export type FunctionDescription = {
|
|
10
|
-
node: SourceFile;
|
|
11
|
-
method: VariableDeclaration;
|
|
12
|
-
methodBlock?: ts.Block;
|
|
13
|
-
httpMethodName: string;
|
|
14
|
-
jsDoc: string;
|
|
15
|
-
isDeprecated: boolean;
|
|
16
|
-
};
|
|
17
3
|
export declare function exists(f: PathLike): Promise<boolean>;
|
|
18
|
-
/**
|
|
19
|
-
* Build a common type name by prepending the Common namespace.
|
|
20
|
-
*/
|
|
21
|
-
export declare function BuildCommonTypeName(name: string | ts.Identifier): ts.Identifier;
|
|
22
4
|
/**
|
|
23
5
|
* Safely parse a value into a number. Checks for NaN and Infinity.
|
|
24
6
|
* Returns NaN if the string is not a valid number.
|
|
@@ -26,26 +8,6 @@ export declare function BuildCommonTypeName(name: string | ts.Identifier): ts.Id
|
|
|
26
8
|
* @returns The parsed number or NaN if the value is not a valid number.
|
|
27
9
|
*/
|
|
28
10
|
export declare function safeParseNumber(value: unknown): number;
|
|
29
|
-
export declare function extractPropertiesFromObjectParam(param: ParameterDeclaration): {
|
|
30
|
-
name: string;
|
|
31
|
-
optional: boolean;
|
|
32
|
-
type: import("ts-morph").Type<import("ts-morph").ts.Type> | undefined;
|
|
33
|
-
}[];
|
|
34
|
-
/**
|
|
35
|
-
* Replace the import("...") surrounding the type if there is one.
|
|
36
|
-
* This can happen when the type is imported from another file, but
|
|
37
|
-
* we are already importing all the types from that file.
|
|
38
|
-
*
|
|
39
|
-
* https://regex101.com/r/3DyHaQ/1
|
|
40
|
-
*
|
|
41
|
-
* TODO: Replace with a more robust solution.
|
|
42
|
-
*/
|
|
43
|
-
export declare function getShortType(type: string): string;
|
|
44
|
-
export declare function getClassesFromService(node: SourceFile): {
|
|
45
|
-
className: string;
|
|
46
|
-
klass: ClassDeclaration;
|
|
47
|
-
}[];
|
|
48
|
-
export declare function getClassNameFromClassNode(klass: ClassDeclaration): string;
|
|
49
11
|
export declare function formatOptions(options: LimitedUserConfig): LimitedUserConfig;
|
|
50
12
|
export declare function buildRequestsOutputPath(outputPath: string): string;
|
|
51
13
|
export declare function buildQueriesOutputPath(outputPath: string): string;
|