@moccona/apicodegen 0.1.1 → 0.1.2
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/README.md +230 -117
- package/bin/cli.cjs +12 -12
- package/npm/index.cjs +1256 -729
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +124 -50
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +124 -50
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +1254 -729
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +11 -0
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +1074 -535
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +6 -3
package/npm/index.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
1
2
|
import { Agent, request } from "undici";
|
|
2
3
|
import { NodeFlags, SyntaxKind, addSyntheticLeadingComment, createPrinter, factory } from "typescript";
|
|
3
|
-
import { writeFile } from "node:fs/promises";
|
|
4
4
|
import { format } from "prettier";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import fs from "fs-extra";
|
|
7
7
|
import { createScopedLogger } from "@moccona/logger";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
8
9
|
//#region src/core/base/Adaptor.ts
|
|
9
10
|
/**
|
|
10
11
|
* Base adapter for tool
|
|
@@ -90,6 +91,251 @@ const typescriptKeywords = new Set([
|
|
|
90
91
|
"bigint"
|
|
91
92
|
]);
|
|
92
93
|
//#endregion
|
|
94
|
+
//#region src/core/errors.ts
|
|
95
|
+
/**
|
|
96
|
+
* Error handling utilities for api-codegen
|
|
97
|
+
*/
|
|
98
|
+
const ErrorCodes = {
|
|
99
|
+
SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
|
|
100
|
+
SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
|
|
101
|
+
SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
|
|
102
|
+
OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
|
|
103
|
+
CONFIG_INVALID: "E_CONFIG_INVALID",
|
|
104
|
+
VALIDATION_FAILED: "E_VALIDATION_FAILED",
|
|
105
|
+
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
106
|
+
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Custom error class for api-codegen with rich context
|
|
110
|
+
*/
|
|
111
|
+
var ApicodegenError = class ApicodegenError extends Error {
|
|
112
|
+
code;
|
|
113
|
+
location;
|
|
114
|
+
line;
|
|
115
|
+
column;
|
|
116
|
+
path;
|
|
117
|
+
suggestions;
|
|
118
|
+
cause;
|
|
119
|
+
constructor(context) {
|
|
120
|
+
super(context.message);
|
|
121
|
+
this.name = "ApicodegenError";
|
|
122
|
+
this.code = context.code;
|
|
123
|
+
this.location = context.location;
|
|
124
|
+
this.line = context.line;
|
|
125
|
+
this.column = context.column;
|
|
126
|
+
this.path = context.path;
|
|
127
|
+
this.suggestions = context.suggestions || [];
|
|
128
|
+
this.cause = context.cause;
|
|
129
|
+
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Convert error to formatted string for CLI output
|
|
133
|
+
*/
|
|
134
|
+
toString(verbose = false) {
|
|
135
|
+
const lines = [];
|
|
136
|
+
lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
|
|
137
|
+
if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
|
|
138
|
+
if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
|
|
139
|
+
if (this.line !== void 0) {
|
|
140
|
+
let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
|
|
141
|
+
if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
|
|
142
|
+
lines.push(lineInfo);
|
|
143
|
+
}
|
|
144
|
+
if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
|
|
145
|
+
if (verbose && this.cause) {
|
|
146
|
+
lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
|
|
147
|
+
if (this.stack) {
|
|
148
|
+
const stackLines = this.stack.split("\n").slice(1).join("\n");
|
|
149
|
+
lines.push(`\x1b[90m${stackLines}\x1b[0m`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return lines.join("\n");
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Convert to JSON-serializable object
|
|
156
|
+
*/
|
|
157
|
+
toJSON() {
|
|
158
|
+
return {
|
|
159
|
+
name: this.name,
|
|
160
|
+
code: this.code,
|
|
161
|
+
message: this.message,
|
|
162
|
+
location: this.location,
|
|
163
|
+
line: this.line,
|
|
164
|
+
column: this.column,
|
|
165
|
+
path: this.path,
|
|
166
|
+
suggestions: this.suggestions,
|
|
167
|
+
cause: this.cause?.message
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* ANSI color codes for terminal output
|
|
173
|
+
*/
|
|
174
|
+
const Colors = {
|
|
175
|
+
reset: "\x1B[0m",
|
|
176
|
+
bold: "\x1B[1m",
|
|
177
|
+
red: "\x1B[31m",
|
|
178
|
+
green: "\x1B[32m",
|
|
179
|
+
yellow: "\x1B[33m",
|
|
180
|
+
blue: "\x1B[34m",
|
|
181
|
+
cyan: "\x1B[36m",
|
|
182
|
+
gray: "\x1B[90m",
|
|
183
|
+
brightRed: "\x1B[91m",
|
|
184
|
+
brightGreen: "\x1B[92m"
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* Format error for CLI output
|
|
188
|
+
*/
|
|
189
|
+
function formatError(error, verbose = false) {
|
|
190
|
+
if (error instanceof ApicodegenError) return error.toString(verbose);
|
|
191
|
+
if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
|
|
192
|
+
return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Print error to console with formatting
|
|
196
|
+
*/
|
|
197
|
+
function printError(error, verbose = false, stream = process.stderr) {
|
|
198
|
+
stream.write(formatError(error, verbose));
|
|
199
|
+
stream.write("\n");
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Create error with common patterns
|
|
203
|
+
*/
|
|
204
|
+
const createErrors = {
|
|
205
|
+
specNotFound(path, cause) {
|
|
206
|
+
return new ApicodegenError({
|
|
207
|
+
code: ErrorCodes.SPEC_NOT_FOUND,
|
|
208
|
+
message: "OpenAPI spec file not found",
|
|
209
|
+
location: path,
|
|
210
|
+
suggestions: [
|
|
211
|
+
"Check if the file exists using 'ls -la'",
|
|
212
|
+
"Use --spec to provide the correct path",
|
|
213
|
+
"For remote specs, ensure the URL is accessible"
|
|
214
|
+
],
|
|
215
|
+
cause
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
specFetchFailed(url, statusCode, cause) {
|
|
219
|
+
const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
|
|
220
|
+
return new ApicodegenError({
|
|
221
|
+
code: ErrorCodes.SPEC_FETCH_FAILED,
|
|
222
|
+
message,
|
|
223
|
+
location: url,
|
|
224
|
+
suggestions: [
|
|
225
|
+
"Check if the URL is accessible in a browser",
|
|
226
|
+
"Download the spec file locally and use the local path",
|
|
227
|
+
"Verify CORS settings if fetching from a different origin"
|
|
228
|
+
],
|
|
229
|
+
cause
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
specParseFailed(path, line, column, cause) {
|
|
233
|
+
return new ApicodegenError({
|
|
234
|
+
code: ErrorCodes.SPEC_PARSE_FAILED,
|
|
235
|
+
message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
|
|
236
|
+
location: path,
|
|
237
|
+
line,
|
|
238
|
+
column,
|
|
239
|
+
suggestions: [
|
|
240
|
+
"Validate JSON syntax using jsonlint.com",
|
|
241
|
+
"For YAML specs, ensure proper indentation",
|
|
242
|
+
"Check for trailing commas or unquoted special characters"
|
|
243
|
+
],
|
|
244
|
+
cause
|
|
245
|
+
});
|
|
246
|
+
},
|
|
247
|
+
outputDirMissing(path, cause) {
|
|
248
|
+
return new ApicodegenError({
|
|
249
|
+
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
250
|
+
message: "Output directory does not exist",
|
|
251
|
+
location: path,
|
|
252
|
+
suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
|
|
253
|
+
cause
|
|
254
|
+
});
|
|
255
|
+
},
|
|
256
|
+
configInvalid(path, cause) {
|
|
257
|
+
return new ApicodegenError({
|
|
258
|
+
code: ErrorCodes.CONFIG_INVALID,
|
|
259
|
+
message: "Invalid configuration file",
|
|
260
|
+
location: path,
|
|
261
|
+
suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
|
|
262
|
+
cause
|
|
263
|
+
});
|
|
264
|
+
},
|
|
265
|
+
validationFailed(path, details, cause) {
|
|
266
|
+
return new ApicodegenError({
|
|
267
|
+
code: ErrorCodes.VALIDATION_FAILED,
|
|
268
|
+
message: "OpenAPI spec validation failed",
|
|
269
|
+
location: path,
|
|
270
|
+
path: details,
|
|
271
|
+
suggestions: [
|
|
272
|
+
"Check OpenAPI spec structure at the specified path",
|
|
273
|
+
"Ensure all required fields are present",
|
|
274
|
+
"Validate using swagger.io editor"
|
|
275
|
+
],
|
|
276
|
+
cause
|
|
277
|
+
});
|
|
278
|
+
},
|
|
279
|
+
generationFailed(cause) {
|
|
280
|
+
return new ApicodegenError({
|
|
281
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
282
|
+
message: "Code generation failed",
|
|
283
|
+
suggestions: [
|
|
284
|
+
"Check for unsupported OpenAPI features",
|
|
285
|
+
"Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
|
|
286
|
+
"Use --verbose for more details"
|
|
287
|
+
],
|
|
288
|
+
cause
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
typeCheckFailed(path, _errors, cause) {
|
|
292
|
+
return new ApicodegenError({
|
|
293
|
+
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
294
|
+
message: "TypeScript type check failed",
|
|
295
|
+
location: path,
|
|
296
|
+
suggestions: [
|
|
297
|
+
..._errors.length > 0 ? _errors : [],
|
|
298
|
+
"Review type errors above",
|
|
299
|
+
"Check for schema inconsistencies",
|
|
300
|
+
"Update generated types or fix source schema"
|
|
301
|
+
],
|
|
302
|
+
cause
|
|
303
|
+
});
|
|
304
|
+
},
|
|
305
|
+
missingRequiredField(field, context) {
|
|
306
|
+
return new ApicodegenError({
|
|
307
|
+
code: ErrorCodes.VALIDATION_FAILED,
|
|
308
|
+
message: `Missing required field: ${field}`,
|
|
309
|
+
path: context,
|
|
310
|
+
suggestions: [`Add the '${field}' field to your configuration`]
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* Wrap unknown error in ApicodegenError if needed
|
|
316
|
+
*/
|
|
317
|
+
function wrapError(error, context) {
|
|
318
|
+
if (error instanceof ApicodegenError) return error;
|
|
319
|
+
if (error instanceof Error) return new ApicodegenError({
|
|
320
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
321
|
+
message: context?.message || error.message,
|
|
322
|
+
location: context?.location,
|
|
323
|
+
suggestions: context?.suggestions,
|
|
324
|
+
cause: error
|
|
325
|
+
});
|
|
326
|
+
return new ApicodegenError({
|
|
327
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
328
|
+
message: String(error),
|
|
329
|
+
suggestions: context?.suggestions
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Check if error is an ApicodegenError
|
|
334
|
+
*/
|
|
335
|
+
function isApicodegenError(error) {
|
|
336
|
+
return error instanceof ApicodegenError;
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
93
339
|
//#region src/core/interface.ts
|
|
94
340
|
let SchemaType = /* @__PURE__ */ function(SchemaType) {
|
|
95
341
|
SchemaType["schemas"] = "schemas";
|
|
@@ -132,7 +378,6 @@ let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
|
|
|
132
378
|
}({});
|
|
133
379
|
let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
|
|
134
380
|
MediaTypes["JSON"] = "application/json";
|
|
135
|
-
MediaTypes["EVENT_STREAM"] = "text/event-stream";
|
|
136
381
|
MediaTypes["TEXT"] = "text";
|
|
137
382
|
MediaTypes["IMAGE"] = "image";
|
|
138
383
|
MediaTypes["AUDIO"] = "audio";
|
|
@@ -211,8 +456,20 @@ var Base = class Base {
|
|
|
211
456
|
* @param [operationId] - Unique identifier for the operation.
|
|
212
457
|
* @returns - The generated function name.
|
|
213
458
|
*/
|
|
214
|
-
static pathToFnName(path, method,
|
|
215
|
-
|
|
459
|
+
static pathToFnName(path, method, operationId) {
|
|
460
|
+
let name = "";
|
|
461
|
+
let keywordProtected = false;
|
|
462
|
+
if (operationId) {
|
|
463
|
+
keywordProtected = typescriptKeywords.has(operationId);
|
|
464
|
+
name = Base.camelCase(Base.normalize(operationId));
|
|
465
|
+
}
|
|
466
|
+
if (!name) {
|
|
467
|
+
keywordProtected = typescriptKeywords.has(path);
|
|
468
|
+
name = Base.camelCase(Base.normalize(path));
|
|
469
|
+
}
|
|
470
|
+
if (keywordProtected && !name.endsWith("_")) name = `${name}_`;
|
|
471
|
+
const suffix = method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "";
|
|
472
|
+
return name + suffix;
|
|
216
473
|
}
|
|
217
474
|
/**
|
|
218
475
|
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
@@ -221,7 +478,37 @@ var Base = class Base {
|
|
|
221
478
|
*/
|
|
222
479
|
static normalize(text) {
|
|
223
480
|
if (typescriptKeywords.has(text)) text += "_";
|
|
224
|
-
return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d
|
|
481
|
+
return text.replaceAll("...", "").replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d/gm, "");
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Map a request body media type to a stable function-name suffix.
|
|
485
|
+
*
|
|
486
|
+
* Used to disambiguate sibling operations sharing the same path+method
|
|
487
|
+
* but different request body media types. The result is appended (in
|
|
488
|
+
* upperCamelCase) to the operation's base function name.
|
|
489
|
+
*
|
|
490
|
+
* Known types are mapped to short, human-readable names. Unknown types
|
|
491
|
+
* fall back to `camelCase(normalize(<sub-type>))`.
|
|
492
|
+
*
|
|
493
|
+
* @param mediaType - The OpenAPI media type (e.g. `application/json`).
|
|
494
|
+
* @returns - The suffix without leading underscore, or empty string.
|
|
495
|
+
*/
|
|
496
|
+
static mediaTypeToSuffix(mediaType) {
|
|
497
|
+
const known = {
|
|
498
|
+
"application/json": "Json",
|
|
499
|
+
"multipart/form-data": "FormData",
|
|
500
|
+
"application/x-www-form-urlencoded": "FormUrlencoded",
|
|
501
|
+
"application/octet-stream": "OctetStream",
|
|
502
|
+
"text/plain": "Text",
|
|
503
|
+
"text/html": "Html",
|
|
504
|
+
"application/xml": "Xml",
|
|
505
|
+
"text/xml": "Xml"
|
|
506
|
+
};
|
|
507
|
+
const normalized = mediaType.toLowerCase().split(";")[0]?.trim() ?? "";
|
|
508
|
+
if (known[normalized]) return known[normalized];
|
|
509
|
+
const sub = normalized.split("/")[1];
|
|
510
|
+
if (!sub || sub === "*" || normalized === "*/*" || normalized === "") return "";
|
|
511
|
+
return Base.upperCamelCase(Base.normalize(sub));
|
|
225
512
|
}
|
|
226
513
|
/**
|
|
227
514
|
* Capitalizes the first character of a string.
|
|
@@ -249,25 +536,91 @@ var Base = class Base {
|
|
|
249
536
|
* @returns - UpperCamelCase string.
|
|
250
537
|
*/
|
|
251
538
|
static upperCamelCase(text) {
|
|
252
|
-
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(Base.capitalize).join("");
|
|
539
|
+
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map((part) => part.match(/^\d/) ? `N${part}` : Base.capitalize(part)).join("");
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Classify a spec location string into a transport + source pair.
|
|
543
|
+
*
|
|
544
|
+
* Returns:
|
|
545
|
+
* - `{ transport: 'file', source }` when `input` looks like a local
|
|
546
|
+
* filesystem path (`file://...`, POSIX absolute, Windows absolute).
|
|
547
|
+
* - `{ transport: 'http', source }` for `http(s)://...` URLs.
|
|
548
|
+
*
|
|
549
|
+
* Relative paths are treated as `http` so that callers (CLI / Vite
|
|
550
|
+
* plugin) must resolve them against cwd first. This makes intent
|
|
551
|
+
* explicit and avoids accidentally reading from process.cwd().
|
|
552
|
+
*/
|
|
553
|
+
static resolveSpecURL(input) {
|
|
554
|
+
if (input.startsWith("file://")) {
|
|
555
|
+
const stripped = input.replace(/^file:\/\//, "");
|
|
556
|
+
return {
|
|
557
|
+
transport: "file",
|
|
558
|
+
source: /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
if (input.startsWith("/")) return {
|
|
562
|
+
transport: "file",
|
|
563
|
+
source: input
|
|
564
|
+
};
|
|
565
|
+
if (/^[A-Za-z]:[\\/]/.test(input)) return {
|
|
566
|
+
transport: "file",
|
|
567
|
+
source: input
|
|
568
|
+
};
|
|
569
|
+
return {
|
|
570
|
+
transport: "http",
|
|
571
|
+
source: input
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Read and parse a local OpenAPI document from the filesystem.
|
|
576
|
+
*
|
|
577
|
+
* @param filePath - Absolute filesystem path to the spec.
|
|
578
|
+
* @returns - A promise resolving to the parsed document.
|
|
579
|
+
*/
|
|
580
|
+
static async readLocalDoc(filePath) {
|
|
581
|
+
let raw;
|
|
582
|
+
try {
|
|
583
|
+
raw = await readFile(filePath, "utf8");
|
|
584
|
+
} catch (error) {
|
|
585
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
|
|
586
|
+
throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
return JSON.parse(raw);
|
|
590
|
+
} catch (error) {
|
|
591
|
+
throw createErrors.specParseFailed(filePath, void 0, void 0, error);
|
|
592
|
+
}
|
|
253
593
|
}
|
|
254
594
|
/**
|
|
255
595
|
* Fetches documentation from a given URL.
|
|
256
|
-
*
|
|
257
|
-
*
|
|
596
|
+
*
|
|
597
|
+
* Supports three transport modes:
|
|
598
|
+
* - `file://...` URLs → read from filesystem (parsed as JSON)
|
|
599
|
+
* - absolute filesystem paths → read from filesystem (parsed as JSON)
|
|
600
|
+
* - `http(s)://...` URLs (and unrecognised inputs like relative paths)
|
|
601
|
+
* → fetched via undici (existing behavior)
|
|
602
|
+
*
|
|
603
|
+
* Callers should pass an already-resolved absolute path or URL. Relative
|
|
604
|
+
* paths fall through to undici by design — CLI / Vite plugin should
|
|
605
|
+
* resolve them against cwd first.
|
|
606
|
+
*
|
|
607
|
+
* @param url - The URL or filesystem path to fetch the documentation from.
|
|
608
|
+
* @param requestInit - Additional request parameters (only used for http(s)).
|
|
258
609
|
* @returns - A promise resolving to the fetched documentation data.
|
|
259
610
|
*/
|
|
260
611
|
static async fetchDoc(url, requestInit = {}) {
|
|
261
|
-
const {
|
|
612
|
+
const { transport, source } = Base.resolveSpecURL(url);
|
|
613
|
+
if (transport === "file") return Base.readLocalDoc(source);
|
|
614
|
+
const { body, statusCode } = await request(source, {
|
|
262
615
|
method: "GET",
|
|
263
616
|
dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
|
|
264
617
|
...requestInit
|
|
265
618
|
});
|
|
266
|
-
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${
|
|
619
|
+
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
|
|
267
620
|
try {
|
|
268
621
|
return body.json();
|
|
269
622
|
} catch (error) {
|
|
270
|
-
throw new Error(`Failed to parse JSON response from ${
|
|
623
|
+
throw new Error(`Failed to parse JSON response from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
271
624
|
}
|
|
272
625
|
}
|
|
273
626
|
/**
|
|
@@ -410,255 +763,35 @@ var Provider = class {
|
|
|
410
763
|
this.enums = enums;
|
|
411
764
|
this.schemas = schemas;
|
|
412
765
|
this.responses = responses;
|
|
413
|
-
this.parameters = parameters;
|
|
414
|
-
this.requestBodies = requestBodies;
|
|
415
|
-
this.apis = apis;
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
//#endregion
|
|
419
|
-
//#region src/core/errors.ts
|
|
420
|
-
/**
|
|
421
|
-
* Error handling utilities for api-codegen
|
|
422
|
-
*/
|
|
423
|
-
const ErrorCodes = {
|
|
424
|
-
SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
|
|
425
|
-
SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
|
|
426
|
-
SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
|
|
427
|
-
OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
|
|
428
|
-
CONFIG_INVALID: "E_CONFIG_INVALID",
|
|
429
|
-
VALIDATION_FAILED: "E_VALIDATION_FAILED",
|
|
430
|
-
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
431
|
-
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
432
|
-
};
|
|
433
|
-
/**
|
|
434
|
-
* Custom error class for api-codegen with rich context
|
|
435
|
-
*/
|
|
436
|
-
var ApicodegenError = class ApicodegenError extends Error {
|
|
437
|
-
code;
|
|
438
|
-
location;
|
|
439
|
-
line;
|
|
440
|
-
column;
|
|
441
|
-
path;
|
|
442
|
-
suggestions;
|
|
443
|
-
cause;
|
|
444
|
-
constructor(context) {
|
|
445
|
-
super(context.message);
|
|
446
|
-
this.name = "ApicodegenError";
|
|
447
|
-
this.code = context.code;
|
|
448
|
-
this.location = context.location;
|
|
449
|
-
this.line = context.line;
|
|
450
|
-
this.column = context.column;
|
|
451
|
-
this.path = context.path;
|
|
452
|
-
this.suggestions = context.suggestions || [];
|
|
453
|
-
this.cause = context.cause;
|
|
454
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
455
|
-
}
|
|
456
|
-
/**
|
|
457
|
-
* Convert error to formatted string for CLI output
|
|
458
|
-
*/
|
|
459
|
-
toString(verbose = false) {
|
|
460
|
-
const lines = [];
|
|
461
|
-
lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
|
|
462
|
-
if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
|
|
463
|
-
if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
|
|
464
|
-
if (this.line !== void 0) {
|
|
465
|
-
let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
|
|
466
|
-
if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
|
|
467
|
-
lines.push(lineInfo);
|
|
468
|
-
}
|
|
469
|
-
if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
|
|
470
|
-
if (verbose && this.cause) {
|
|
471
|
-
lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
|
|
472
|
-
if (this.stack) {
|
|
473
|
-
const stackLines = this.stack.split("\n").slice(1).join("\n");
|
|
474
|
-
lines.push(`\x1b[90m${stackLines}\x1b[0m`);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
return lines.join("\n");
|
|
478
|
-
}
|
|
479
|
-
/**
|
|
480
|
-
* Convert to JSON-serializable object
|
|
481
|
-
*/
|
|
482
|
-
toJSON() {
|
|
483
|
-
return {
|
|
484
|
-
name: this.name,
|
|
485
|
-
code: this.code,
|
|
486
|
-
message: this.message,
|
|
487
|
-
location: this.location,
|
|
488
|
-
line: this.line,
|
|
489
|
-
column: this.column,
|
|
490
|
-
path: this.path,
|
|
491
|
-
suggestions: this.suggestions,
|
|
492
|
-
cause: this.cause?.message
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
};
|
|
496
|
-
/**
|
|
497
|
-
* ANSI color codes for terminal output
|
|
498
|
-
*/
|
|
499
|
-
const Colors = {
|
|
500
|
-
reset: "\x1B[0m",
|
|
501
|
-
bold: "\x1B[1m",
|
|
502
|
-
red: "\x1B[31m",
|
|
503
|
-
green: "\x1B[32m",
|
|
504
|
-
yellow: "\x1B[33m",
|
|
505
|
-
blue: "\x1B[34m",
|
|
506
|
-
cyan: "\x1B[36m",
|
|
507
|
-
gray: "\x1B[90m",
|
|
508
|
-
brightRed: "\x1B[91m",
|
|
509
|
-
brightGreen: "\x1B[92m"
|
|
510
|
-
};
|
|
511
|
-
/**
|
|
512
|
-
* Format error for CLI output
|
|
513
|
-
*/
|
|
514
|
-
function formatError(error, verbose = false) {
|
|
515
|
-
if (error instanceof ApicodegenError) return error.toString(verbose);
|
|
516
|
-
if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
|
|
517
|
-
return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Print error to console with formatting
|
|
521
|
-
*/
|
|
522
|
-
function printError(error, verbose = false, stream = process.stderr) {
|
|
523
|
-
stream.write(formatError(error, verbose));
|
|
524
|
-
stream.write("\n");
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Create error with common patterns
|
|
528
|
-
*/
|
|
529
|
-
const createErrors = {
|
|
530
|
-
specNotFound(path, cause) {
|
|
531
|
-
return new ApicodegenError({
|
|
532
|
-
code: ErrorCodes.SPEC_NOT_FOUND,
|
|
533
|
-
message: "OpenAPI spec file not found",
|
|
534
|
-
location: path,
|
|
535
|
-
suggestions: [
|
|
536
|
-
"Check if the file exists using 'ls -la'",
|
|
537
|
-
"Use --spec to provide the correct path",
|
|
538
|
-
"For remote specs, ensure the URL is accessible"
|
|
539
|
-
],
|
|
540
|
-
cause
|
|
541
|
-
});
|
|
542
|
-
},
|
|
543
|
-
specFetchFailed(url, statusCode, cause) {
|
|
544
|
-
const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
|
|
545
|
-
return new ApicodegenError({
|
|
546
|
-
code: ErrorCodes.SPEC_FETCH_FAILED,
|
|
547
|
-
message,
|
|
548
|
-
location: url,
|
|
549
|
-
suggestions: [
|
|
550
|
-
"Check if the URL is accessible in a browser",
|
|
551
|
-
"Download the spec file locally and use the local path",
|
|
552
|
-
"Verify CORS settings if fetching from a different origin"
|
|
553
|
-
],
|
|
554
|
-
cause
|
|
555
|
-
});
|
|
556
|
-
},
|
|
557
|
-
specParseFailed(path, line, column, cause) {
|
|
558
|
-
return new ApicodegenError({
|
|
559
|
-
code: ErrorCodes.SPEC_PARSE_FAILED,
|
|
560
|
-
message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
|
|
561
|
-
location: path,
|
|
562
|
-
line,
|
|
563
|
-
column,
|
|
564
|
-
suggestions: [
|
|
565
|
-
"Validate JSON syntax using jsonlint.com",
|
|
566
|
-
"For YAML specs, ensure proper indentation",
|
|
567
|
-
"Check for trailing commas or unquoted special characters"
|
|
568
|
-
],
|
|
569
|
-
cause
|
|
570
|
-
});
|
|
571
|
-
},
|
|
572
|
-
outputDirMissing(path, cause) {
|
|
573
|
-
return new ApicodegenError({
|
|
574
|
-
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
575
|
-
message: "Output directory does not exist",
|
|
576
|
-
location: path,
|
|
577
|
-
suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
|
|
578
|
-
cause
|
|
579
|
-
});
|
|
580
|
-
},
|
|
581
|
-
configInvalid(path, cause) {
|
|
582
|
-
return new ApicodegenError({
|
|
583
|
-
code: ErrorCodes.CONFIG_INVALID,
|
|
584
|
-
message: "Invalid configuration file",
|
|
585
|
-
location: path,
|
|
586
|
-
suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
|
|
587
|
-
cause
|
|
588
|
-
});
|
|
589
|
-
},
|
|
590
|
-
validationFailed(path, details, cause) {
|
|
591
|
-
return new ApicodegenError({
|
|
592
|
-
code: ErrorCodes.VALIDATION_FAILED,
|
|
593
|
-
message: "OpenAPI spec validation failed",
|
|
594
|
-
location: path,
|
|
595
|
-
path: details,
|
|
596
|
-
suggestions: [
|
|
597
|
-
"Check OpenAPI spec structure at the specified path",
|
|
598
|
-
"Ensure all required fields are present",
|
|
599
|
-
"Validate using swagger.io editor"
|
|
600
|
-
],
|
|
601
|
-
cause
|
|
602
|
-
});
|
|
603
|
-
},
|
|
604
|
-
generationFailed(cause) {
|
|
605
|
-
return new ApicodegenError({
|
|
606
|
-
code: ErrorCodes.GENERATION_FAILED,
|
|
607
|
-
message: "Code generation failed",
|
|
608
|
-
suggestions: [
|
|
609
|
-
"Check for unsupported OpenAPI features",
|
|
610
|
-
"Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
|
|
611
|
-
"Use --verbose for more details"
|
|
612
|
-
],
|
|
613
|
-
cause
|
|
614
|
-
});
|
|
615
|
-
},
|
|
616
|
-
typeCheckFailed(path, _errors, cause) {
|
|
617
|
-
return new ApicodegenError({
|
|
618
|
-
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
619
|
-
message: "TypeScript type check failed",
|
|
620
|
-
location: path,
|
|
621
|
-
suggestions: [
|
|
622
|
-
"Review type errors above",
|
|
623
|
-
"Check for schema inconsistencies",
|
|
624
|
-
"Update generated types or fix source schema"
|
|
625
|
-
],
|
|
626
|
-
cause
|
|
627
|
-
});
|
|
628
|
-
},
|
|
629
|
-
missingRequiredField(field, context) {
|
|
630
|
-
return new ApicodegenError({
|
|
631
|
-
code: ErrorCodes.VALIDATION_FAILED,
|
|
632
|
-
message: `Missing required field: ${field}`,
|
|
633
|
-
path: context,
|
|
634
|
-
suggestions: [`Add the '${field}' field to your configuration`]
|
|
635
|
-
});
|
|
766
|
+
this.parameters = parameters;
|
|
767
|
+
this.requestBodies = requestBodies;
|
|
768
|
+
this.apis = apis;
|
|
636
769
|
}
|
|
637
770
|
};
|
|
771
|
+
//#endregion
|
|
772
|
+
//#region src/core/generator/naming.ts
|
|
638
773
|
/**
|
|
639
|
-
*
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
652
|
-
message: String(error),
|
|
653
|
-
suggestions: context?.suggestions
|
|
654
|
-
});
|
|
655
|
-
}
|
|
656
|
-
/**
|
|
657
|
-
* Check if error is an ApicodegenError
|
|
774
|
+
* Create a per-generation unique-name resolver.
|
|
775
|
+
*
|
|
776
|
+
* Tracks how many times each base name has been seen during a single
|
|
777
|
+
* code generation pass and returns a unique variant on every call:
|
|
778
|
+
*
|
|
779
|
+
* reserve('foo') // 'foo'
|
|
780
|
+
* reserve('foo') // 'foo2'
|
|
781
|
+
* reserve('foo') // 'foo3'
|
|
782
|
+
* reserve('bar') // 'bar' (independent counter)
|
|
783
|
+
*
|
|
784
|
+
* The resolver holds no module-level state — create one per generation pass
|
|
785
|
+
* and let it go out of scope when the pass completes.
|
|
658
786
|
*/
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
787
|
+
const createUniqueNameResolver = () => {
|
|
788
|
+
const seen = /* @__PURE__ */ new Map();
|
|
789
|
+
return (name) => {
|
|
790
|
+
const next = (seen.get(name) ?? 0) + 1;
|
|
791
|
+
seen.set(name, next);
|
|
792
|
+
return next === 1 ? name : `${name}${next}`;
|
|
793
|
+
};
|
|
794
|
+
};
|
|
662
795
|
//#endregion
|
|
663
796
|
//#region src/core/generator/index.ts
|
|
664
797
|
var Generator = class Generator {
|
|
@@ -675,19 +808,10 @@ var Generator = class Generator {
|
|
|
675
808
|
return createPrinter().printFile(sourceFile);
|
|
676
809
|
}
|
|
677
810
|
static async write(code, filepath) {
|
|
678
|
-
const { mkdir } = await import("node:fs/promises");
|
|
679
|
-
const { dirname } = await import("node:path");
|
|
680
811
|
try {
|
|
681
|
-
await mkdir(dirname(filepath), { recursive: true });
|
|
682
812
|
await writeFile(filepath, code);
|
|
683
813
|
} catch (error) {
|
|
684
|
-
|
|
685
|
-
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
686
|
-
message: "Failed to write generated code to output file",
|
|
687
|
-
location: filepath,
|
|
688
|
-
cause: error instanceof Error ? error : new Error(String(error)),
|
|
689
|
-
suggestions: ["Verify the output directory path is writable", "Check that the parent directory exists or can be created"]
|
|
690
|
-
});
|
|
814
|
+
console.error(error);
|
|
691
815
|
}
|
|
692
816
|
}
|
|
693
817
|
/**
|
|
@@ -702,7 +826,7 @@ var Generator = class Generator {
|
|
|
702
826
|
static toUrlTemplate(path, parameters, basePath = "") {
|
|
703
827
|
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
704
828
|
if (queryParameters.length > 0) {
|
|
705
|
-
const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.normalize(qp.name)}}`).join("");
|
|
829
|
+
const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.camelCase(Base.normalize(qp.name))}}`).join("");
|
|
706
830
|
path += queryString;
|
|
707
831
|
}
|
|
708
832
|
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
@@ -711,7 +835,7 @@ var Generator = class Generator {
|
|
|
711
835
|
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
712
836
|
const isLastSegment = index === pathSegments.length - 2;
|
|
713
837
|
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
714
|
-
return factory.createTemplateSpan(factory.createIdentifier(
|
|
838
|
+
return factory.createTemplateSpan(factory.createIdentifier(match[1]), !isLastSegment ? factory.createTemplateMiddle(match[2]) : factory.createTemplateTail(match[2] || ""));
|
|
715
839
|
}));
|
|
716
840
|
}
|
|
717
841
|
/**
|
|
@@ -724,7 +848,10 @@ var Generator = class Generator {
|
|
|
724
848
|
if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
|
|
725
849
|
const formatComment = (comment) => {
|
|
726
850
|
if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
|
|
727
|
-
if (comment.tag === "param")
|
|
851
|
+
if (comment.tag === "param") {
|
|
852
|
+
const typePart = comment.type ? `{${comment.type}} ` : "";
|
|
853
|
+
return comment.comment ? `* @param ${typePart}${comment.paramName} - ${comment.comment}` : `* @param ${typePart}${comment.paramName}`;
|
|
854
|
+
}
|
|
728
855
|
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
729
856
|
return `* ${comment.comment}`;
|
|
730
857
|
};
|
|
@@ -763,15 +890,16 @@ var Generator = class Generator {
|
|
|
763
890
|
static generateParamTags(parameters, requestBody) {
|
|
764
891
|
const tags = [];
|
|
765
892
|
for (const p of parameters) {
|
|
766
|
-
const paramName = Base.normalize(p.name);
|
|
893
|
+
const paramName = Base.camelCase(Base.normalize(p.name));
|
|
767
894
|
let paramType = "unknown";
|
|
768
895
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
769
896
|
const isOptional = p.required === false;
|
|
897
|
+
const inPrefix = p.in ? `[${p.in}] ` : "";
|
|
770
898
|
tags.push({
|
|
771
899
|
tag: "param",
|
|
772
900
|
paramName,
|
|
773
901
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
774
|
-
comment: p.description ?? ""
|
|
902
|
+
comment: `${inPrefix}${p.description ?? ""}`
|
|
775
903
|
});
|
|
776
904
|
}
|
|
777
905
|
if (requestBody?.schema && "properties" in requestBody.schema) {
|
|
@@ -810,9 +938,10 @@ var Generator = class Generator {
|
|
|
810
938
|
const propsCount = Object.keys(schema.properties ?? {}).length;
|
|
811
939
|
if (!schema.properties || propsCount === 0) return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [factory.createToken(SyntaxKind.StringKeyword), factory.createToken(SyntaxKind.UnknownKeyword)]);
|
|
812
940
|
const props = Object.keys(schema.properties);
|
|
941
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
813
942
|
return factory.createTypeLiteralNode(props.map((propKey) => {
|
|
814
943
|
const propSchema = schema.properties[propKey];
|
|
815
|
-
return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey),
|
|
944
|
+
return factory.createPropertySignature(void 0, factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : factory.createToken(SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
|
|
816
945
|
}));
|
|
817
946
|
}
|
|
818
947
|
case "integer":
|
|
@@ -833,25 +962,46 @@ var Generator = class Generator {
|
|
|
833
962
|
}
|
|
834
963
|
if (enum_) return factory.createUnionTypeNode(enum_.map((e) => factory.createLiteralTypeNode(factory.createStringLiteral(e))));
|
|
835
964
|
if (type === "string") return factory.createToken(SyntaxKind.StringKeyword);
|
|
836
|
-
if (oneOf)
|
|
837
|
-
|
|
965
|
+
if (oneOf) {
|
|
966
|
+
const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
|
|
967
|
+
return factory.createUnionTypeNode(uniqueTypes);
|
|
968
|
+
}
|
|
969
|
+
if (anyOf) {
|
|
970
|
+
const uniqueTypes = Generator.deduplicateTypes(anyOf.map((s) => Generator.toTypeNode(s)));
|
|
971
|
+
return factory.createUnionTypeNode(uniqueTypes);
|
|
972
|
+
}
|
|
838
973
|
if (allOf) return factory.createIntersectionTypeNode(allOf.map((schema) => Generator.toTypeNode(schema)));
|
|
839
974
|
if (type && typeof type === "string") return factory.createTypeReferenceNode(type !== "unknown" && type !== "null" ? factory.createIdentifier(Base.upperCamelCase(type)) : type);
|
|
840
975
|
}
|
|
841
976
|
}
|
|
842
977
|
return factory.createToken(SyntaxKind.UnknownKeyword);
|
|
843
978
|
}
|
|
979
|
+
static deduplicateTypes(types) {
|
|
980
|
+
const seen = /* @__PURE__ */ new Set();
|
|
981
|
+
const unique = [];
|
|
982
|
+
for (const type of types) {
|
|
983
|
+
const key = Generator.getTypeNodeKey(type);
|
|
984
|
+
if (!seen.has(key)) {
|
|
985
|
+
seen.add(key);
|
|
986
|
+
unique.push(type);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
return unique;
|
|
990
|
+
}
|
|
991
|
+
static getTypeNodeKey(type) {
|
|
992
|
+
return JSON.stringify(type);
|
|
993
|
+
}
|
|
844
994
|
static toDeclarationNodes(parameters) {
|
|
845
995
|
const objectElements = [];
|
|
846
996
|
const typeObjectElements = [];
|
|
847
997
|
const refParameters = [];
|
|
848
998
|
for (const parameter of parameters) if (parameter.ref) {
|
|
849
999
|
const refName = Base.ref2name(parameter.ref);
|
|
850
|
-
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.normalize(refName)), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
1000
|
+
refParameters.push(factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier(Base.camelCase(Base.normalize(refName))), void 0, factory.createTypeReferenceNode(factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
851
1001
|
} else {
|
|
852
1002
|
const { name, schema, required } = parameter;
|
|
853
|
-
objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.normalize(name))));
|
|
854
|
-
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.normalize(name)), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
1003
|
+
objectElements.push(factory.createBindingElement(void 0, void 0, factory.createIdentifier(Base.camelCase(Base.normalize(name)))));
|
|
1004
|
+
typeObjectElements.push(factory.createPropertySignature([], factory.createIdentifier(Base.camelCase(Base.normalize(name))), required ? void 0 : factory.createToken(SyntaxKind.QuestionToken), !schema ? factory.createToken(SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
855
1005
|
}
|
|
856
1006
|
if (objectElements.length > 0) return [factory.createParameterDeclaration(void 0, void 0, factory.createObjectBindingPattern(objectElements), void 0, factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
857
1007
|
return refParameters;
|
|
@@ -875,17 +1025,77 @@ var Generator = class Generator {
|
|
|
875
1025
|
});
|
|
876
1026
|
return statements;
|
|
877
1027
|
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Build statements that construct a `URLSearchParams` from request body
|
|
1030
|
+
* fields for an `application/x-www-form-urlencoded` request.
|
|
1031
|
+
*
|
|
1032
|
+
* Skips `undefined` / `null` values so optional fields don't end up as
|
|
1033
|
+
* the literal string `"undefined"` in the URL (fixes #8).
|
|
1034
|
+
*
|
|
1035
|
+
* The resulting `sp` variable is referenced by the adapter as the
|
|
1036
|
+
* `body` payload.
|
|
1037
|
+
*/
|
|
1038
|
+
static toURLSearchParamsStatement(parameters, requestBody) {
|
|
1039
|
+
const statements = [];
|
|
1040
|
+
const spDeclaration = factory.createVariableStatement(void 0, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createIdentifier("sp"), void 0, void 0, factory.createNewExpression(factory.createIdentifier("URLSearchParams"), void 0, []))], NodeFlags.Const));
|
|
1041
|
+
statements.push(spDeclaration);
|
|
1042
|
+
const appendValue = (key, valueExpr) => factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("sp"), factory.createIdentifier("append")), void 0, [factory.createStringLiteral(key), valueExpr]));
|
|
1043
|
+
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) for (const key of Object.keys(requestBody.properties)) {
|
|
1044
|
+
const fieldSchema = requestBody.properties[key];
|
|
1045
|
+
const required = !!fieldSchema.required;
|
|
1046
|
+
const accessor = factory.createElementAccessExpression(factory.createIdentifier("req"), factory.createStringLiteral(key));
|
|
1047
|
+
const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
|
|
1048
|
+
if (required) statements.push(append);
|
|
1049
|
+
else statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([append], true)));
|
|
1050
|
+
}
|
|
1051
|
+
for (const parameter of parameters) {
|
|
1052
|
+
if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
|
|
1053
|
+
const accessor = factory.createIdentifier(Base.camelCase(Base.normalize(parameter.name)));
|
|
1054
|
+
statements.push(factory.createIfStatement(factory.createBinaryExpression(accessor, factory.createToken(SyntaxKind.ExclamationEqualsToken), factory.createToken(SyntaxKind.NullKeyword)), factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
|
|
1055
|
+
}
|
|
1056
|
+
return statements;
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Render `expr` as a string suitable for `FormData.append` /
|
|
1060
|
+
* `URLSearchParams.append`. Object/array schemas are JSON-stringified,
|
|
1061
|
+
* everything else is coerced via `String(...)`.
|
|
1062
|
+
*/
|
|
1063
|
+
static toFormDataCompatibleString(expr, schema) {
|
|
1064
|
+
if (schema && (schema.type === "object" || schema.type === "array")) return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), void 0, [expr]);
|
|
1065
|
+
return factory.createCallExpression(factory.createIdentifier("String"), void 0, [expr]);
|
|
1066
|
+
}
|
|
878
1067
|
static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
|
|
879
|
-
const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(requestBody.type);
|
|
880
1068
|
const shouldParseResponseToJSON = "application/json" === response?.type;
|
|
881
|
-
const isEventStream = response?.type === "text/event-stream";
|
|
882
|
-
const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
|
|
883
1069
|
const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
|
|
884
1070
|
const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
|
|
1071
|
+
const inBody = parametersShouldNotPutInFormData.filter((p) => !p.in || p.in === "body");
|
|
885
1072
|
const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
|
|
886
1073
|
const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
|
|
887
|
-
const
|
|
888
|
-
|
|
1074
|
+
const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
|
|
1075
|
+
const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
|
|
1076
|
+
let bodyKind = "none";
|
|
1077
|
+
let bodyContentType;
|
|
1078
|
+
if (mediaType === "multipart/form-data") {
|
|
1079
|
+
if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1080
|
+
} else if (mediaType === "application/x-www-form-urlencoded") {
|
|
1081
|
+
bodyKind = "urlencoded";
|
|
1082
|
+
bodyContentType = "application/x-www-form-urlencoded";
|
|
1083
|
+
} else if (mediaType === "application/json") {
|
|
1084
|
+
if (requestBody?.schema || inBody.length > 0) {
|
|
1085
|
+
bodyKind = "json";
|
|
1086
|
+
bodyContentType = "application/json";
|
|
1087
|
+
}
|
|
1088
|
+
} else if (requestSchemaIsBinary) {
|
|
1089
|
+
bodyKind = "binary";
|
|
1090
|
+
bodyContentType = requestBody?.type;
|
|
1091
|
+
} else if (requestBody?.schema) {
|
|
1092
|
+
bodyKind = "json";
|
|
1093
|
+
bodyContentType = requestBody?.type;
|
|
1094
|
+
}
|
|
1095
|
+
const preStatements = [];
|
|
1096
|
+
if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
|
|
1097
|
+
else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
|
|
1098
|
+
return factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
|
|
889
1099
|
}
|
|
890
1100
|
static schemaToStatemets(parsedDoc, adaptor, options) {
|
|
891
1101
|
const statements = [];
|
|
@@ -893,14 +1103,16 @@ var Generator = class Generator {
|
|
|
893
1103
|
const enumNames = [];
|
|
894
1104
|
for (const enumObject of enums) {
|
|
895
1105
|
enumNames.push(Base.upperCamelCase(enumObject.name));
|
|
896
|
-
statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member) => {
|
|
897
|
-
|
|
1106
|
+
statements.push(factory.createEnumDeclaration([factory.createToken(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member, index) => {
|
|
1107
|
+
const key = typeof member === "string" ? member : `Value${member}`;
|
|
1108
|
+
return factory.createEnumMember(factory.createStringLiteral(key), typeof member === "string" ? factory.createStringLiteral(member) : factory.createNumericLiteral(member));
|
|
898
1109
|
})));
|
|
899
1110
|
}
|
|
900
1111
|
for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
|
|
901
1112
|
const schema = schemas[schemaKey];
|
|
902
1113
|
statements.push(factory.createTypeAliasDeclaration([factory.createModifier(SyntaxKind.ExportKeyword)], factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
|
|
903
1114
|
}
|
|
1115
|
+
const reserveUnique = createUniqueNameResolver();
|
|
904
1116
|
for (const uri in apis) {
|
|
905
1117
|
const operations = apis[uri];
|
|
906
1118
|
for (const operation of operations) {
|
|
@@ -910,7 +1122,7 @@ var Generator = class Generator {
|
|
|
910
1122
|
if (requestBody.length === 0) requestBody.push({ type: "application/json" });
|
|
911
1123
|
const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
|
|
912
1124
|
for (const req of requestBody) {
|
|
913
|
-
const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.
|
|
1125
|
+
const statement = factory.createFunctionDeclaration([factory.createModifier(SyntaxKind.ExportKeyword), factory.createModifier(SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [], ...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : []].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor));
|
|
914
1126
|
const mergedDescription = [description, summary].filter(Boolean).join(". ");
|
|
915
1127
|
Generator.addComments(statement, [
|
|
916
1128
|
mergedDescription && { comment: mergedDescription },
|
|
@@ -938,7 +1150,7 @@ var Generator = class Generator {
|
|
|
938
1150
|
//#region src/core/client/axios.ts
|
|
939
1151
|
/**
|
|
940
1152
|
* Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
|
|
941
|
-
* This
|
|
1153
|
+
* This adapter defines custom behavior and field mappings specific to the Axios client.
|
|
942
1154
|
*/
|
|
943
1155
|
var AxiosAdapter = class extends Adapter {
|
|
944
1156
|
/**
|
|
@@ -962,35 +1174,38 @@ var AxiosAdapter = class extends Adapter {
|
|
|
962
1174
|
*/
|
|
963
1175
|
name = "axios";
|
|
964
1176
|
/**
|
|
965
|
-
*
|
|
966
|
-
*
|
|
967
|
-
* @
|
|
968
|
-
* @param parameters - Array of parameters to include in the request
|
|
969
|
-
* @param requestBody - The request body media type definition
|
|
970
|
-
* @param response - The response media type definition
|
|
971
|
-
* @param adapter - The adapter instance
|
|
972
|
-
* @param shouldUseFormData - Flag to use FormData for the request body
|
|
973
|
-
* @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
|
|
974
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
|
|
975
|
-
* @return - An array of generated TypeScript statements
|
|
1177
|
+
* Method that should generate and return the client-specific configuration statements.
|
|
1178
|
+
*
|
|
1179
|
+
* @returns {Statement[]} An array of TypeScript statements that define the client configuration.
|
|
976
1180
|
*/
|
|
977
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1181
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
|
|
978
1182
|
const statements = [];
|
|
979
|
-
|
|
1183
|
+
parameters.filter((p) => !p.in || p.in === "body");
|
|
980
1184
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1185
|
+
const toLiterlExpression = () => {
|
|
1186
|
+
const headerEntries = [];
|
|
1187
|
+
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
|
|
1188
|
+
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
1189
|
+
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1190
|
+
if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
|
|
1191
|
+
let bodyExpr;
|
|
1192
|
+
switch (bodyKind) {
|
|
1193
|
+
case "form-data":
|
|
1194
|
+
bodyExpr = factory.createIdentifier("fd");
|
|
1195
|
+
break;
|
|
1196
|
+
case "urlencoded":
|
|
1197
|
+
bodyExpr = factory.createIdentifier("sp");
|
|
1198
|
+
break;
|
|
1199
|
+
case "json":
|
|
1200
|
+
case "binary":
|
|
1201
|
+
bodyExpr = factory.createIdentifier("req");
|
|
1202
|
+
break;
|
|
1203
|
+
case "none": break;
|
|
1204
|
+
}
|
|
1205
|
+
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1206
|
+
return factory.createObjectLiteralExpression(properties, true);
|
|
988
1207
|
};
|
|
989
|
-
|
|
990
|
-
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression([factory.createPropertyAssignment(factory.createIdentifier("adapter"), factory.createStringLiteral("fetch")), factory.createPropertyAssignment(factory.createIdentifier("responseType"), factory.createStringLiteral("stream"))])])));
|
|
991
|
-
return statements;
|
|
992
|
-
}
|
|
993
|
-
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
1208
|
+
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [factory.createTypeReferenceNode(factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
994
1209
|
return statements;
|
|
995
1210
|
}
|
|
996
1211
|
};
|
|
@@ -1014,12 +1229,12 @@ var FetchAdapter = class extends Adapter {
|
|
|
1014
1229
|
* @param requestBody - The request body media type definition
|
|
1015
1230
|
* @param response - The response media type definition
|
|
1016
1231
|
* @param adapter - The adapter instance
|
|
1017
|
-
* @param
|
|
1232
|
+
* @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
|
|
1233
|
+
* @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
|
|
1018
1234
|
* @param shouldUseJSONResponse - Flag to use JSON parsing for the response
|
|
1019
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
|
|
1020
1235
|
* @return - An array of generated TypeScript statements
|
|
1021
1236
|
*/
|
|
1022
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1237
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
|
|
1023
1238
|
const statements = [];
|
|
1024
1239
|
const inBody = parameters.filter((p) => !p.in || p.in === "body");
|
|
1025
1240
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
@@ -1029,19 +1244,49 @@ var FetchAdapter = class extends Adapter {
|
|
|
1029
1244
|
* @returns - The constructed fetch options object
|
|
1030
1245
|
*/
|
|
1031
1246
|
const toLiterlExpression = () => {
|
|
1032
|
-
|
|
1247
|
+
const headerEntries = [];
|
|
1248
|
+
for (const p of inHeader) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral(p.name), factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [factory.createCallExpression(factory.createIdentifier("String"), void 0, [factory.createIdentifier(Base.camelCase(Base.normalize(p.name)))])])));
|
|
1249
|
+
if (bodyContentType !== void 0) headerEntries.push(factory.createPropertyAssignment(factory.createStringLiteral("Content-Type"), factory.createStringLiteral(bodyContentType)));
|
|
1250
|
+
const properties = [factory.createPropertyAssignment(factory.createIdentifier(adapter.methodFieldName), factory.createStringLiteral(method.toUpperCase()))];
|
|
1251
|
+
if (headerEntries.length > 0) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.headersFieldName), factory.createObjectLiteralExpression(headerEntries)));
|
|
1252
|
+
let bodyExpr;
|
|
1253
|
+
switch (bodyKind) {
|
|
1254
|
+
case "form-data":
|
|
1255
|
+
bodyExpr = factory.createIdentifier("fd");
|
|
1256
|
+
break;
|
|
1257
|
+
case "urlencoded":
|
|
1258
|
+
bodyExpr = factory.createIdentifier("sp");
|
|
1259
|
+
break;
|
|
1260
|
+
case "json": {
|
|
1261
|
+
const arg = requestBody ? factory.createIdentifier("req") : factory.createObjectLiteralExpression(inBody.map((b) => factory.createShorthandPropertyAssignment(factory.createIdentifier(b.name))), true);
|
|
1262
|
+
bodyExpr = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("JSON"), factory.createIdentifier("stringify")), [], [arg]);
|
|
1263
|
+
break;
|
|
1264
|
+
}
|
|
1265
|
+
case "binary":
|
|
1266
|
+
bodyExpr = factory.createIdentifier("req");
|
|
1267
|
+
break;
|
|
1268
|
+
case "none": break;
|
|
1269
|
+
}
|
|
1270
|
+
if (bodyExpr) properties.push(factory.createPropertyAssignment(factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1271
|
+
return factory.createObjectLiteralExpression(properties, true);
|
|
1033
1272
|
};
|
|
1034
|
-
|
|
1035
|
-
statements.push(factory.createReturnStatement(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
1036
|
-
return statements;
|
|
1037
|
-
}
|
|
1038
|
-
statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), response?.schema ? factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : factory.createToken(SyntaxKind.UnknownKeyword)) : factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))))]) : factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
1273
|
+
statements.push(factory.createReturnStatement(shouldUseJSONResponse ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), factory.createIdentifier("then")), void 0, [factory.createArrowFunction([factory.createModifier(SyntaxKind.AsyncKeyword)], [], [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("response"))], void 0, factory.createToken(SyntaxKind.EqualsGreaterThanToken), response?.schema ? factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), Generator.toTypeNode(response.schema)) : factory.createAsExpression(factory.createParenthesizedExpression(factory.createAwaitExpression(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("response"), factory.createIdentifier("json")), void 0, []))), factory.createToken(SyntaxKind.UnknownKeyword)))]) : factory.createCallExpression(factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
|
|
1039
1274
|
return statements;
|
|
1040
1275
|
}
|
|
1041
1276
|
};
|
|
1042
1277
|
//#endregion
|
|
1043
1278
|
//#region src/core/config.ts
|
|
1044
1279
|
/**
|
|
1280
|
+
* Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
|
|
1281
|
+
*/
|
|
1282
|
+
const TRUTHY_STRINGS = new Set([
|
|
1283
|
+
"true",
|
|
1284
|
+
"1",
|
|
1285
|
+
"yes",
|
|
1286
|
+
"on",
|
|
1287
|
+
"enable"
|
|
1288
|
+
]);
|
|
1289
|
+
/**
|
|
1045
1290
|
* Environment variable mappings
|
|
1046
1291
|
*/
|
|
1047
1292
|
const ENV_MAPPINGS = {
|
|
@@ -1064,10 +1309,10 @@ function loadFromEnv() {
|
|
|
1064
1309
|
case "verbose":
|
|
1065
1310
|
case "watch":
|
|
1066
1311
|
case "typeCheck":
|
|
1067
|
-
config[configKey] = value
|
|
1312
|
+
config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
|
|
1068
1313
|
break;
|
|
1069
1314
|
case "adaptor":
|
|
1070
|
-
config[configKey] = value;
|
|
1315
|
+
if (Object.values(Adaptors).includes(value)) config[configKey] = value;
|
|
1071
1316
|
break;
|
|
1072
1317
|
default: config[configKey] = value;
|
|
1073
1318
|
}
|
|
@@ -1134,7 +1379,7 @@ function mergeConfigs(base, ...sources) {
|
|
|
1134
1379
|
const result = { ...base };
|
|
1135
1380
|
for (const source of sources) {
|
|
1136
1381
|
if (!source) continue;
|
|
1137
|
-
for (const [key, value] of Object.entries(source)) if (value !== void 0) result[key] = value;
|
|
1382
|
+
for (const [key, value] of Object.entries(source)) if (value !== void 0 && value !== null) result[key] = value;
|
|
1138
1383
|
}
|
|
1139
1384
|
return result;
|
|
1140
1385
|
}
|
|
@@ -1183,6 +1428,20 @@ async function loadConfig(options = {}) {
|
|
|
1183
1428
|
};
|
|
1184
1429
|
}
|
|
1185
1430
|
/**
|
|
1431
|
+
* Create CLI options from config for commander
|
|
1432
|
+
*/
|
|
1433
|
+
function configToCLIOptions(config) {
|
|
1434
|
+
const options = {};
|
|
1435
|
+
if (config.spec) options.spec = config.spec;
|
|
1436
|
+
if (config.output) options.output = config.output;
|
|
1437
|
+
if (config.adaptor) options.adaptor = config.adaptor;
|
|
1438
|
+
if (config.baseURL) options.baseURL = config.baseURL;
|
|
1439
|
+
if (config.verbose) options.verbose = config.verbose;
|
|
1440
|
+
if (config.watch) options.watch = config.watch;
|
|
1441
|
+
if (config.importClientSource) options.importClientSource = config.importClientSource;
|
|
1442
|
+
return options;
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1186
1445
|
* Convert resolved config to provider options format
|
|
1187
1446
|
*/
|
|
1188
1447
|
function toProviderOptions(config) {
|
|
@@ -1197,74 +1456,265 @@ function toProviderOptions(config) {
|
|
|
1197
1456
|
};
|
|
1198
1457
|
}
|
|
1199
1458
|
//#endregion
|
|
1200
|
-
//#region src/
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1459
|
+
//#region src/openapi/V2.ts
|
|
1460
|
+
var V2 = class {
|
|
1461
|
+
doc;
|
|
1462
|
+
constructor(doc) {
|
|
1463
|
+
this.doc = doc;
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Resolves a path $ref to the actual path object.
|
|
1467
|
+
*/
|
|
1468
|
+
resolvePathRef($ref) {
|
|
1469
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
1470
|
+
return this.doc.paths?.[refName];
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Is array schema.
|
|
1474
|
+
*/
|
|
1475
|
+
isOpenAPIArraySchema(schema) {
|
|
1476
|
+
return typeof schema === "object" && schema.type === "array";
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* OpenAPI schema to base schema.
|
|
1480
|
+
*/
|
|
1481
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
1482
|
+
let refName = "";
|
|
1483
|
+
if (Base.isRef(schema)) {
|
|
1484
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
1485
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
1486
|
+
if (!this.doc.definitions) this.doc.definitions = {};
|
|
1487
|
+
schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
|
|
1488
|
+
}
|
|
1489
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Transform all OpenAPI schema to Base Schema
|
|
1493
|
+
*/
|
|
1494
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
1495
|
+
if (!schema) return { type: "unknown" };
|
|
1496
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1497
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
1498
|
+
const { type, description, items, required } = schema;
|
|
1499
|
+
return {
|
|
1500
|
+
type,
|
|
1501
|
+
required: !!required,
|
|
1502
|
+
description,
|
|
1503
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1504
|
+
};
|
|
1505
|
+
} else {
|
|
1506
|
+
const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1507
|
+
let { type } = schema;
|
|
1508
|
+
if (enum_ && type !== "boolean") {
|
|
1509
|
+
const enumObject = {
|
|
1510
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
|
|
1511
|
+
enum: [...new Set(enum_)]
|
|
1512
|
+
};
|
|
1513
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1514
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1515
|
+
return {
|
|
1516
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
1517
|
+
required,
|
|
1518
|
+
description
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1522
|
+
return {
|
|
1523
|
+
type,
|
|
1524
|
+
required,
|
|
1525
|
+
description,
|
|
1526
|
+
enum: enum_,
|
|
1527
|
+
format,
|
|
1528
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1529
|
+
...s,
|
|
1530
|
+
ref: s.$ref,
|
|
1531
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1532
|
+
} : this.toBaseSchema(s, enums)),
|
|
1533
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
1534
|
+
...s,
|
|
1535
|
+
ref: s.$ref,
|
|
1536
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1537
|
+
} : this.toBaseSchema(s, enums)),
|
|
1538
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
1539
|
+
...s,
|
|
1540
|
+
ref: s.$ref,
|
|
1541
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1542
|
+
} : this.toBaseSchema(s, enums)),
|
|
1543
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
1544
|
+
const propSchema = properties[p];
|
|
1545
|
+
return {
|
|
1546
|
+
...acc,
|
|
1547
|
+
[p]: Base.isRef(propSchema) ? { type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)) } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
1548
|
+
};
|
|
1549
|
+
}, {})
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* OpenAPI parameter to base parameter.
|
|
1555
|
+
*/
|
|
1556
|
+
getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
|
|
1557
|
+
if (Base.isRef(parameter)) {
|
|
1558
|
+
const refName = Base.ref2name(parameter.$ref, this.doc);
|
|
1559
|
+
const resolved = this.doc.parameters?.[refName];
|
|
1560
|
+
if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
|
|
1561
|
+
parameter = resolved;
|
|
1562
|
+
}
|
|
1563
|
+
const p = parameter;
|
|
1564
|
+
const { name, required, description, type, items, enum: enum_, properties, schema } = p;
|
|
1565
|
+
if (enum_) {
|
|
1566
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
1567
|
+
const enumSchema = {
|
|
1568
|
+
name: type,
|
|
1569
|
+
enum: [...new Set(enum_)]
|
|
1570
|
+
};
|
|
1571
|
+
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
1572
|
+
if (!sameEnum && Base.isValidEnumType({
|
|
1573
|
+
type,
|
|
1574
|
+
enum: enum_
|
|
1575
|
+
})) enums.push(enumSchema);
|
|
1576
|
+
return {
|
|
1577
|
+
name,
|
|
1578
|
+
required,
|
|
1579
|
+
description,
|
|
1580
|
+
in: p.in,
|
|
1581
|
+
schema: { type: sameEnum?.name ?? type }
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
if (items) return {
|
|
1585
|
+
name,
|
|
1586
|
+
required,
|
|
1587
|
+
description,
|
|
1588
|
+
in: p.in,
|
|
1589
|
+
schema: {
|
|
1590
|
+
type,
|
|
1591
|
+
items
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
if (schema && Base.isRef(schema)) return {
|
|
1595
|
+
name,
|
|
1596
|
+
required,
|
|
1597
|
+
description,
|
|
1598
|
+
in: p.in,
|
|
1599
|
+
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1600
|
+
};
|
|
1601
|
+
return {
|
|
1602
|
+
name,
|
|
1603
|
+
required,
|
|
1604
|
+
description,
|
|
1605
|
+
in: p.in,
|
|
1606
|
+
schema: {
|
|
1607
|
+
type,
|
|
1608
|
+
properties
|
|
1609
|
+
}
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
/**
|
|
1613
|
+
* OpenAPI schema to base response
|
|
1614
|
+
*/
|
|
1615
|
+
getResponseByRef(schema) {
|
|
1616
|
+
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1617
|
+
const { schema: responseSchema } = schema;
|
|
1618
|
+
return [{
|
|
1619
|
+
type: "application/json",
|
|
1620
|
+
schema: responseSchema && this.getSchemaByRef(responseSchema, true)
|
|
1621
|
+
}];
|
|
1622
|
+
}
|
|
1623
|
+
init() {
|
|
1624
|
+
const { definitions = {}, responses = {}, paths = {} } = this.doc;
|
|
1625
|
+
const enums = [];
|
|
1626
|
+
const definitions_ = Object.keys(definitions).reduce((acc, key) => {
|
|
1627
|
+
const schema = definitions[key];
|
|
1628
|
+
return {
|
|
1629
|
+
...acc,
|
|
1630
|
+
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1631
|
+
};
|
|
1632
|
+
}, {});
|
|
1633
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
1634
|
+
const response = responses[key];
|
|
1635
|
+
return {
|
|
1636
|
+
...acc,
|
|
1637
|
+
[key]: this.getResponseByRef(response)
|
|
1638
|
+
};
|
|
1639
|
+
}, {});
|
|
1640
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
1641
|
+
let pathObject = paths[path] ?? {};
|
|
1642
|
+
if (pathObject.$ref) {
|
|
1643
|
+
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
1644
|
+
if (resolved) pathObject = resolved;
|
|
1645
|
+
}
|
|
1646
|
+
const { parameters = [] } = pathObject;
|
|
1647
|
+
const methodApis = [];
|
|
1648
|
+
Object.values(HttpMethods).forEach((method) => {
|
|
1649
|
+
const methodObject = pathObject[method];
|
|
1650
|
+
if (methodObject) {
|
|
1651
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {} } = methodObject;
|
|
1652
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
1653
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
1654
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1655
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1656
|
+
const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
|
|
1657
|
+
const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
|
|
1658
|
+
const httpCodes = Object.keys(responses);
|
|
1659
|
+
for (const code of httpCodes) if (code in responses) {
|
|
1660
|
+
const response = responses[code];
|
|
1661
|
+
const responseSchema = this.getResponseByRef(response);
|
|
1662
|
+
const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
1663
|
+
methodApis.push({
|
|
1664
|
+
method,
|
|
1665
|
+
operationId,
|
|
1666
|
+
summary: summary_,
|
|
1667
|
+
deprecated,
|
|
1668
|
+
description: description_,
|
|
1669
|
+
parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
|
|
1670
|
+
responses: responseSchema,
|
|
1671
|
+
requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
|
|
1672
|
+
type: "application/json",
|
|
1673
|
+
schema: inBody[0].schema
|
|
1674
|
+
}] : [{
|
|
1675
|
+
type: "application/json",
|
|
1676
|
+
schema: {
|
|
1677
|
+
type: "object",
|
|
1678
|
+
properties: inBody.reduce((a, p) => {
|
|
1679
|
+
return {
|
|
1680
|
+
...a,
|
|
1681
|
+
[p.name]: {
|
|
1682
|
+
type: p.schema?.type ?? "unknown",
|
|
1683
|
+
required: p.schema?.required,
|
|
1684
|
+
items: p.schema?.items,
|
|
1685
|
+
description: p.schema?.description
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
}, {})
|
|
1689
|
+
}
|
|
1690
|
+
}] : void 0
|
|
1691
|
+
});
|
|
1692
|
+
break;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
return {
|
|
1697
|
+
...acc,
|
|
1698
|
+
[path]: methodApis
|
|
1699
|
+
};
|
|
1700
|
+
}, {});
|
|
1701
|
+
return {
|
|
1702
|
+
enums: Base.uniqueEnums(enums),
|
|
1703
|
+
schemas: definitions_,
|
|
1704
|
+
responses: responses_,
|
|
1705
|
+
parameters: {},
|
|
1706
|
+
requestBodies: {},
|
|
1707
|
+
apis
|
|
1708
|
+
};
|
|
1259
1709
|
}
|
|
1260
1710
|
};
|
|
1261
1711
|
//#endregion
|
|
1262
|
-
//#region src/openapi/
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1712
|
+
//#region src/openapi/V3.ts
|
|
1713
|
+
var V3 = class {
|
|
1714
|
+
doc;
|
|
1715
|
+
constructor(doc) {
|
|
1716
|
+
this.doc = doc;
|
|
1717
|
+
}
|
|
1268
1718
|
/**
|
|
1269
1719
|
* Resolves a path $ref to the actual path object.
|
|
1270
1720
|
*/
|
|
@@ -1276,37 +1726,28 @@ var VersionedProvider = class {
|
|
|
1276
1726
|
* Is array schema.
|
|
1277
1727
|
*/
|
|
1278
1728
|
isOpenAPIArraySchema(schema) {
|
|
1279
|
-
return typeof schema === "object" && schema
|
|
1729
|
+
return typeof schema === "object" && schema.type === "array";
|
|
1280
1730
|
}
|
|
1281
1731
|
/**
|
|
1282
|
-
* OpenAPI schema to base schema.
|
|
1283
|
-
* (V3_1 throws on missing ref; V3 returns `{ type: 'unknown' }`).
|
|
1732
|
+
* OpenAPI schema to base schema.
|
|
1284
1733
|
*/
|
|
1285
1734
|
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
1286
1735
|
let refName = "";
|
|
1287
1736
|
if (Base.isRef(schema)) {
|
|
1288
|
-
refName =
|
|
1737
|
+
refName = Base.capitalize(Base.ref2name(schema.$ref));
|
|
1289
1738
|
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
1290
|
-
const resolvedSchema = this.
|
|
1739
|
+
const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1291
1740
|
if (!resolvedSchema) return { type: "unknown" };
|
|
1292
1741
|
schema = resolvedSchema;
|
|
1293
1742
|
}
|
|
1294
1743
|
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1295
1744
|
}
|
|
1296
1745
|
/**
|
|
1297
|
-
*
|
|
1298
|
-
* V3 uses `capitalize`; V3_1 uses `upperCamelCase` (preserved for compat).
|
|
1299
|
-
*/
|
|
1300
|
-
formatRefName(name) {
|
|
1301
|
-
return Base.capitalize(name);
|
|
1302
|
-
}
|
|
1303
|
-
/**
|
|
1304
|
-
* OpenAPI parameter to base parameter. Override in V2 — its parameter
|
|
1305
|
-
* shape is structurally different (top-level `items`/`properties`/`enum`).
|
|
1746
|
+
* OpenAPI parameter to base parameter.
|
|
1306
1747
|
*/
|
|
1307
1748
|
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
1308
1749
|
if (Base.isRef(schema)) {
|
|
1309
|
-
const resolvedSchema = this.
|
|
1750
|
+
const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1310
1751
|
if (!resolvedSchema) return {
|
|
1311
1752
|
name: "unknown",
|
|
1312
1753
|
in: "query"
|
|
@@ -1337,38 +1778,37 @@ var VersionedProvider = class {
|
|
|
1337
1778
|
description,
|
|
1338
1779
|
deprecated,
|
|
1339
1780
|
in: schema.in,
|
|
1340
|
-
schema: schema.schema
|
|
1781
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1341
1782
|
};
|
|
1342
1783
|
}
|
|
1343
1784
|
/**
|
|
1344
|
-
* OpenAPI schema to base response
|
|
1345
|
-
* lacks the `content` wrapper).
|
|
1785
|
+
* OpenAPI schema to base response
|
|
1346
1786
|
*/
|
|
1347
1787
|
getResponseByRef(schema) {
|
|
1348
1788
|
if (Base.isRef(schema)) {
|
|
1349
|
-
const resolvedSchema = this.
|
|
1789
|
+
const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1350
1790
|
if (!resolvedSchema) return [];
|
|
1351
1791
|
schema = resolvedSchema;
|
|
1352
1792
|
}
|
|
1353
1793
|
const { content = {} } = schema;
|
|
1354
1794
|
return Object.keys(content).map((c) => ({
|
|
1355
1795
|
type: c,
|
|
1356
|
-
schema: content[c].schema
|
|
1796
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
1357
1797
|
}));
|
|
1358
1798
|
}
|
|
1359
1799
|
/**
|
|
1360
|
-
* OpenAPI schema to requestBody.
|
|
1800
|
+
* OpenAPI schema to requestBody.
|
|
1361
1801
|
*/
|
|
1362
1802
|
getRequestBodyByRef(schema, enums = []) {
|
|
1363
1803
|
if (Base.isRef(schema)) {
|
|
1364
|
-
const resolvedSchema = this.
|
|
1804
|
+
const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1365
1805
|
if (!resolvedSchema) return [];
|
|
1366
1806
|
schema = resolvedSchema;
|
|
1367
1807
|
}
|
|
1368
1808
|
const { content = {} } = schema;
|
|
1369
1809
|
return Object.keys(content).map((c) => ({
|
|
1370
1810
|
type: c,
|
|
1371
|
-
schema: content[c].schema
|
|
1811
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
|
|
1372
1812
|
}));
|
|
1373
1813
|
}
|
|
1374
1814
|
/**
|
|
@@ -1379,98 +1819,92 @@ var VersionedProvider = class {
|
|
|
1379
1819
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1380
1820
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1381
1821
|
const { type, description, items, required } = schema;
|
|
1382
|
-
const itemsSchema = items ? this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey) : { type: "unknown" };
|
|
1383
1822
|
return {
|
|
1384
1823
|
type,
|
|
1385
1824
|
required: !!required,
|
|
1386
1825
|
description,
|
|
1387
|
-
items:
|
|
1388
|
-
};
|
|
1389
|
-
}
|
|
1390
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1391
|
-
let { type } = schema;
|
|
1392
|
-
if (enum_ && type !== "boolean") {
|
|
1393
|
-
const enumObject = {
|
|
1394
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
|
|
1395
|
-
enum: [...new Set(enum_)]
|
|
1826
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1396
1827
|
};
|
|
1397
|
-
|
|
1398
|
-
|
|
1828
|
+
} else {
|
|
1829
|
+
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1830
|
+
let { type } = schema;
|
|
1831
|
+
if (enum_ && type !== "boolean") {
|
|
1832
|
+
const enumObject = {
|
|
1833
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
|
|
1834
|
+
enum: [...new Set(enum_)]
|
|
1835
|
+
};
|
|
1836
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1837
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1838
|
+
return {
|
|
1839
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
1840
|
+
required,
|
|
1841
|
+
description,
|
|
1842
|
+
deprecated
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1399
1846
|
return {
|
|
1400
|
-
type
|
|
1847
|
+
type,
|
|
1401
1848
|
required,
|
|
1402
1849
|
description,
|
|
1403
|
-
deprecated
|
|
1850
|
+
deprecated,
|
|
1851
|
+
enum: enum_,
|
|
1852
|
+
format,
|
|
1853
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1854
|
+
...s,
|
|
1855
|
+
ref: s.$ref,
|
|
1856
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1857
|
+
} : this.toBaseSchema(s, enums)),
|
|
1858
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
1859
|
+
...s,
|
|
1860
|
+
ref: s.$ref,
|
|
1861
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1862
|
+
} : this.toBaseSchema(s, enums)),
|
|
1863
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
1864
|
+
...s,
|
|
1865
|
+
ref: s.$ref,
|
|
1866
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1867
|
+
} : this.toBaseSchema(s, enums)),
|
|
1868
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
1869
|
+
const propSchema = properties[p];
|
|
1870
|
+
return {
|
|
1871
|
+
...acc,
|
|
1872
|
+
[p]: Base.isRef(propSchema) ? {
|
|
1873
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
1874
|
+
isRef: true
|
|
1875
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
1876
|
+
};
|
|
1877
|
+
}, {})
|
|
1404
1878
|
};
|
|
1405
1879
|
}
|
|
1406
|
-
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
1407
|
-
return {
|
|
1408
|
-
type,
|
|
1409
|
-
required,
|
|
1410
|
-
description,
|
|
1411
|
-
deprecated,
|
|
1412
|
-
enum: enum_,
|
|
1413
|
-
format,
|
|
1414
|
-
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
1415
|
-
...s,
|
|
1416
|
-
ref: s.$ref,
|
|
1417
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1418
|
-
} : this.toBaseSchema(s, enums)),
|
|
1419
|
-
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
1420
|
-
...s,
|
|
1421
|
-
ref: s.$ref,
|
|
1422
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1423
|
-
} : this.toBaseSchema(s, enums)),
|
|
1424
|
-
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
1425
|
-
...s,
|
|
1426
|
-
ref: s.$ref,
|
|
1427
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1428
|
-
} : this.toBaseSchema(s, enums)),
|
|
1429
|
-
properties: Object.keys(properties).reduce((acc, p) => {
|
|
1430
|
-
const propSchema = properties[p];
|
|
1431
|
-
return {
|
|
1432
|
-
...acc,
|
|
1433
|
-
[p]: Base.isRef(propSchema) ? {
|
|
1434
|
-
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
1435
|
-
isRef: true
|
|
1436
|
-
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
1437
|
-
};
|
|
1438
|
-
}, {})
|
|
1439
|
-
};
|
|
1440
1880
|
}
|
|
1441
|
-
/**
|
|
1442
|
-
* Run the parsing pipeline and return a ProviderInitResult.
|
|
1443
|
-
*/
|
|
1444
1881
|
init() {
|
|
1445
|
-
const { paths = {} } = this.doc;
|
|
1882
|
+
const { components = {}, paths = {} } = this.doc;
|
|
1446
1883
|
const enums = [];
|
|
1447
|
-
const
|
|
1448
|
-
const
|
|
1449
|
-
|
|
1450
|
-
const requestBodyContainer = this.getRequestBodyContainer() ?? {};
|
|
1451
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1452
|
-
const schema = schemaContainer[key];
|
|
1884
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
1885
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
1886
|
+
const schema = schemas[key];
|
|
1453
1887
|
return {
|
|
1454
1888
|
...acc,
|
|
1455
1889
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1456
1890
|
};
|
|
1457
1891
|
}, {});
|
|
1458
|
-
const parameters_ = Object.keys(
|
|
1459
|
-
const parameter =
|
|
1892
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
1893
|
+
const parameter = parameters[key];
|
|
1460
1894
|
return {
|
|
1461
1895
|
...acc,
|
|
1462
1896
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1463
1897
|
};
|
|
1464
1898
|
}, {});
|
|
1465
|
-
const responses_ = Object.keys(
|
|
1466
|
-
const response =
|
|
1899
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
1900
|
+
const response = responses[key];
|
|
1467
1901
|
return {
|
|
1468
1902
|
...acc,
|
|
1469
1903
|
[key]: this.getResponseByRef(response)
|
|
1470
1904
|
};
|
|
1471
1905
|
}, {});
|
|
1472
|
-
const requestBodies_ = Object.keys(
|
|
1473
|
-
const requestBody =
|
|
1906
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
1907
|
+
const requestBody = requestBodies[key];
|
|
1474
1908
|
return {
|
|
1475
1909
|
...acc,
|
|
1476
1910
|
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
@@ -1487,16 +1921,15 @@ var VersionedProvider = class {
|
|
|
1487
1921
|
Object.values(HttpMethods).forEach((method) => {
|
|
1488
1922
|
const methodObject = pathObject[method];
|
|
1489
1923
|
if (methodObject) {
|
|
1490
|
-
const { deprecated, operationId, responses, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1491
|
-
const responsesClone = responses ? { ...responses } : {};
|
|
1924
|
+
const { deprecated, operationId, responses = {}, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1492
1925
|
const { parameters: parameters_ = [] } = methodObject;
|
|
1493
1926
|
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
1494
1927
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
1495
1928
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1496
|
-
if (Object.keys(
|
|
1497
|
-
const httpCodes = Object.keys(
|
|
1498
|
-
for (const code of httpCodes) if (code in
|
|
1499
|
-
const response =
|
|
1929
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
1930
|
+
const httpCodes = Object.keys(responses);
|
|
1931
|
+
for (const code of httpCodes) if (code in responses) {
|
|
1932
|
+
const response = responses[code];
|
|
1500
1933
|
const responseSchema = this.getResponseByRef(response);
|
|
1501
1934
|
methodApis.push({
|
|
1502
1935
|
method,
|
|
@@ -1528,246 +1961,244 @@ var VersionedProvider = class {
|
|
|
1528
1961
|
}
|
|
1529
1962
|
};
|
|
1530
1963
|
//#endregion
|
|
1531
|
-
//#region src/openapi/
|
|
1532
|
-
var
|
|
1964
|
+
//#region src/openapi/V3_1.ts
|
|
1965
|
+
var V3_1 = class {
|
|
1533
1966
|
doc;
|
|
1534
|
-
version = "v2";
|
|
1535
1967
|
constructor(doc) {
|
|
1536
|
-
super();
|
|
1537
1968
|
this.doc = doc;
|
|
1538
1969
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1970
|
+
/**
|
|
1971
|
+
* Resolves a path $ref to the actual path object.
|
|
1972
|
+
*/
|
|
1973
|
+
resolvePathRef($ref) {
|
|
1974
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
1975
|
+
return this.doc.paths?.[refName];
|
|
1544
1976
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1977
|
+
/**
|
|
1978
|
+
* Is array schema.
|
|
1979
|
+
*/
|
|
1980
|
+
isOpenAPIArraySchema(schema) {
|
|
1981
|
+
return typeof schema === "object" && schema.type === "array";
|
|
1547
1982
|
}
|
|
1548
|
-
getRequestBodyContainer() {}
|
|
1549
1983
|
/**
|
|
1550
|
-
*
|
|
1551
|
-
* rather than nested under `schema`. Override accordingly.
|
|
1984
|
+
* OpenAPI schema to base schema.
|
|
1552
1985
|
*/
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
if (
|
|
1558
|
-
|
|
1986
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
1987
|
+
let refName = "";
|
|
1988
|
+
if (Base.isRef(schema)) {
|
|
1989
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
1990
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
1991
|
+
if (!this.doc.components) this.doc.components = { schemas: {} };
|
|
1992
|
+
const resolvedSchema = this.doc.components.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1993
|
+
if (!resolvedSchema) throw new Error(`Schema reference not found: ${refName}`);
|
|
1994
|
+
schema = resolvedSchema;
|
|
1559
1995
|
}
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1996
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* OpenAPI parameter to base parameter.
|
|
2000
|
+
*/
|
|
2001
|
+
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
2002
|
+
if (Base.isRef(schema)) schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2003
|
+
const { name, required, deprecated, description, schema: parameterSchema } = schema;
|
|
2004
|
+
if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
|
|
2005
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
1564
2006
|
const enumSchema = {
|
|
1565
|
-
name:
|
|
1566
|
-
enum: [...new Set(
|
|
2007
|
+
name: type,
|
|
2008
|
+
enum: [...new Set(parameterSchema.enum)]
|
|
1567
2009
|
};
|
|
1568
2010
|
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
1569
|
-
if (!sameEnum && Base.isValidEnumType(
|
|
1570
|
-
type: enumType,
|
|
1571
|
-
enum: enum_
|
|
1572
|
-
})) enums.push(enumSchema);
|
|
2011
|
+
if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
|
|
1573
2012
|
return {
|
|
1574
2013
|
name,
|
|
1575
2014
|
required,
|
|
1576
2015
|
description,
|
|
1577
|
-
|
|
1578
|
-
|
|
2016
|
+
deprecated,
|
|
2017
|
+
in: schema.in,
|
|
2018
|
+
schema: { type: sameEnum?.name ?? type }
|
|
1579
2019
|
};
|
|
1580
2020
|
}
|
|
1581
|
-
if (items) return {
|
|
1582
|
-
name,
|
|
1583
|
-
required,
|
|
1584
|
-
description,
|
|
1585
|
-
in: p.in,
|
|
1586
|
-
schema: {
|
|
1587
|
-
type,
|
|
1588
|
-
items
|
|
1589
|
-
}
|
|
1590
|
-
};
|
|
1591
|
-
if (schema && Base.isRef(schema)) return {
|
|
1592
|
-
name,
|
|
1593
|
-
required,
|
|
1594
|
-
description,
|
|
1595
|
-
in: p.in,
|
|
1596
|
-
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1597
|
-
};
|
|
1598
2021
|
return {
|
|
1599
2022
|
name,
|
|
1600
2023
|
required,
|
|
1601
2024
|
description,
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
properties
|
|
1606
|
-
}
|
|
2025
|
+
deprecated,
|
|
2026
|
+
in: schema.in,
|
|
2027
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1607
2028
|
};
|
|
1608
2029
|
}
|
|
1609
2030
|
/**
|
|
1610
|
-
*
|
|
1611
|
-
* emits JSON.
|
|
2031
|
+
* OpenAPI schema to base response
|
|
1612
2032
|
*/
|
|
1613
2033
|
getResponseByRef(schema) {
|
|
1614
|
-
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1615
|
-
const {
|
|
1616
|
-
return
|
|
1617
|
-
type:
|
|
1618
|
-
schema:
|
|
1619
|
-
}
|
|
2034
|
+
if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2035
|
+
const { content = {} } = schema;
|
|
2036
|
+
return Object.keys(content).map((c) => ({
|
|
2037
|
+
type: c,
|
|
2038
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
|
|
2039
|
+
}));
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* OpenAPI schema to requestBody.
|
|
2043
|
+
*/
|
|
2044
|
+
getRequestBodyByRef(schema, enums = []) {
|
|
2045
|
+
if (Base.isRef(schema)) schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2046
|
+
const { content = {} } = schema;
|
|
2047
|
+
return Object.keys(content).map((c) => ({
|
|
2048
|
+
type: c,
|
|
2049
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2050
|
+
}));
|
|
1620
2051
|
}
|
|
1621
2052
|
/**
|
|
1622
|
-
*
|
|
1623
|
-
* `in: formData` are split out and turned into a synthetic requestBody
|
|
1624
|
-
* here. A single body param named `body` is used directly; otherwise
|
|
1625
|
-
* the body / formData params are wrapped in a synthetic object.
|
|
2053
|
+
* Transform all OpenAPI schema to Base Schema
|
|
1626
2054
|
*/
|
|
2055
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
2056
|
+
if (!schema) return { type: "unknown" };
|
|
2057
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2058
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
2059
|
+
const { type, description, items, required } = schema;
|
|
2060
|
+
return {
|
|
2061
|
+
type,
|
|
2062
|
+
required: !!required,
|
|
2063
|
+
description,
|
|
2064
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2065
|
+
};
|
|
2066
|
+
} else {
|
|
2067
|
+
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2068
|
+
let { type } = schema;
|
|
2069
|
+
if (enum_ && type !== "boolean") {
|
|
2070
|
+
const enumObject = {
|
|
2071
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
|
|
2072
|
+
enum: [...new Set(enum_)]
|
|
2073
|
+
};
|
|
2074
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2075
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2076
|
+
return {
|
|
2077
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2078
|
+
required,
|
|
2079
|
+
description,
|
|
2080
|
+
deprecated
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2084
|
+
return {
|
|
2085
|
+
type,
|
|
2086
|
+
required,
|
|
2087
|
+
description,
|
|
2088
|
+
deprecated,
|
|
2089
|
+
enum: enum_,
|
|
2090
|
+
format,
|
|
2091
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2092
|
+
...s,
|
|
2093
|
+
ref: s.$ref,
|
|
2094
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2095
|
+
} : this.toBaseSchema(s, enums)),
|
|
2096
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2097
|
+
...s,
|
|
2098
|
+
ref: s.$ref,
|
|
2099
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2100
|
+
} : this.toBaseSchema(s, enums)),
|
|
2101
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2102
|
+
...s,
|
|
2103
|
+
ref: s.$ref,
|
|
2104
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2105
|
+
} : this.toBaseSchema(s, enums)),
|
|
2106
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
2107
|
+
const propSchema = properties[p];
|
|
2108
|
+
return {
|
|
2109
|
+
...acc,
|
|
2110
|
+
[p]: Base.isRef(propSchema) ? {
|
|
2111
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
2112
|
+
isRef: true
|
|
2113
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
2114
|
+
};
|
|
2115
|
+
}, {})
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
1627
2119
|
init() {
|
|
1628
|
-
const { paths = {} } = this.doc;
|
|
2120
|
+
const { components = {}, paths = {} } = this.doc;
|
|
1629
2121
|
const enums = [];
|
|
1630
|
-
const
|
|
1631
|
-
const
|
|
1632
|
-
|
|
1633
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1634
|
-
const schema = schemaContainer[key];
|
|
2122
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
|
|
2123
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
2124
|
+
const schema = schemas[key];
|
|
1635
2125
|
return {
|
|
1636
2126
|
...acc,
|
|
1637
2127
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1638
2128
|
};
|
|
1639
2129
|
}, {});
|
|
1640
|
-
const parameters_ = Object.keys(
|
|
1641
|
-
const parameter =
|
|
2130
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
2131
|
+
const parameter = parameters[key];
|
|
1642
2132
|
return {
|
|
1643
2133
|
...acc,
|
|
1644
2134
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1645
2135
|
};
|
|
1646
2136
|
}, {});
|
|
1647
|
-
const responses_ = Object.keys(
|
|
1648
|
-
const response =
|
|
2137
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
2138
|
+
const response = responses[key];
|
|
1649
2139
|
return {
|
|
1650
2140
|
...acc,
|
|
1651
2141
|
[key]: this.getResponseByRef(response)
|
|
1652
2142
|
};
|
|
1653
2143
|
}, {});
|
|
1654
|
-
const
|
|
1655
|
-
|
|
2144
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
2145
|
+
const requestBody = requestBodies[key];
|
|
2146
|
+
return {
|
|
2147
|
+
...acc,
|
|
2148
|
+
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
2149
|
+
};
|
|
2150
|
+
}, {});
|
|
2151
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
1656
2152
|
let pathObject = paths[path] ?? {};
|
|
1657
2153
|
if (pathObject.$ref) {
|
|
1658
2154
|
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
1659
2155
|
if (resolved) pathObject = resolved;
|
|
1660
2156
|
}
|
|
1661
|
-
const { parameters = [] } = pathObject;
|
|
2157
|
+
const { parameters = [], description, summary } = pathObject;
|
|
1662
2158
|
const methodApis = [];
|
|
1663
2159
|
Object.values(HttpMethods).forEach((method) => {
|
|
1664
2160
|
const methodObject = pathObject[method];
|
|
1665
|
-
if (
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
type: "application/json",
|
|
1689
|
-
schema: inBody[0].schema
|
|
1690
|
-
}] : [{
|
|
1691
|
-
type: "application/json",
|
|
1692
|
-
schema: {
|
|
1693
|
-
type: "object",
|
|
1694
|
-
properties: inBody.reduce((a, p) => {
|
|
1695
|
-
return {
|
|
1696
|
-
...a,
|
|
1697
|
-
[p.name]: {
|
|
1698
|
-
type: p.schema?.type ?? "unknown",
|
|
1699
|
-
required: p.schema?.required,
|
|
1700
|
-
items: p.schema?.items,
|
|
1701
|
-
description: p.schema?.description
|
|
1702
|
-
}
|
|
1703
|
-
};
|
|
1704
|
-
}, {})
|
|
1705
|
-
}
|
|
1706
|
-
}] : void 0
|
|
1707
|
-
});
|
|
1708
|
-
break;
|
|
2161
|
+
if (methodObject) {
|
|
2162
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {}, requestBody = { content: {} } } = methodObject;
|
|
2163
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
2164
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
2165
|
+
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
2166
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
2167
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2168
|
+
const httpCodes = Object.keys(responses);
|
|
2169
|
+
for (const code of httpCodes) if (code in responses) {
|
|
2170
|
+
const response = responses[code];
|
|
2171
|
+
const responseSchema = this.getResponseByRef(response);
|
|
2172
|
+
methodApis.push({
|
|
2173
|
+
method,
|
|
2174
|
+
operationId,
|
|
2175
|
+
summary: summary_ ?? summary,
|
|
2176
|
+
description: description_ ?? description,
|
|
2177
|
+
deprecated,
|
|
2178
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
2179
|
+
responses: responseSchema,
|
|
2180
|
+
requestBody: baseRequestBody
|
|
2181
|
+
});
|
|
2182
|
+
break;
|
|
2183
|
+
}
|
|
1709
2184
|
}
|
|
1710
2185
|
});
|
|
1711
|
-
|
|
1712
|
-
|
|
2186
|
+
return {
|
|
2187
|
+
...acc,
|
|
2188
|
+
[path]: methodApis
|
|
2189
|
+
};
|
|
2190
|
+
}, {});
|
|
1713
2191
|
return {
|
|
1714
2192
|
enums: Base.uniqueEnums(enums),
|
|
1715
2193
|
schemas: schemas_,
|
|
1716
2194
|
responses: responses_,
|
|
1717
2195
|
parameters: parameters_,
|
|
1718
|
-
requestBodies:
|
|
2196
|
+
requestBodies: requestBodies_,
|
|
1719
2197
|
apis
|
|
1720
2198
|
};
|
|
1721
2199
|
}
|
|
1722
2200
|
};
|
|
1723
2201
|
//#endregion
|
|
1724
|
-
//#region src/openapi/V3.ts
|
|
1725
|
-
var V3 = class extends VersionedProvider {
|
|
1726
|
-
doc;
|
|
1727
|
-
version = "v3";
|
|
1728
|
-
constructor(doc) {
|
|
1729
|
-
super();
|
|
1730
|
-
this.doc = doc;
|
|
1731
|
-
}
|
|
1732
|
-
getSchemaContainer() {
|
|
1733
|
-
return this.doc.components?.schemas;
|
|
1734
|
-
}
|
|
1735
|
-
getParameterContainer() {
|
|
1736
|
-
return this.doc.components?.parameters;
|
|
1737
|
-
}
|
|
1738
|
-
getResponseContainer() {
|
|
1739
|
-
return this.doc.components?.responses;
|
|
1740
|
-
}
|
|
1741
|
-
getRequestBodyContainer() {
|
|
1742
|
-
return this.doc.components?.requestBodies;
|
|
1743
|
-
}
|
|
1744
|
-
};
|
|
1745
|
-
//#endregion
|
|
1746
|
-
//#region src/openapi/V3_1.ts
|
|
1747
|
-
var V3_1 = class extends VersionedProvider {
|
|
1748
|
-
doc;
|
|
1749
|
-
version = "v3_1";
|
|
1750
|
-
constructor(doc) {
|
|
1751
|
-
super();
|
|
1752
|
-
this.doc = doc;
|
|
1753
|
-
}
|
|
1754
|
-
formatRefName(name) {
|
|
1755
|
-
return Base.upperCamelCase(name);
|
|
1756
|
-
}
|
|
1757
|
-
getSchemaContainer() {
|
|
1758
|
-
return this.doc.components?.schemas;
|
|
1759
|
-
}
|
|
1760
|
-
getParameterContainer() {
|
|
1761
|
-
return this.doc.components?.parameters;
|
|
1762
|
-
}
|
|
1763
|
-
getResponseContainer() {
|
|
1764
|
-
return this.doc.components?.responses;
|
|
1765
|
-
}
|
|
1766
|
-
getRequestBodyContainer() {
|
|
1767
|
-
return this.doc.components?.requestBodies;
|
|
1768
|
-
}
|
|
1769
|
-
};
|
|
1770
|
-
//#endregion
|
|
1771
2202
|
//#region src/openapi/index.ts
|
|
1772
2203
|
const logger$1 = createScopedLogger("OpenAPI");
|
|
1773
2204
|
let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
@@ -1778,7 +2209,9 @@ let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
|
1778
2209
|
return OpenAPIVersion;
|
|
1779
2210
|
}({});
|
|
1780
2211
|
function getDocVersion(doc) {
|
|
1781
|
-
|
|
2212
|
+
const raw = doc.openapi || doc.swagger;
|
|
2213
|
+
if (typeof raw !== "string" || raw.length === 0) return "unknown";
|
|
2214
|
+
switch (raw.slice(0, 3)) {
|
|
1782
2215
|
case "3.1": return "v3_1";
|
|
1783
2216
|
case "3.0": return "v3";
|
|
1784
2217
|
case "2.0": return "v2";
|
|
@@ -1809,7 +2242,21 @@ async function codeGen(initOptions) {
|
|
|
1809
2242
|
if (verbose) logger$1.setLevel("debug");
|
|
1810
2243
|
else logger$1.setLevel("info");
|
|
1811
2244
|
logger$1.info(`Fetch document from ${initOptions.docURL}`);
|
|
1812
|
-
const {
|
|
2245
|
+
const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
|
|
2246
|
+
const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, transport === "file" ? await (async () => {
|
|
2247
|
+
let raw;
|
|
2248
|
+
try {
|
|
2249
|
+
raw = await readFile(source, "utf8");
|
|
2250
|
+
} catch (error) {
|
|
2251
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
|
|
2252
|
+
throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2253
|
+
}
|
|
2254
|
+
try {
|
|
2255
|
+
return JSON.parse(raw);
|
|
2256
|
+
} catch (error) {
|
|
2257
|
+
throw createErrors.specParseFailed(source, void 0, void 0, error);
|
|
2258
|
+
}
|
|
2259
|
+
})() : await Base.fetchDoc(source, initOptions.requestOptions));
|
|
1813
2260
|
const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
|
|
1814
2261
|
const code = await Generator.genCode({
|
|
1815
2262
|
enums,
|
|
@@ -1831,61 +2278,95 @@ async function codeGen(initOptions) {
|
|
|
1831
2278
|
};
|
|
1832
2279
|
}
|
|
1833
2280
|
//#endregion
|
|
1834
|
-
//#region src/vite-plugin/
|
|
1835
|
-
const PLUGIN_NAME = "api-code-gen";
|
|
1836
|
-
const pluginLogger = createScopedLogger("api-code-gen");
|
|
2281
|
+
//#region src/vite-plugin/cache.ts
|
|
1837
2282
|
/**
|
|
1838
|
-
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
2283
|
+
* Cache for a single vite-plugin codegen run. Lives only for the duration
|
|
2284
|
+
* of one plugin invocation — there is no module-level state.
|
|
2285
|
+
*
|
|
2286
|
+
* Cache files are stored at:
|
|
2287
|
+
*
|
|
2288
|
+
* <cacheDir>/<optionsHash>.json
|
|
2289
|
+
*
|
|
2290
|
+
* where `<cacheDir>` defaults to `node_modules/.cache/apicodegen` but can
|
|
2291
|
+
* be overridden via `cacheDir`.
|
|
1841
2292
|
*/
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
2293
|
+
var CodegenCache = class CodegenCache {
|
|
2294
|
+
cacheDir;
|
|
2295
|
+
constructor(cacheDir) {
|
|
2296
|
+
this.cacheDir = cacheDir;
|
|
2297
|
+
}
|
|
2298
|
+
/** Hash the options that affect generated output (excluding the spec). */
|
|
2299
|
+
static hashOptions(options) {
|
|
2300
|
+
const payload = Object.keys(options).sort().filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`).join("|");
|
|
2301
|
+
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
2302
|
+
}
|
|
2303
|
+
/** Hash the raw spec content so unrelated edits are detected. */
|
|
2304
|
+
static hashContent(content) {
|
|
2305
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Look up a cached entry. Returns `null` on miss / corruption / disabled.
|
|
2309
|
+
*
|
|
2310
|
+
* @param optionsHash Options hash from `hashOptions`.
|
|
2311
|
+
* @param specSource Resolved spec path or URL. Local paths use mtime +
|
|
2312
|
+
* content hash; URLs always miss (no cache).
|
|
2313
|
+
*/
|
|
2314
|
+
async lookup(optionsHash, specSource) {
|
|
2315
|
+
const cachePath = path.join(this.cacheDir, `${optionsHash}.json`);
|
|
2316
|
+
let raw;
|
|
2317
|
+
try {
|
|
2318
|
+
raw = await readFile(cachePath, "utf8");
|
|
2319
|
+
} catch {
|
|
2320
|
+
return null;
|
|
2321
|
+
}
|
|
2322
|
+
let entry;
|
|
2323
|
+
try {
|
|
2324
|
+
entry = JSON.parse(raw);
|
|
2325
|
+
} catch {
|
|
2326
|
+
return null;
|
|
2327
|
+
}
|
|
2328
|
+
if (entry.optionsHash !== optionsHash) return null;
|
|
2329
|
+
if (specSource.startsWith("http://") || specSource.startsWith("https://")) return null;
|
|
2330
|
+
let currentMtimeMs;
|
|
2331
|
+
try {
|
|
2332
|
+
currentMtimeMs = (await stat(specSource)).mtimeMs;
|
|
2333
|
+
} catch {
|
|
2334
|
+
return null;
|
|
2335
|
+
}
|
|
2336
|
+
if (currentMtimeMs !== entry.specMtimeMs) return null;
|
|
2337
|
+
if (entry.specContentHash) {
|
|
2338
|
+
let content;
|
|
2339
|
+
try {
|
|
2340
|
+
content = await readFile(specSource, "utf8");
|
|
2341
|
+
} catch {
|
|
2342
|
+
return null;
|
|
2343
|
+
}
|
|
2344
|
+
if (CodegenCache.hashContent(content) !== entry.specContentHash) return null;
|
|
1850
2345
|
}
|
|
1851
|
-
|
|
1852
|
-
dir = path.dirname(dir);
|
|
2346
|
+
return entry;
|
|
1853
2347
|
}
|
|
1854
|
-
|
|
1855
|
-
|
|
2348
|
+
/** Persist a successful codegen result. */
|
|
2349
|
+
async store(entry) {
|
|
2350
|
+
const cachePath = path.join(this.cacheDir, `${entry.optionsHash}.json`);
|
|
2351
|
+
const dir = path.dirname(cachePath);
|
|
2352
|
+
await import("fs-extra").then((fs) => fs.ensureDir(dir));
|
|
2353
|
+
await writeFile(cachePath, JSON.stringify(entry));
|
|
2354
|
+
}
|
|
2355
|
+
};
|
|
2356
|
+
//#endregion
|
|
2357
|
+
//#region src/vite-plugin/index.ts
|
|
2358
|
+
const PLUGIN_NAME = "api-code-gen";
|
|
2359
|
+
const logger = createScopedLogger("api-code-gen");
|
|
1856
2360
|
/**
|
|
1857
2361
|
* Run TypeScript type checking on generated file
|
|
1858
2362
|
*/
|
|
1859
2363
|
async function runTypeCheck(filePath) {
|
|
1860
2364
|
const { execaCommand } = await import("execa");
|
|
1861
2365
|
const errors = [];
|
|
1862
|
-
const resolvedPath = path.resolve(filePath);
|
|
1863
|
-
const tsconfigPath = await findNearestTsConfig(resolvedPath);
|
|
1864
|
-
if (!tsconfigPath) {
|
|
1865
|
-
try {
|
|
1866
|
-
await execaCommand(`npx tsc ${resolvedPath} --noEmit`, { shell: true });
|
|
1867
|
-
} catch (error) {
|
|
1868
|
-
if (error instanceof Error) errors.push(error.message);
|
|
1869
|
-
}
|
|
1870
|
-
return errors;
|
|
1871
|
-
}
|
|
1872
|
-
const outputDir = path.dirname(resolvedPath);
|
|
1873
|
-
const tempConfigName = `.${path.basename(resolvedPath).replace(/\.ts$/i, "")}.${Date.now()}.apicodegen.json`;
|
|
1874
|
-
const tempConfigPath = path.join(outputDir, tempConfigName);
|
|
1875
|
-
const tempConfig = {
|
|
1876
|
-
extends: path.relative(outputDir, tsconfigPath),
|
|
1877
|
-
compilerOptions: { noEmit: true },
|
|
1878
|
-
include: [path.basename(resolvedPath)]
|
|
1879
|
-
};
|
|
1880
2366
|
try {
|
|
1881
|
-
await
|
|
1882
|
-
await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
|
|
2367
|
+
await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
1883
2368
|
} catch (error) {
|
|
1884
2369
|
if (error instanceof Error) errors.push(error.message);
|
|
1885
|
-
} finally {
|
|
1886
|
-
try {
|
|
1887
|
-
await fs.remove(tempConfigPath);
|
|
1888
|
-
} catch {}
|
|
1889
2370
|
}
|
|
1890
2371
|
return errors;
|
|
1891
2372
|
}
|
|
@@ -1902,9 +2383,9 @@ async function validateSpecPath(specPath) {
|
|
|
1902
2383
|
* Generate code for a single API configuration
|
|
1903
2384
|
*/
|
|
1904
2385
|
async function generateForOption(option) {
|
|
1905
|
-
const { name, typeCheck = true, verbose, ...restOptions } = option;
|
|
2386
|
+
const { name, typeCheck = true, verbose, cache = true, cacheDir, ...restOptions } = option;
|
|
1906
2387
|
try {
|
|
1907
|
-
|
|
2388
|
+
console.log(`\x1b[36m├─\x1b[0m ${name}`);
|
|
1908
2389
|
const config = await loadConfig({
|
|
1909
2390
|
name,
|
|
1910
2391
|
cliOptions: {
|
|
@@ -1918,25 +2399,69 @@ async function generateForOption(option) {
|
|
|
1918
2399
|
await fs.ensureDir(outputDir);
|
|
1919
2400
|
}
|
|
1920
2401
|
let docURL = config.spec;
|
|
1921
|
-
if (!docURL.startsWith("http://") && !docURL.startsWith("https://")
|
|
1922
|
-
|
|
1923
|
-
const
|
|
1924
|
-
|
|
1925
|
-
|
|
2402
|
+
if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = path.resolve(process.cwd(), docURL);
|
|
2403
|
+
const resolvedCacheDir = cacheDir ?? path.join(process.cwd(), "node_modules", ".cache", "apicodegen");
|
|
2404
|
+
const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
|
|
2405
|
+
const optionsHash = CodegenCache.hashOptions({
|
|
2406
|
+
name,
|
|
2407
|
+
spec: docURL,
|
|
2408
|
+
output: config.output,
|
|
2409
|
+
adaptor: config.adaptor,
|
|
2410
|
+
baseURL: config.baseURL,
|
|
2411
|
+
importClientSource: config.importClientSource
|
|
1926
2412
|
});
|
|
2413
|
+
let result = null;
|
|
2414
|
+
let cached = false;
|
|
2415
|
+
if (codegenCache) {
|
|
2416
|
+
const cachedEntry = await codegenCache.lookup(optionsHash, docURL);
|
|
2417
|
+
if (cachedEntry) {
|
|
2418
|
+
result = {
|
|
2419
|
+
code: cachedEntry.code,
|
|
2420
|
+
stats: cachedEntry.stats
|
|
2421
|
+
};
|
|
2422
|
+
cached = true;
|
|
2423
|
+
if (verbose) logger.debug(`Cache hit for ${name} (${optionsHash})`);
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
if (!result) {
|
|
2427
|
+
result = await codeGen({
|
|
2428
|
+
...toProviderOptions(config),
|
|
2429
|
+
docURL
|
|
2430
|
+
});
|
|
2431
|
+
if (codegenCache) try {
|
|
2432
|
+
const fsPromises = await import("node:fs/promises");
|
|
2433
|
+
let specMtimeMs;
|
|
2434
|
+
let specContentHash;
|
|
2435
|
+
if (!(docURL.startsWith("http://") || docURL.startsWith("https://"))) try {
|
|
2436
|
+
specMtimeMs = (await fsPromises.stat(docURL)).mtimeMs;
|
|
2437
|
+
const content = await fsPromises.readFile(docURL, "utf8");
|
|
2438
|
+
specContentHash = CodegenCache.hashContent(content);
|
|
2439
|
+
} catch {}
|
|
2440
|
+
await codegenCache.store({
|
|
2441
|
+
optionsHash,
|
|
2442
|
+
specMtimeMs,
|
|
2443
|
+
specContentHash,
|
|
2444
|
+
code: result.code,
|
|
2445
|
+
stats: result.stats
|
|
2446
|
+
});
|
|
2447
|
+
} catch (cacheError) {
|
|
2448
|
+
if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
1927
2451
|
if (config.output) await fs.writeFile(config.output, result.code);
|
|
1928
2452
|
if (typeCheck && config.output) {
|
|
1929
2453
|
const typeErrors = await runTypeCheck(config.output);
|
|
1930
2454
|
if (typeErrors.length > 0) {
|
|
1931
|
-
|
|
1932
|
-
if (verbose) for (const error of typeErrors)
|
|
2455
|
+
logger.warn(`Type check failed for ${config.output}`);
|
|
2456
|
+
if (verbose) for (const error of typeErrors) logger.warn(` ${error}`);
|
|
1933
2457
|
}
|
|
1934
2458
|
}
|
|
1935
2459
|
return {
|
|
1936
2460
|
success: true,
|
|
1937
2461
|
name,
|
|
1938
2462
|
output: config.output,
|
|
1939
|
-
stats: result.stats
|
|
2463
|
+
stats: result.stats,
|
|
2464
|
+
cached
|
|
1940
2465
|
};
|
|
1941
2466
|
} catch (error) {
|
|
1942
2467
|
return {
|
|
@@ -1970,52 +2495,52 @@ async function generateForOption(option) {
|
|
|
1970
2495
|
*/
|
|
1971
2496
|
function apiCodeGenPlugin(options) {
|
|
1972
2497
|
if (!Array.isArray(options) || options.length === 0) {
|
|
1973
|
-
|
|
2498
|
+
logger.warn("No API configurations provided to apiCodeGenPlugin");
|
|
1974
2499
|
return { name: PLUGIN_NAME };
|
|
1975
2500
|
}
|
|
1976
2501
|
return {
|
|
1977
2502
|
name: PLUGIN_NAME,
|
|
1978
2503
|
async config(_config, env) {
|
|
1979
|
-
|
|
2504
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2505
|
+
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
2506
|
+
console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
|
|
2507
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
1980
2508
|
const results = await Promise.all(options.map(generateForOption));
|
|
1981
2509
|
const successCount = results.filter((r) => r.success).length;
|
|
1982
2510
|
const failCount = options.length - successCount;
|
|
1983
|
-
|
|
2511
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
1984
2512
|
for (const result of results) if (result.success) {
|
|
1985
|
-
const { name, output, stats } = result;
|
|
1986
|
-
if (stats)
|
|
1987
|
-
|
|
2513
|
+
const { name, output, stats, cached } = result;
|
|
2514
|
+
if (stats) {
|
|
2515
|
+
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
2516
|
+
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
2517
|
+
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
1988
2518
|
} else {
|
|
1989
2519
|
const { name, error } = result;
|
|
1990
2520
|
if (isApicodegenError(error)) {
|
|
1991
|
-
|
|
1992
|
-
|
|
2521
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2522
|
+
console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
|
|
1993
2523
|
} else {
|
|
1994
2524
|
const wrapped = wrapError(error, {
|
|
1995
|
-
code:
|
|
2525
|
+
code: "E_GENERATION_FAILED",
|
|
1996
2526
|
message: `Failed to generate API "${name}"`
|
|
1997
2527
|
});
|
|
1998
|
-
|
|
1999
|
-
|
|
2528
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
2529
|
+
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
2000
2530
|
}
|
|
2001
2531
|
}
|
|
2002
|
-
|
|
2532
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2003
2533
|
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
2004
2534
|
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
2005
2535
|
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
endpoints: totalEndpoints,
|
|
2010
|
-
schemas: totalSchemas,
|
|
2011
|
-
duration: totalDuration
|
|
2012
|
-
});
|
|
2013
|
-
logger.divider();
|
|
2536
|
+
if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${options.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
2537
|
+
else console.log(`\x1b[33m⚠\x1b[0m API Code Gen - Complete (\x1b[90m${successCount} succeeded, ${failCount} failed\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
2538
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
2014
2539
|
return {};
|
|
2015
2540
|
}
|
|
2016
2541
|
};
|
|
2017
2542
|
}
|
|
2018
2543
|
//#endregion
|
|
2019
|
-
export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, codeGen, createErrors, formatError, isApicodegenError, loadConfig,
|
|
2544
|
+
export { Adapter, Adaptors, ApicodegenError, ArraySchemaType, AxiosAdapter, Base, Colors, ErrorCodes, FetchAdapter, Generator, HttpMethods, MediaTypes, NonArraySchemaType, OpenAPIProvider, OpenAPIVersion, ParameterIn, Provider, SchemaFormatType, SchemaType, SuccessHttpStatusCode, apiCodeGenPlugin, codeGen, configToCLIOptions, createErrors, formatError, isApicodegenError, loadConfig, mergeConfigs, printError, toProviderOptions, validateConfig, wrapError };
|
|
2020
2545
|
|
|
2021
2546
|
//# sourceMappingURL=index.mjs.map
|