@moccona/apicodegen 0.1.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +517 -121
- package/bin/cli.cjs +15 -12
- package/npm/index.cjs +2520 -1025
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +409 -93
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +409 -93
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +2390 -904
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +38 -10
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +2140 -648
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +41 -22
package/npm/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
3
|
var __create = Object.create;
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
5
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -16,29 +16,25 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
|
-
//#endregion
|
|
24
|
-
let undici = require("undici");
|
|
25
23
|
let typescript = require("typescript");
|
|
26
24
|
let node_fs_promises = require("node:fs/promises");
|
|
27
|
-
let
|
|
25
|
+
let node_url = require("node:url");
|
|
26
|
+
let undici = require("undici");
|
|
27
|
+
let yaml = require("yaml");
|
|
28
28
|
let node_path = require("node:path");
|
|
29
29
|
node_path = __toESM(node_path, 1);
|
|
30
|
+
let prettier = require("prettier");
|
|
30
31
|
let fs_extra = require("fs-extra");
|
|
31
32
|
fs_extra = __toESM(fs_extra, 1);
|
|
32
33
|
let _moccona_logger = require("@moccona/logger");
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
*/
|
|
38
|
-
var Adapter = class {};
|
|
39
|
-
//#endregion
|
|
40
|
-
//#region src/core/constants/keywords.ts
|
|
41
|
-
const typescriptKeywords = new Set([
|
|
34
|
+
let execa = require("execa");
|
|
35
|
+
let node_crypto = require("node:crypto");
|
|
36
|
+
// src/core/constants/keywords.ts
|
|
37
|
+
const typescriptKeywords = /* @__PURE__ */ new Set([
|
|
42
38
|
"break",
|
|
43
39
|
"case",
|
|
44
40
|
"catch",
|
|
@@ -114,408 +110,81 @@ const typescriptKeywords = new Set([
|
|
|
114
110
|
"undefined",
|
|
115
111
|
"bigint"
|
|
116
112
|
]);
|
|
117
|
-
|
|
118
|
-
//#region src/core/interface.ts
|
|
119
|
-
let SchemaType = /* @__PURE__ */ function(SchemaType) {
|
|
120
|
-
SchemaType["schemas"] = "schemas";
|
|
121
|
-
SchemaType["parameters"] = "parameters";
|
|
122
|
-
SchemaType["responses"] = "responses";
|
|
123
|
-
SchemaType["requestBodies"] = "requestBodies";
|
|
124
|
-
return SchemaType;
|
|
125
|
-
}({});
|
|
126
|
-
let NonArraySchemaType = /* @__PURE__ */ function(NonArraySchemaType) {
|
|
127
|
-
NonArraySchemaType["object"] = "object";
|
|
128
|
-
NonArraySchemaType["string"] = "string";
|
|
129
|
-
NonArraySchemaType["number"] = "number";
|
|
130
|
-
NonArraySchemaType["boolean"] = "boolean";
|
|
131
|
-
NonArraySchemaType["integer"] = "integer";
|
|
132
|
-
NonArraySchemaType["enum"] = "enum";
|
|
133
|
-
NonArraySchemaType["file"] = "file";
|
|
134
|
-
return NonArraySchemaType;
|
|
135
|
-
}({});
|
|
136
|
-
let ArraySchemaType = /* @__PURE__ */ function(ArraySchemaType) {
|
|
137
|
-
ArraySchemaType["array"] = "array";
|
|
138
|
-
return ArraySchemaType;
|
|
139
|
-
}({});
|
|
140
|
-
let SchemaFormatType = /* @__PURE__ */ function(SchemaFormatType) {
|
|
141
|
-
SchemaFormatType["string"] = "string";
|
|
142
|
-
SchemaFormatType["number"] = "number";
|
|
143
|
-
SchemaFormatType["boolean"] = "boolean";
|
|
144
|
-
SchemaFormatType["file"] = "file";
|
|
145
|
-
SchemaFormatType["binary"] = "binary";
|
|
146
|
-
SchemaFormatType["blob"] = "blob";
|
|
147
|
-
return SchemaFormatType;
|
|
148
|
-
}({});
|
|
149
|
-
let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
|
|
150
|
-
ParameterIn["header"] = "header";
|
|
151
|
-
ParameterIn["body"] = "body";
|
|
152
|
-
ParameterIn["query"] = "query";
|
|
153
|
-
ParameterIn["cookie"] = "cookie";
|
|
154
|
-
ParameterIn["path"] = "path";
|
|
155
|
-
ParameterIn["formData"] = "formData";
|
|
156
|
-
return ParameterIn;
|
|
157
|
-
}({});
|
|
158
|
-
let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
|
|
159
|
-
MediaTypes["JSON"] = "application/json";
|
|
160
|
-
MediaTypes["EVENT_STREAM"] = "text/event-stream";
|
|
161
|
-
MediaTypes["TEXT"] = "text";
|
|
162
|
-
MediaTypes["IMAGE"] = "image";
|
|
163
|
-
MediaTypes["AUDIO"] = "audio";
|
|
164
|
-
MediaTypes["VIDEO"] = "video";
|
|
165
|
-
return MediaTypes;
|
|
166
|
-
}({});
|
|
167
|
-
let HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
168
|
-
HttpMethods["GET"] = "get";
|
|
169
|
-
HttpMethods["PUT"] = "put";
|
|
170
|
-
HttpMethods["POST"] = "post";
|
|
171
|
-
HttpMethods["DELETE"] = "delete";
|
|
172
|
-
HttpMethods["OPTIONS"] = "options";
|
|
173
|
-
HttpMethods["HEAD"] = "head";
|
|
174
|
-
HttpMethods["PATCH"] = "patch";
|
|
175
|
-
HttpMethods["TRACE"] = "trace";
|
|
176
|
-
return HttpMethods;
|
|
177
|
-
}({});
|
|
178
|
-
let Adaptors = /* @__PURE__ */ function(Adaptors) {
|
|
179
|
-
Adaptors["fetch"] = "fetch";
|
|
180
|
-
Adaptors["axios"] = "axios";
|
|
181
|
-
return Adaptors;
|
|
182
|
-
}({});
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/core/base/Base.ts
|
|
113
|
+
// src/core/errors.ts
|
|
185
114
|
/**
|
|
186
|
-
*
|
|
187
|
-
* @author wp.l
|
|
188
|
-
* @description Base utility class providing common methods for code generation and API handling
|
|
189
|
-
*/
|
|
190
|
-
/**
|
|
191
|
-
* Represents success HTTP status codes.
|
|
192
|
-
* Each key is a string representation of a success HTTP status code.
|
|
115
|
+
* Error handling utilities for api-codegen
|
|
193
116
|
*/
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
"208": "208",
|
|
204
|
-
"226": "226"
|
|
117
|
+
const ErrorCodes = {
|
|
118
|
+
SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
|
|
119
|
+
SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
|
|
120
|
+
SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
|
|
121
|
+
OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
|
|
122
|
+
CONFIG_INVALID: "E_CONFIG_INVALID",
|
|
123
|
+
VALIDATION_FAILED: "E_VALIDATION_FAILED",
|
|
124
|
+
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
125
|
+
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
205
126
|
};
|
|
206
127
|
/**
|
|
207
|
-
*
|
|
128
|
+
* Custom error class for api-codegen with rich context
|
|
208
129
|
*/
|
|
209
|
-
var
|
|
210
|
-
|
|
211
|
-
|
|
130
|
+
var ApicodegenError = class ApicodegenError extends Error {
|
|
131
|
+
code;
|
|
132
|
+
location;
|
|
133
|
+
line;
|
|
134
|
+
column;
|
|
135
|
+
path;
|
|
136
|
+
suggestions;
|
|
137
|
+
cause;
|
|
138
|
+
constructor(context) {
|
|
139
|
+
super(context.message);
|
|
140
|
+
this.name = "ApicodegenError";
|
|
141
|
+
this.code = context.code;
|
|
142
|
+
this.location = context.location;
|
|
143
|
+
this.line = context.line;
|
|
144
|
+
this.column = context.column;
|
|
145
|
+
this.path = context.path;
|
|
146
|
+
this.suggestions = context.suggestions || [];
|
|
147
|
+
this.cause = context.cause;
|
|
148
|
+
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
212
149
|
}
|
|
213
150
|
/**
|
|
214
|
-
*
|
|
215
|
-
* @param ref - The reference string to process.
|
|
216
|
-
* @param [doc] - Optional document reference for context.
|
|
217
|
-
* @returns - The processed name.
|
|
151
|
+
* Convert error to formatted string for CLI output
|
|
218
152
|
*/
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
153
|
+
toString(verbose = false) {
|
|
154
|
+
const lines = [];
|
|
155
|
+
lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
|
|
156
|
+
if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
|
|
157
|
+
if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
|
|
158
|
+
if (this.line !== void 0) {
|
|
159
|
+
let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
|
|
160
|
+
if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
|
|
161
|
+
lines.push(lineInfo);
|
|
228
162
|
}
|
|
229
|
-
if (
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
* @param [operationId] - Unique identifier for the operation.
|
|
237
|
-
* @returns - The generated function name.
|
|
238
|
-
*/
|
|
239
|
-
static pathToFnName(path, method, _operationId = "") {
|
|
240
|
-
return Base.normalize(Base.camelCase(Base.normalize(path))) + (method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "");
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
244
|
-
* @param text - Input text to normalize.
|
|
245
|
-
* @returns - The normalized string.
|
|
246
|
-
*/
|
|
247
|
-
static normalize(text) {
|
|
248
|
-
if (typescriptKeywords.has(text)) text += "_";
|
|
249
|
-
return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d./gm, "").replaceAll("...", "");
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* Capitalizes the first character of a string.
|
|
253
|
-
* @param text - Input string.
|
|
254
|
-
* @returns - Capitalized string.
|
|
255
|
-
*/
|
|
256
|
-
static capitalize(text) {
|
|
257
|
-
text = text.trim();
|
|
258
|
-
return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
|
|
259
|
-
}
|
|
260
|
-
/**
|
|
261
|
-
* Converts a string to camelCase.
|
|
262
|
-
* @param text - Input string.
|
|
263
|
-
* @returns - CamelCase string.
|
|
264
|
-
*/
|
|
265
|
-
static camelCase(text) {
|
|
266
|
-
text = text.trim();
|
|
267
|
-
const parts = text.split("_").filter(Boolean);
|
|
268
|
-
while (parts[0]?.match(/^\d/)) parts.shift();
|
|
269
|
-
return parts.map((t, index) => index === 0 ? t : Base.capitalize(t)).join("");
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Converts a string to UpperCamelCase.
|
|
273
|
-
* @param text - Input string.
|
|
274
|
-
* @returns - UpperCamelCase string.
|
|
275
|
-
*/
|
|
276
|
-
static upperCamelCase(text) {
|
|
277
|
-
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(Base.capitalize).join("");
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Fetches documentation from a given URL.
|
|
281
|
-
* @param url - The URL to fetch the documentation from.
|
|
282
|
-
* @param requestInit - Additional request parameters.
|
|
283
|
-
* @returns - A promise resolving to the fetched documentation data.
|
|
284
|
-
*/
|
|
285
|
-
static async fetchDoc(url, requestInit = {}) {
|
|
286
|
-
const { body, statusCode } = await (0, undici.request)(url, {
|
|
287
|
-
method: "GET",
|
|
288
|
-
dispatcher: new undici.Agent({ connect: { rejectUnauthorized: false } }),
|
|
289
|
-
...requestInit
|
|
290
|
-
});
|
|
291
|
-
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${url}: HTTP ${statusCode}`);
|
|
292
|
-
try {
|
|
293
|
-
return body.json();
|
|
294
|
-
} catch (error) {
|
|
295
|
-
throw new Error(`Failed to parse JSON response from ${url}: ${error instanceof Error ? error.message : String(error)}`);
|
|
163
|
+
if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
|
|
164
|
+
if (verbose && this.cause) {
|
|
165
|
+
lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
|
|
166
|
+
if (this.stack) {
|
|
167
|
+
const stackLines = this.stack.split("\n").slice(1).join("\n");
|
|
168
|
+
lines.push(`\x1b[90m${stackLines}\x1b[0m`);
|
|
169
|
+
}
|
|
296
170
|
}
|
|
171
|
+
return lines.join("\n");
|
|
297
172
|
}
|
|
298
173
|
/**
|
|
299
|
-
*
|
|
300
|
-
* @param mediaType - The media type string to evaluate.
|
|
301
|
-
* @returns - The matched MediaTypes or null.
|
|
302
|
-
*/
|
|
303
|
-
static getMediaType(mediaType) {
|
|
304
|
-
return Object.values(MediaTypes).find((type) => mediaType.includes(type));
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* Checks if a schema is a valid enum type that isn't boolean.
|
|
308
|
-
* @param a - The schema object to evaluate.
|
|
309
|
-
* @returns - True if the schema is a valid non-boolean enum.
|
|
310
|
-
*/
|
|
311
|
-
static isValidEnumType(a) {
|
|
312
|
-
return a.type !== "boolean" && !Base.isBooleanEnum(a);
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Checks if a schema represents a boolean enum.
|
|
316
|
-
* @param a - The schema object to evaluate.
|
|
317
|
-
* @returns - True if the schema is a boolean enum.
|
|
318
|
-
*/
|
|
319
|
-
static isBooleanEnum(a) {
|
|
320
|
-
return a.type === "boolean" || !!a.enum?.some((member) => typeof member === "boolean");
|
|
321
|
-
}
|
|
322
|
-
/**
|
|
323
|
-
* Checks if two enum schemas are identical.
|
|
324
|
-
* @param a - First enum schema to compare.
|
|
325
|
-
* @param b - Second enum schema to compare.
|
|
326
|
-
* @returns - True if the enums are identical.
|
|
174
|
+
* Convert to JSON-serializable object
|
|
327
175
|
*/
|
|
328
|
-
|
|
329
|
-
return
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (existing) for (const value of e.enum) existing.add(value);
|
|
341
|
-
else enumMap.set(e.name, new Set(e.enum));
|
|
342
|
-
}
|
|
343
|
-
return Array.from(enumMap.entries()).map(([name, values]) => ({
|
|
344
|
-
name,
|
|
345
|
-
enum: Array.from(values)
|
|
346
|
-
}));
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* Finds the first occurrence of a matching enum schema in an array.
|
|
350
|
-
* @param a - The enum schema to find.
|
|
351
|
-
* @param enums - Array of enum schemas to search.
|
|
352
|
-
* @returns - The found schema or undefined.
|
|
353
|
-
*/
|
|
354
|
-
static findSameSchema(a, enums) {
|
|
355
|
-
return enums.find((b) => Base.isSameEnum(b, a));
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Checks if an object is a reference object.
|
|
359
|
-
* @param schema - The object to check.
|
|
360
|
-
* @returns - True if the object is a reference.
|
|
361
|
-
*/
|
|
362
|
-
static isRef(schema) {
|
|
363
|
-
return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
|
|
364
|
-
}
|
|
365
|
-
};
|
|
366
|
-
//#endregion
|
|
367
|
-
//#region src/core/base/Provider.ts
|
|
368
|
-
/**
|
|
369
|
-
* Abstract Provider Class.
|
|
370
|
-
*
|
|
371
|
-
* The Provider class is designed to be extended by specific implementations (e.g., OpenAPI 2 provider, OpenAPI 3 provider).
|
|
372
|
-
* It handles the initialization of the provider and the parsing of documentation into structured data.
|
|
373
|
-
*
|
|
374
|
-
* @example
|
|
375
|
-
*
|
|
376
|
-
* ```ts
|
|
377
|
-
* /// Example of how this class might be used by a subclass:
|
|
378
|
-
* class OpenAPIProvider extends Provider {
|
|
379
|
-
* /// Implement the parse method to handle OpenAPI-specific documentation parsing.
|
|
380
|
-
* parse(doc: unknown): ProviderInitResult {
|
|
381
|
-
* /// Implementation details...
|
|
382
|
-
* }
|
|
383
|
-
* }
|
|
384
|
-
*
|
|
385
|
-
* /// Initializing a provider with configuration and documentation data:
|
|
386
|
-
* const initOptions: ProviderInitOptions = {
|
|
387
|
-
* docURL: "https://example.com/api/swagger.json",
|
|
388
|
-
* baseURL: "https://api.example.com",
|
|
389
|
-
* output: "./generated",
|
|
390
|
-
* requestOptions: {
|
|
391
|
-
* headers: { "Content-Type": "application/json" },
|
|
392
|
-
* },
|
|
393
|
-
* importClientSource: "generated/client",
|
|
394
|
-
* };
|
|
395
|
-
*
|
|
396
|
-
* const docData = fetchSwaggerDoc();
|
|
397
|
-
* const provider = new OpenAPIProvider(initOptions, docData);
|
|
398
|
-
* ```
|
|
399
|
-
*/
|
|
400
|
-
var Provider = class {
|
|
401
|
-
/** collection of enum schemas */
|
|
402
|
-
enums = [];
|
|
403
|
-
/** collection of schemas indexed by name */
|
|
404
|
-
schemas = {};
|
|
405
|
-
/** collection of parameters indexed by name */
|
|
406
|
-
parameters = {};
|
|
407
|
-
/** collection of API responses indexed by name */
|
|
408
|
-
responses = {};
|
|
409
|
-
/** collection of request bodies indexed by name */
|
|
410
|
-
requestBodies = {};
|
|
411
|
-
/** collection of API endpoints (operations) indexed by path */
|
|
412
|
-
apis = {};
|
|
413
|
-
/** URL for fetching API documentation */
|
|
414
|
-
docURL;
|
|
415
|
-
/** base URL for API endpoints */
|
|
416
|
-
baseURL;
|
|
417
|
-
/** output directory for generated code */
|
|
418
|
-
output;
|
|
419
|
-
/** request options for API documentation fetch */
|
|
420
|
-
requestOptions;
|
|
421
|
-
/** source path for imported client */
|
|
422
|
-
importClientSource;
|
|
423
|
-
/**
|
|
424
|
-
* Provider Constructor.
|
|
425
|
-
* @param {ProviderInitOptions} initOptions - Initial configuration for the provider.
|
|
426
|
-
* @param {unknown} doc - Raw API documentation data to be parsed.
|
|
427
|
-
*/
|
|
428
|
-
constructor(initOptions, doc) {
|
|
429
|
-
this.docURL = initOptions.docURL;
|
|
430
|
-
this.baseURL = initOptions.baseURL ?? "";
|
|
431
|
-
this.output = initOptions.output ?? ".";
|
|
432
|
-
this.requestOptions = initOptions.requestOptions ?? {};
|
|
433
|
-
this.importClientSource = initOptions.importClientSource ?? "";
|
|
434
|
-
const { enums, schemas, requestBodies, responses, parameters, apis } = this.parse(doc);
|
|
435
|
-
this.enums = enums;
|
|
436
|
-
this.schemas = schemas;
|
|
437
|
-
this.responses = responses;
|
|
438
|
-
this.parameters = parameters;
|
|
439
|
-
this.requestBodies = requestBodies;
|
|
440
|
-
this.apis = apis;
|
|
441
|
-
}
|
|
442
|
-
};
|
|
443
|
-
//#endregion
|
|
444
|
-
//#region src/core/errors.ts
|
|
445
|
-
/**
|
|
446
|
-
* Error handling utilities for api-codegen
|
|
447
|
-
*/
|
|
448
|
-
const ErrorCodes = {
|
|
449
|
-
SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
|
|
450
|
-
SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
|
|
451
|
-
SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
|
|
452
|
-
OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
|
|
453
|
-
CONFIG_INVALID: "E_CONFIG_INVALID",
|
|
454
|
-
VALIDATION_FAILED: "E_VALIDATION_FAILED",
|
|
455
|
-
GENERATION_FAILED: "E_GENERATION_FAILED",
|
|
456
|
-
TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
|
|
457
|
-
};
|
|
458
|
-
/**
|
|
459
|
-
* Custom error class for api-codegen with rich context
|
|
460
|
-
*/
|
|
461
|
-
var ApicodegenError = class ApicodegenError extends Error {
|
|
462
|
-
code;
|
|
463
|
-
location;
|
|
464
|
-
line;
|
|
465
|
-
column;
|
|
466
|
-
path;
|
|
467
|
-
suggestions;
|
|
468
|
-
cause;
|
|
469
|
-
constructor(context) {
|
|
470
|
-
super(context.message);
|
|
471
|
-
this.name = "ApicodegenError";
|
|
472
|
-
this.code = context.code;
|
|
473
|
-
this.location = context.location;
|
|
474
|
-
this.line = context.line;
|
|
475
|
-
this.column = context.column;
|
|
476
|
-
this.path = context.path;
|
|
477
|
-
this.suggestions = context.suggestions || [];
|
|
478
|
-
this.cause = context.cause;
|
|
479
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
|
|
480
|
-
}
|
|
481
|
-
/**
|
|
482
|
-
* Convert error to formatted string for CLI output
|
|
483
|
-
*/
|
|
484
|
-
toString(verbose = false) {
|
|
485
|
-
const lines = [];
|
|
486
|
-
lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
|
|
487
|
-
if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
|
|
488
|
-
if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
|
|
489
|
-
if (this.line !== void 0) {
|
|
490
|
-
let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
|
|
491
|
-
if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
|
|
492
|
-
lines.push(lineInfo);
|
|
493
|
-
}
|
|
494
|
-
if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
|
|
495
|
-
if (verbose && this.cause) {
|
|
496
|
-
lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
|
|
497
|
-
if (this.stack) {
|
|
498
|
-
const stackLines = this.stack.split("\n").slice(1).join("\n");
|
|
499
|
-
lines.push(`\x1b[90m${stackLines}\x1b[0m`);
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
return lines.join("\n");
|
|
503
|
-
}
|
|
504
|
-
/**
|
|
505
|
-
* Convert to JSON-serializable object
|
|
506
|
-
*/
|
|
507
|
-
toJSON() {
|
|
508
|
-
return {
|
|
509
|
-
name: this.name,
|
|
510
|
-
code: this.code,
|
|
511
|
-
message: this.message,
|
|
512
|
-
location: this.location,
|
|
513
|
-
line: this.line,
|
|
514
|
-
column: this.column,
|
|
515
|
-
path: this.path,
|
|
516
|
-
suggestions: this.suggestions,
|
|
517
|
-
cause: this.cause?.message
|
|
518
|
-
};
|
|
176
|
+
toJSON() {
|
|
177
|
+
return {
|
|
178
|
+
name: this.name,
|
|
179
|
+
code: this.code,
|
|
180
|
+
message: this.message,
|
|
181
|
+
location: this.location,
|
|
182
|
+
line: this.line,
|
|
183
|
+
column: this.column,
|
|
184
|
+
path: this.path,
|
|
185
|
+
suggestions: this.suggestions,
|
|
186
|
+
cause: this.cause?.message
|
|
187
|
+
};
|
|
519
188
|
}
|
|
520
189
|
};
|
|
521
190
|
/**
|
|
@@ -638,12 +307,22 @@ const createErrors = {
|
|
|
638
307
|
cause
|
|
639
308
|
});
|
|
640
309
|
},
|
|
310
|
+
writeFailed(path, cause) {
|
|
311
|
+
return new ApicodegenError({
|
|
312
|
+
code: ErrorCodes.GENERATION_FAILED,
|
|
313
|
+
message: "Failed to write generated code",
|
|
314
|
+
location: path,
|
|
315
|
+
suggestions: ["Check that the output path is writable", "Ensure the output directory can be created"],
|
|
316
|
+
cause
|
|
317
|
+
});
|
|
318
|
+
},
|
|
641
319
|
typeCheckFailed(path, _errors, cause) {
|
|
642
320
|
return new ApicodegenError({
|
|
643
321
|
code: ErrorCodes.TYPE_CHECK_FAILED,
|
|
644
322
|
message: "TypeScript type check failed",
|
|
645
323
|
location: path,
|
|
646
324
|
suggestions: [
|
|
325
|
+
..._errors.length > 0 ? _errors : [],
|
|
647
326
|
"Review type errors above",
|
|
648
327
|
"Check for schema inconsistencies",
|
|
649
328
|
"Update generated types or fix source schema"
|
|
@@ -661,31 +340,700 @@ const createErrors = {
|
|
|
661
340
|
}
|
|
662
341
|
};
|
|
663
342
|
/**
|
|
664
|
-
* Wrap unknown error in ApicodegenError if needed
|
|
665
|
-
*/
|
|
666
|
-
function wrapError(error, context) {
|
|
667
|
-
if (error instanceof ApicodegenError) return error;
|
|
668
|
-
if (error instanceof Error) return new ApicodegenError({
|
|
669
|
-
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
670
|
-
message: context?.message || error.message,
|
|
671
|
-
location: context?.location,
|
|
672
|
-
suggestions: context?.suggestions,
|
|
673
|
-
cause: error
|
|
674
|
-
});
|
|
675
|
-
return new ApicodegenError({
|
|
676
|
-
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
677
|
-
message: String(error),
|
|
678
|
-
suggestions: context?.suggestions
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Check if error is an ApicodegenError
|
|
343
|
+
* Wrap unknown error in ApicodegenError if needed
|
|
344
|
+
*/
|
|
345
|
+
function wrapError(error, context) {
|
|
346
|
+
if (error instanceof ApicodegenError) return error;
|
|
347
|
+
if (error instanceof Error) return new ApicodegenError({
|
|
348
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
349
|
+
message: context?.message || error.message,
|
|
350
|
+
location: context?.location,
|
|
351
|
+
suggestions: context?.suggestions,
|
|
352
|
+
cause: error
|
|
353
|
+
});
|
|
354
|
+
return new ApicodegenError({
|
|
355
|
+
code: context?.code || ErrorCodes.GENERATION_FAILED,
|
|
356
|
+
message: String(error),
|
|
357
|
+
suggestions: context?.suggestions
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Check if error is an ApicodegenError
|
|
362
|
+
*/
|
|
363
|
+
function isApicodegenError(error) {
|
|
364
|
+
return error instanceof ApicodegenError;
|
|
365
|
+
}
|
|
366
|
+
// src/core/interface.ts
|
|
367
|
+
let SchemaType = /* @__PURE__ */ function(SchemaType) {
|
|
368
|
+
SchemaType["schemas"] = "schemas";
|
|
369
|
+
SchemaType["parameters"] = "parameters";
|
|
370
|
+
SchemaType["responses"] = "responses";
|
|
371
|
+
SchemaType["requestBodies"] = "requestBodies";
|
|
372
|
+
return SchemaType;
|
|
373
|
+
}({});
|
|
374
|
+
let NonArraySchemaType = /* @__PURE__ */ function(NonArraySchemaType) {
|
|
375
|
+
NonArraySchemaType["object"] = "object";
|
|
376
|
+
NonArraySchemaType["string"] = "string";
|
|
377
|
+
NonArraySchemaType["number"] = "number";
|
|
378
|
+
NonArraySchemaType["boolean"] = "boolean";
|
|
379
|
+
NonArraySchemaType["integer"] = "integer";
|
|
380
|
+
NonArraySchemaType["enum"] = "enum";
|
|
381
|
+
NonArraySchemaType["file"] = "file";
|
|
382
|
+
return NonArraySchemaType;
|
|
383
|
+
}({});
|
|
384
|
+
let ArraySchemaType = /* @__PURE__ */ function(ArraySchemaType) {
|
|
385
|
+
ArraySchemaType["array"] = "array";
|
|
386
|
+
return ArraySchemaType;
|
|
387
|
+
}({});
|
|
388
|
+
let SchemaFormatType = /* @__PURE__ */ function(SchemaFormatType) {
|
|
389
|
+
SchemaFormatType["string"] = "string";
|
|
390
|
+
SchemaFormatType["number"] = "number";
|
|
391
|
+
SchemaFormatType["boolean"] = "boolean";
|
|
392
|
+
SchemaFormatType["file"] = "file";
|
|
393
|
+
SchemaFormatType["binary"] = "binary";
|
|
394
|
+
SchemaFormatType["blob"] = "blob";
|
|
395
|
+
return SchemaFormatType;
|
|
396
|
+
}({});
|
|
397
|
+
let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
|
|
398
|
+
ParameterIn["header"] = "header";
|
|
399
|
+
ParameterIn["body"] = "body";
|
|
400
|
+
ParameterIn["query"] = "query";
|
|
401
|
+
ParameterIn["cookie"] = "cookie";
|
|
402
|
+
ParameterIn["path"] = "path";
|
|
403
|
+
ParameterIn["formData"] = "formData";
|
|
404
|
+
return ParameterIn;
|
|
405
|
+
}({});
|
|
406
|
+
let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
|
|
407
|
+
MediaTypes["JSON"] = "application/json";
|
|
408
|
+
MediaTypes["TEXT"] = "text";
|
|
409
|
+
MediaTypes["IMAGE"] = "image";
|
|
410
|
+
MediaTypes["AUDIO"] = "audio";
|
|
411
|
+
MediaTypes["VIDEO"] = "video";
|
|
412
|
+
return MediaTypes;
|
|
413
|
+
}({});
|
|
414
|
+
let HttpMethods = /* @__PURE__ */ function(HttpMethods) {
|
|
415
|
+
HttpMethods["GET"] = "get";
|
|
416
|
+
HttpMethods["PUT"] = "put";
|
|
417
|
+
HttpMethods["POST"] = "post";
|
|
418
|
+
HttpMethods["DELETE"] = "delete";
|
|
419
|
+
HttpMethods["OPTIONS"] = "options";
|
|
420
|
+
HttpMethods["HEAD"] = "head";
|
|
421
|
+
HttpMethods["PATCH"] = "patch";
|
|
422
|
+
HttpMethods["TRACE"] = "trace";
|
|
423
|
+
return HttpMethods;
|
|
424
|
+
}({});
|
|
425
|
+
let Adaptors = /* @__PURE__ */ function(Adaptors) {
|
|
426
|
+
Adaptors["fetch"] = "fetch";
|
|
427
|
+
Adaptors["axios"] = "axios";
|
|
428
|
+
return Adaptors;
|
|
429
|
+
}({});
|
|
430
|
+
// src/core/base/Base.ts
|
|
431
|
+
/**
|
|
432
|
+
* @file Base class implementation
|
|
433
|
+
* @author wp.l
|
|
434
|
+
* @description Base utility class providing common methods for code generation and API handling
|
|
435
|
+
*/
|
|
436
|
+
/**
|
|
437
|
+
* Represents success HTTP status codes.
|
|
438
|
+
* Each key is a string representation of a success HTTP status code.
|
|
439
|
+
*/
|
|
440
|
+
const SuccessHttpStatusCode = {
|
|
441
|
+
"200": "200",
|
|
442
|
+
"201": "201",
|
|
443
|
+
"202": "202",
|
|
444
|
+
"203": "203",
|
|
445
|
+
"204": "204",
|
|
446
|
+
"205": "205",
|
|
447
|
+
"206": "206",
|
|
448
|
+
"207": "207",
|
|
449
|
+
"208": "208",
|
|
450
|
+
"226": "226"
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Base abstract class providing common utility methods.
|
|
454
|
+
*/
|
|
455
|
+
var Base = class Base {
|
|
456
|
+
constructor() {
|
|
457
|
+
if (new.target === Base) throw new Error("Cannot instantiate abstract class");
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Converts a reference string to a meaningful name.
|
|
461
|
+
* @param ref - The reference string to process.
|
|
462
|
+
* @param [doc] - Optional document reference for context.
|
|
463
|
+
* @returns - The processed name.
|
|
464
|
+
*/
|
|
465
|
+
static ref2name(ref, doc) {
|
|
466
|
+
const paths = ref.replace(/^#/, "").split("/").filter(Boolean);
|
|
467
|
+
if (!doc) return paths.slice(-1)[0];
|
|
468
|
+
let temporary = doc;
|
|
469
|
+
let lastPath = "";
|
|
470
|
+
for (const path of paths) {
|
|
471
|
+
const adjustedPath = path.replaceAll("~1", "/");
|
|
472
|
+
temporary = temporary[adjustedPath];
|
|
473
|
+
lastPath = adjustedPath;
|
|
474
|
+
}
|
|
475
|
+
if (!temporary) return "unknown";
|
|
476
|
+
return temporary.$ref ? Base.ref2name(temporary.$ref, doc) : lastPath;
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Converts an API path to a function name.
|
|
480
|
+
* @param path - The API endpoint path.
|
|
481
|
+
* @param [method] - The HTTP method (e.g., GET, POST).
|
|
482
|
+
* @param [operationId] - Unique identifier for the operation.
|
|
483
|
+
* @returns - The generated function name.
|
|
484
|
+
*/
|
|
485
|
+
static pathToFnName(path, method, operationId) {
|
|
486
|
+
let name = "";
|
|
487
|
+
let keywordProtected = false;
|
|
488
|
+
if (operationId) {
|
|
489
|
+
keywordProtected = typescriptKeywords.has(operationId);
|
|
490
|
+
name = Base.camelCase(Base.normalize(operationId));
|
|
491
|
+
}
|
|
492
|
+
if (!name) {
|
|
493
|
+
keywordProtected = typescriptKeywords.has(path);
|
|
494
|
+
name = Base.camelCase(Base.normalize(path));
|
|
495
|
+
}
|
|
496
|
+
if (keywordProtected && !name.endsWith("_")) name = `${name}_`;
|
|
497
|
+
const suffix = method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "";
|
|
498
|
+
return name + suffix;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Converts arbitrary text into a legal TypeScript variable identifier.
|
|
502
|
+
* Keywords keep the `_` suffix that `normalize` adds, since `camelCase`
|
|
503
|
+
* would otherwise strip it and emit a reserved word.
|
|
504
|
+
* @param text - Input text.
|
|
505
|
+
* @returns - A legal identifier.
|
|
506
|
+
*/
|
|
507
|
+
static toIdentifier(text) {
|
|
508
|
+
const name = Base.camelCase(Base.normalize(text));
|
|
509
|
+
return typescriptKeywords.has(name) ? `${name}_` : name;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Normalizes a string by replacing special characters and avoiding TypeScript keywords.
|
|
513
|
+
* @param text - Input text to normalize.
|
|
514
|
+
* @returns - The normalized string.
|
|
515
|
+
*/
|
|
516
|
+
static normalize(text) {
|
|
517
|
+
if (typescriptKeywords.has(text)) text += "_";
|
|
518
|
+
return text.replaceAll("...", "").replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d/gm, "");
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Map a request body media type to a stable function-name suffix.
|
|
522
|
+
*
|
|
523
|
+
* Used to disambiguate sibling operations sharing the same path+method
|
|
524
|
+
* but different request body media types. The result is appended (in
|
|
525
|
+
* upperCamelCase) to the operation's base function name.
|
|
526
|
+
*
|
|
527
|
+
* Known types are mapped to short, human-readable names. Unknown types
|
|
528
|
+
* fall back to `camelCase(normalize(<sub-type>))`.
|
|
529
|
+
*
|
|
530
|
+
* @param mediaType - The OpenAPI media type (e.g. `application/json`).
|
|
531
|
+
* @returns - The suffix without leading underscore, or empty string.
|
|
532
|
+
*/
|
|
533
|
+
static mediaTypeToSuffix(mediaType) {
|
|
534
|
+
const known = {
|
|
535
|
+
"application/json": "Json",
|
|
536
|
+
"multipart/form-data": "FormData",
|
|
537
|
+
"application/x-www-form-urlencoded": "FormUrlencoded",
|
|
538
|
+
"application/octet-stream": "OctetStream",
|
|
539
|
+
"text/plain": "Text",
|
|
540
|
+
"text/html": "Html",
|
|
541
|
+
"application/xml": "Xml",
|
|
542
|
+
"text/xml": "Xml"
|
|
543
|
+
};
|
|
544
|
+
const normalized = mediaType.toLowerCase().split(";")[0]?.trim() ?? "";
|
|
545
|
+
if (known[normalized]) return known[normalized];
|
|
546
|
+
const sub = normalized.split("/")[1];
|
|
547
|
+
if (!sub || sub === "*" || normalized === "*/*" || normalized === "") return "";
|
|
548
|
+
return Base.upperCamelCase(Base.normalize(sub));
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Capitalizes the first character of a string.
|
|
552
|
+
* @param text - Input string.
|
|
553
|
+
* @returns - Capitalized string.
|
|
554
|
+
*/
|
|
555
|
+
static capitalize(text) {
|
|
556
|
+
text = text.trim();
|
|
557
|
+
return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Converts a string to camelCase.
|
|
561
|
+
* @param text - Input string.
|
|
562
|
+
* @returns - CamelCase string.
|
|
563
|
+
*/
|
|
564
|
+
static camelCase(text) {
|
|
565
|
+
text = text.trim();
|
|
566
|
+
const parts = text.split("_").filter(Boolean);
|
|
567
|
+
while (parts[0]?.match(/^\d/)) parts.shift();
|
|
568
|
+
return parts.map((t, index) => index === 0 ? t : Base.capitalize(t)).join("");
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Converts a string to UpperCamelCase.
|
|
572
|
+
* @param text - Input string.
|
|
573
|
+
* @returns - UpperCamelCase string.
|
|
574
|
+
*/
|
|
575
|
+
static upperCamelCase(text) {
|
|
576
|
+
return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map((part) => part.match(/^\d/) ? `N${part}` : Base.capitalize(part)).join("");
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Classify a spec location string into a transport + source pair.
|
|
580
|
+
*
|
|
581
|
+
* Returns:
|
|
582
|
+
* - `{ transport: 'file', source }` when `input` looks like a local
|
|
583
|
+
* filesystem path (`file://...`, POSIX absolute, Windows absolute).
|
|
584
|
+
* - `{ transport: 'http', source }` for `http(s)://...` URLs.
|
|
585
|
+
*
|
|
586
|
+
* Relative paths are treated as `http` so that callers (CLI / Vite
|
|
587
|
+
* plugin) must resolve them against cwd first. This makes intent
|
|
588
|
+
* explicit and avoids accidentally reading from process.cwd().
|
|
589
|
+
*/
|
|
590
|
+
static resolveSpecURL(input) {
|
|
591
|
+
if (input.startsWith("file://")) {
|
|
592
|
+
const stripped = input.replace(/^file:\/\//, "");
|
|
593
|
+
return {
|
|
594
|
+
transport: "file",
|
|
595
|
+
source: /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
if (input.startsWith("/")) return {
|
|
599
|
+
transport: "file",
|
|
600
|
+
source: input
|
|
601
|
+
};
|
|
602
|
+
if (/^[A-Za-z]:[\\/]/.test(input)) return {
|
|
603
|
+
transport: "file",
|
|
604
|
+
source: input
|
|
605
|
+
};
|
|
606
|
+
return {
|
|
607
|
+
transport: "http",
|
|
608
|
+
source: input
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Read and parse a local OpenAPI document from the filesystem.
|
|
613
|
+
*
|
|
614
|
+
* @param filePath - Absolute filesystem path to the spec.
|
|
615
|
+
* @returns - A promise resolving to the parsed document.
|
|
616
|
+
*/
|
|
617
|
+
static async readLocalDoc(filePath) {
|
|
618
|
+
let raw;
|
|
619
|
+
try {
|
|
620
|
+
raw = await (0, node_fs_promises.readFile)(filePath, "utf8");
|
|
621
|
+
} catch (error) {
|
|
622
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
|
|
623
|
+
throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
624
|
+
}
|
|
625
|
+
return Base.parseDoc(raw, filePath);
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Parses an OpenAPI document from JSON or YAML text.
|
|
629
|
+
*
|
|
630
|
+
* JSON is attempted first for a clearer syntax error on JSON files; YAML
|
|
631
|
+
* then handles `.yaml` / `.yml` specs. Any failure is reported as
|
|
632
|
+
* `E_SPEC_PARSE_FAILED` with the source path attached.
|
|
633
|
+
*
|
|
634
|
+
* @param raw - Raw spec content.
|
|
635
|
+
* @param source - Path or URL used in error messages.
|
|
636
|
+
* @returns - The parsed document.
|
|
637
|
+
*/
|
|
638
|
+
static parseDoc(raw, source) {
|
|
639
|
+
let parsed;
|
|
640
|
+
try {
|
|
641
|
+
parsed = JSON.parse(raw);
|
|
642
|
+
} catch {
|
|
643
|
+
try {
|
|
644
|
+
parsed = (0, yaml.parse)(raw);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
throw createErrors.specParseFailed(source, void 0, void 0, error);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (parsed === null || typeof parsed !== "object") throw createErrors.specParseFailed(source, void 0, void 0, /* @__PURE__ */ new Error("Spec must be a JSON or YAML object"));
|
|
650
|
+
return parsed;
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Fetches documentation from a given URL.
|
|
654
|
+
*
|
|
655
|
+
* Supports three transport modes:
|
|
656
|
+
* - `file://...` URLs → read from filesystem (JSON or YAML)
|
|
657
|
+
* - absolute filesystem paths → read from filesystem (JSON or YAML)
|
|
658
|
+
* - `http(s)://...` URLs (and unrecognised inputs like relative paths)
|
|
659
|
+
* → fetched via undici (existing behavior)
|
|
660
|
+
*
|
|
661
|
+
* Callers should pass an already-resolved absolute path or URL. Relative
|
|
662
|
+
* paths fall through to undici by design — CLI / Vite plugin should
|
|
663
|
+
* resolve them against cwd first.
|
|
664
|
+
*
|
|
665
|
+
* @param url - The URL or filesystem path to fetch the documentation from.
|
|
666
|
+
* @param requestInit - Additional request parameters (only used for http(s)).
|
|
667
|
+
* TLS certificates are verified by default; set `insecure: true` to opt out.
|
|
668
|
+
* @returns - A promise resolving to the fetched documentation data.
|
|
669
|
+
*/
|
|
670
|
+
static async fetchDoc(url, requestInit = {}) {
|
|
671
|
+
const { transport, source } = Base.resolveSpecURL(url);
|
|
672
|
+
if (transport === "file") return Base.readLocalDoc(source);
|
|
673
|
+
const { insecure = false, ...init } = requestInit;
|
|
674
|
+
const { body, statusCode } = await (0, undici.request)(source, {
|
|
675
|
+
method: "GET",
|
|
676
|
+
...insecure ? { dispatcher: new undici.Agent({ connect: { rejectUnauthorized: false } }) } : {},
|
|
677
|
+
...init
|
|
678
|
+
});
|
|
679
|
+
if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
|
|
680
|
+
return Base.parseDoc(await body.text(), source);
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Copies external `$ref` targets (other files or remote URLs) into the root
|
|
684
|
+
* document and rewrites the refs to local ones. Objects are registered
|
|
685
|
+
* before their children are walked, so cycles keep working.
|
|
686
|
+
*
|
|
687
|
+
* External refs are placed in the component section implied by their
|
|
688
|
+
* fragment (`schemas` by default); a generated local `$ref` points at the
|
|
689
|
+
* copy.
|
|
690
|
+
*
|
|
691
|
+
* @param doc - Parsed root document (mutated in place).
|
|
692
|
+
* @param source - Absolute path or URL of the root document.
|
|
693
|
+
* @param requestInit - Request options for remote refs.
|
|
694
|
+
* @returns - The same document with external refs resolved.
|
|
695
|
+
*/
|
|
696
|
+
static async bundleExternalRefs(doc, source, requestInit = {}) {
|
|
697
|
+
const root = doc;
|
|
698
|
+
const isV2 = typeof root.swagger === "string";
|
|
699
|
+
const rootURL = Base.resolveSpecURL(source).transport === "file" ? (0, node_url.pathToFileURL)(source).href : source;
|
|
700
|
+
const docs = /* @__PURE__ */ new Map([[rootURL, root]]);
|
|
701
|
+
const registered = /* @__PURE__ */ new Map();
|
|
702
|
+
const loadDoc = async (url) => {
|
|
703
|
+
const cached = docs.get(url);
|
|
704
|
+
if (cached !== void 0) return cached;
|
|
705
|
+
const loaded = await Base.fetchDoc(url, requestInit);
|
|
706
|
+
docs.set(url, loaded);
|
|
707
|
+
return loaded;
|
|
708
|
+
};
|
|
709
|
+
const containerFor = (ref) => {
|
|
710
|
+
const section = Base.externalRefSection(ref, isV2);
|
|
711
|
+
if (isV2) {
|
|
712
|
+
root[section] ??= {};
|
|
713
|
+
return {
|
|
714
|
+
record: root[section],
|
|
715
|
+
prefix: `#/${section}/`
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
root.components ??= {};
|
|
719
|
+
root.components[section] ??= {};
|
|
720
|
+
return {
|
|
721
|
+
record: root.components[section],
|
|
722
|
+
prefix: `#/components/${section}/`
|
|
723
|
+
};
|
|
724
|
+
};
|
|
725
|
+
const register = async (absolute) => {
|
|
726
|
+
const existing = registered.get(absolute);
|
|
727
|
+
if (existing) return existing;
|
|
728
|
+
const hashIndex = absolute.indexOf("#");
|
|
729
|
+
const docURL = hashIndex === -1 ? absolute : absolute.slice(0, hashIndex);
|
|
730
|
+
const fragment = hashIndex === -1 ? "" : absolute.slice(hashIndex);
|
|
731
|
+
const externalDoc = await loadDoc(docURL);
|
|
732
|
+
const { record, prefix } = containerFor(fragment);
|
|
733
|
+
const target = Base.resolveJSONPointer(externalDoc, fragment);
|
|
734
|
+
if (target === void 0) return `${prefix}unknown`;
|
|
735
|
+
const baseName = Base.externalRefName(fragment, docURL);
|
|
736
|
+
let name = baseName;
|
|
737
|
+
let suffix = 2;
|
|
738
|
+
while (name in record) {
|
|
739
|
+
name = `${baseName}${suffix}`;
|
|
740
|
+
suffix++;
|
|
741
|
+
}
|
|
742
|
+
registered.set(absolute, prefix + name);
|
|
743
|
+
record[name] = target;
|
|
744
|
+
await walk(target, docURL);
|
|
745
|
+
return prefix + name;
|
|
746
|
+
};
|
|
747
|
+
const walk = async (value, docURL) => {
|
|
748
|
+
if (Array.isArray(value)) {
|
|
749
|
+
for (const item of value) await walk(item, docURL);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (value === null || typeof value !== "object") return;
|
|
753
|
+
const object = value;
|
|
754
|
+
if (typeof object.$ref === "string") {
|
|
755
|
+
const ref = object.$ref;
|
|
756
|
+
if (ref.startsWith("#") && docURL === rootURL) return;
|
|
757
|
+
const absolute = ref.startsWith("#") ? docURL + ref : new URL(ref, docURL).href;
|
|
758
|
+
if ((docURL.startsWith("http://") || docURL.startsWith("https://")) && !absolute.startsWith("http://") && !absolute.startsWith("https://")) throw new Error(`Refusing to resolve external $ref from a remote document: ${absolute}`);
|
|
759
|
+
object.$ref = await register(absolute);
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
for (const key of Object.keys(object)) await walk(object[key], docURL);
|
|
763
|
+
};
|
|
764
|
+
await walk(root, rootURL);
|
|
765
|
+
return doc;
|
|
766
|
+
}
|
|
767
|
+
/** Component section an external ref belongs to. */
|
|
768
|
+
static externalRefSection(ref, isV2) {
|
|
769
|
+
if (isV2) {
|
|
770
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
771
|
+
if (ref.includes("/responses/")) return "responses";
|
|
772
|
+
return "definitions";
|
|
773
|
+
}
|
|
774
|
+
if (ref.includes("/parameters/")) return "parameters";
|
|
775
|
+
if (ref.includes("/responses/")) return "responses";
|
|
776
|
+
if (ref.includes("/requestBodies/")) return "requestBodies";
|
|
777
|
+
return "schemas";
|
|
778
|
+
}
|
|
779
|
+
/** Local component name derived from the ref fragment or file name. */
|
|
780
|
+
static externalRefName(fragment, docURL) {
|
|
781
|
+
let name = fragment.replace(/^#/, "").split("/").filter(Boolean).map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).at(-1) ?? "";
|
|
782
|
+
if (!name) try {
|
|
783
|
+
name = new URL(docURL).pathname.split("/").pop() ?? "";
|
|
784
|
+
} catch {
|
|
785
|
+
name = "";
|
|
786
|
+
}
|
|
787
|
+
name = name.replace(/\.(json|ya?ml)$/i, "").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
788
|
+
return name || "External";
|
|
789
|
+
}
|
|
790
|
+
/** Resolves a `#/a/b` JSON pointer inside a parsed document. */
|
|
791
|
+
static resolveJSONPointer(doc, fragment) {
|
|
792
|
+
if (!fragment) return doc;
|
|
793
|
+
const parts = fragment.replace(/^#\/?/, "").split("/").filter(Boolean).map((part) => decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
794
|
+
let current = doc;
|
|
795
|
+
for (const part of parts) {
|
|
796
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
797
|
+
current = current[part];
|
|
798
|
+
}
|
|
799
|
+
return current;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Determines the media type from a given media type string.
|
|
803
|
+
* @param mediaType - The media type string to evaluate.
|
|
804
|
+
* @returns - The matched MediaTypes or null.
|
|
805
|
+
*/
|
|
806
|
+
static getMediaType(mediaType) {
|
|
807
|
+
return Object.values(MediaTypes).find((type) => mediaType.includes(type));
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Checks if a schema is a valid enum type that isn't boolean.
|
|
811
|
+
* @param a - The schema object to evaluate.
|
|
812
|
+
* @returns - True if the schema is a valid non-boolean enum.
|
|
813
|
+
*/
|
|
814
|
+
static isValidEnumType(a) {
|
|
815
|
+
return a.type !== "boolean" && !Base.isBooleanEnum(a);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Checks if a schema represents a boolean enum.
|
|
819
|
+
* @param a - The schema object to evaluate.
|
|
820
|
+
* @returns - True if the schema is a boolean enum.
|
|
821
|
+
*/
|
|
822
|
+
static isBooleanEnum(a) {
|
|
823
|
+
return a.type === "boolean" || !!a.enum?.some((member) => typeof member === "boolean");
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Checks if two enum schemas are identical.
|
|
827
|
+
* @param a - First enum schema to compare.
|
|
828
|
+
* @param b - Second enum schema to compare.
|
|
829
|
+
* @returns - True if the enums are identical.
|
|
830
|
+
*/
|
|
831
|
+
static isSameEnum(a, b) {
|
|
832
|
+
return a.enum.length === b.enum.length && a.enum.sort().every((v, index) => v === b.enum.sort()[index]);
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Filters out duplicate enum schemas from an array.
|
|
836
|
+
* @param enums - Array of enum schemas to process.
|
|
837
|
+
* @returns - Array of unique enum schemas.
|
|
838
|
+
*/
|
|
839
|
+
static uniqueEnums(enums) {
|
|
840
|
+
const enumMap = /* @__PURE__ */ new Map();
|
|
841
|
+
for (const e of enums) {
|
|
842
|
+
const existing = enumMap.get(e.name);
|
|
843
|
+
if (existing) for (const value of e.enum) existing.add(value);
|
|
844
|
+
else enumMap.set(e.name, new Set(e.enum));
|
|
845
|
+
}
|
|
846
|
+
return Array.from(enumMap.entries()).map(([name, values]) => ({
|
|
847
|
+
name,
|
|
848
|
+
enum: Array.from(values)
|
|
849
|
+
}));
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Finds the first occurrence of a matching enum schema in an array.
|
|
853
|
+
* @param a - The enum schema to find.
|
|
854
|
+
* @param enums - Array of enum schemas to search.
|
|
855
|
+
* @returns - The found schema or undefined.
|
|
856
|
+
*/
|
|
857
|
+
static findSameSchema(a, enums) {
|
|
858
|
+
return enums.find((b) => Base.isSameEnum(b, a));
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Checks if an object is a reference object.
|
|
862
|
+
* @param schema - The object to check.
|
|
863
|
+
* @returns - True if the object is a reference.
|
|
864
|
+
*/
|
|
865
|
+
static isRef(schema) {
|
|
866
|
+
return typeof schema === "object" && schema !== null && "$ref" in schema && typeof schema.$ref === "string";
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
// src/core/base/Adaptor.ts
|
|
870
|
+
/** `options?.name` */
|
|
871
|
+
function optionalAccess(control, name) {
|
|
872
|
+
return typescript.factory.createPropertyAccessChain(typescript.factory.createIdentifier(control.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionDotToken), typescript.factory.createIdentifier(name));
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* `options?.signal && options?.timeout ? AbortSignal.any([...]) : ...`,
|
|
876
|
+
* combining a caller signal with a timeout when both are present.
|
|
877
|
+
*/
|
|
878
|
+
function fetchSignalExpression(control) {
|
|
879
|
+
const signal = optionalAccess(control, "signal");
|
|
880
|
+
const timeout = optionalAccess(control, "timeout");
|
|
881
|
+
const timeoutSignal = () => typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("AbortSignal"), typescript.factory.createIdentifier("timeout")), void 0, [timeout]);
|
|
882
|
+
const both = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("AbortSignal"), typescript.factory.createIdentifier("any")), void 0, [typescript.factory.createArrayLiteralExpression([signal, timeoutSignal()])]);
|
|
883
|
+
return typescript.factory.createConditionalExpression(signal, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createConditionalExpression(timeout, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), both, typescript.factory.createToken(typescript.SyntaxKind.ColonToken), signal), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createConditionalExpression(timeout, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), timeoutSignal(), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createIdentifier("undefined")));
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Header entries plus a spread of caller-supplied headers.
|
|
887
|
+
*/
|
|
888
|
+
function withRequestHeaders(entries, control) {
|
|
889
|
+
if (!control) return entries;
|
|
890
|
+
return [...entries, typescript.factory.createSpreadAssignment(optionalAccess(control, "headers"))];
|
|
891
|
+
}
|
|
892
|
+
/** `auth?.["scheme"]` */
|
|
893
|
+
function authAccess(auth, scheme) {
|
|
894
|
+
return typescript.factory.createElementAccessChain(typescript.factory.createIdentifier(auth.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionDotToken), typescript.factory.createStringLiteral(scheme));
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Header entries (conditional spreads) for auth schemes sent as headers.
|
|
898
|
+
*/
|
|
899
|
+
function authHeaderEntries(auth) {
|
|
900
|
+
return auth.injections.filter((injection) => injection.location === "header").map((injection) => {
|
|
901
|
+
const access = authAccess(auth, injection.scheme);
|
|
902
|
+
const hasValue = typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
903
|
+
let value;
|
|
904
|
+
let condition = hasValue;
|
|
905
|
+
if (injection.kind === "basic") {
|
|
906
|
+
condition = typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createBinaryExpression(typescript.factory.createTypeOfExpression(access), typescript.factory.createToken(typescript.SyntaxKind.EqualsEqualsEqualsToken), typescript.factory.createStringLiteral("object")));
|
|
907
|
+
const credentials = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(""), [typescript.factory.createTemplateSpan(typescript.factory.createPropertyAccessExpression(access, "username"), typescript.factory.createTemplateMiddle(":")), typescript.factory.createTemplateSpan(typescript.factory.createPropertyAccessExpression(access, "password"), typescript.factory.createTemplateTail(""))]);
|
|
908
|
+
value = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("Basic "), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("btoa"), void 0, [credentials]), typescript.factory.createTemplateTail(""))]);
|
|
909
|
+
} else if (injection.kind === "bearer") value = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("Bearer "), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access]), typescript.factory.createTemplateTail(""))]);
|
|
910
|
+
else value = typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access]);
|
|
911
|
+
return typescript.factory.createSpreadAssignment(typescript.factory.createConditionalExpression(condition, typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(injection.name), value)], false), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createObjectLiteralExpression([], false)));
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Builds a `Cookie` header value from OpenAPI cookie parameters.
|
|
916
|
+
* Undefined/null values are filtered out at runtime.
|
|
917
|
+
*/
|
|
918
|
+
function cookieHeaderExpression(parameters, auth) {
|
|
919
|
+
const entries = parameters.filter((p) => p.in === "cookie").map((parameter) => {
|
|
920
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
921
|
+
return typescript.factory.createConditionalExpression(typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(`${parameter.name}=`), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [id])]), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""));
|
|
922
|
+
});
|
|
923
|
+
const authEntries = auth ? auth.injections.filter((injection) => injection.location === "cookie").map((injection) => {
|
|
924
|
+
const access = authAccess(auth, injection.scheme);
|
|
925
|
+
return typescript.factory.createConditionalExpression(typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(`${injection.name}=`), [typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [access])]), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""));
|
|
926
|
+
}) : [];
|
|
927
|
+
return typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createArrayLiteralExpression([...entries, ...authEntries], true), typescript.factory.createIdentifier("filter")), void 0, [typescript.factory.createIdentifier("Boolean")]), typescript.factory.createIdentifier("join")), void 0, [typescript.factory.createStringLiteral("; ")]);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Base adapter for tool
|
|
931
|
+
* This abstract class serves as the foundation for implementing adapters for different code generation tools
|
|
932
|
+
*/
|
|
933
|
+
var Adapter = class {};
|
|
934
|
+
// src/core/base/Provider.ts
|
|
935
|
+
/**
|
|
936
|
+
* Abstract Provider Class.
|
|
937
|
+
*
|
|
938
|
+
* The Provider class is designed to be extended by specific implementations (e.g., OpenAPI 2 provider, OpenAPI 3 provider).
|
|
939
|
+
* It handles the initialization of the provider and the parsing of documentation into structured data.
|
|
940
|
+
*
|
|
941
|
+
* @example
|
|
942
|
+
*
|
|
943
|
+
* ```ts
|
|
944
|
+
* /// Example of how this class might be used by a subclass:
|
|
945
|
+
* class OpenAPIProvider extends Provider {
|
|
946
|
+
* /// Implement the parse method to handle OpenAPI-specific documentation parsing.
|
|
947
|
+
* parse(doc: unknown): ProviderInitResult {
|
|
948
|
+
* /// Implementation details...
|
|
949
|
+
* }
|
|
950
|
+
* }
|
|
951
|
+
*
|
|
952
|
+
* /// Initializing a provider with configuration and documentation data:
|
|
953
|
+
* const initOptions: ProviderInitOptions = {
|
|
954
|
+
* docURL: "https://example.com/api/swagger.json",
|
|
955
|
+
* baseURL: "https://api.example.com",
|
|
956
|
+
* output: "./generated",
|
|
957
|
+
* requestOptions: {
|
|
958
|
+
* headers: { "Content-Type": "application/json" },
|
|
959
|
+
* },
|
|
960
|
+
* importClientSource: "generated/client",
|
|
961
|
+
* };
|
|
962
|
+
*
|
|
963
|
+
* const docData = fetchSwaggerDoc();
|
|
964
|
+
* const provider = new OpenAPIProvider(initOptions, docData);
|
|
965
|
+
* ```
|
|
966
|
+
*/
|
|
967
|
+
var Provider = class {
|
|
968
|
+
/** collection of enum schemas */
|
|
969
|
+
enums = [];
|
|
970
|
+
/** collection of schemas indexed by name */
|
|
971
|
+
schemas = {};
|
|
972
|
+
/** collection of parameters indexed by name */
|
|
973
|
+
parameters = {};
|
|
974
|
+
/** collection of API responses indexed by name */
|
|
975
|
+
responses = {};
|
|
976
|
+
/** collection of request bodies indexed by name */
|
|
977
|
+
requestBodies = {};
|
|
978
|
+
/** security schemes declared by the document */
|
|
979
|
+
securitySchemes = {};
|
|
980
|
+
/** collection of API endpoints (operations) indexed by path */
|
|
981
|
+
apis = {};
|
|
982
|
+
/** URL for fetching API documentation */
|
|
983
|
+
docURL;
|
|
984
|
+
/** base URL for API endpoints */
|
|
985
|
+
baseURL;
|
|
986
|
+
/** output directory for generated code */
|
|
987
|
+
output;
|
|
988
|
+
/** request options for API documentation fetch */
|
|
989
|
+
requestOptions;
|
|
990
|
+
/** source path for imported client */
|
|
991
|
+
importClientSource;
|
|
992
|
+
/**
|
|
993
|
+
* Provider Constructor.
|
|
994
|
+
* @param {ProviderInitOptions} initOptions - Initial configuration for the provider.
|
|
995
|
+
* @param {unknown} doc - Raw API documentation data to be parsed.
|
|
996
|
+
*/
|
|
997
|
+
constructor(initOptions, doc) {
|
|
998
|
+
this.docURL = initOptions.docURL;
|
|
999
|
+
this.baseURL = initOptions.baseURL ?? "";
|
|
1000
|
+
this.output = initOptions.output ?? ".";
|
|
1001
|
+
this.requestOptions = initOptions.requestOptions ?? {};
|
|
1002
|
+
this.importClientSource = initOptions.importClientSource ?? "";
|
|
1003
|
+
const { enums, schemas, requestBodies, responses, parameters, securitySchemes, apis } = this.parse(doc);
|
|
1004
|
+
this.enums = enums;
|
|
1005
|
+
this.schemas = schemas;
|
|
1006
|
+
this.responses = responses;
|
|
1007
|
+
this.parameters = parameters;
|
|
1008
|
+
this.requestBodies = requestBodies;
|
|
1009
|
+
this.securitySchemes = securitySchemes;
|
|
1010
|
+
this.apis = apis;
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
// src/core/generator/naming.ts
|
|
1014
|
+
/**
|
|
1015
|
+
* Create a per-generation unique-name resolver.
|
|
1016
|
+
*
|
|
1017
|
+
* Tracks how many times each base name has been seen during a single
|
|
1018
|
+
* code generation pass and returns a unique variant on every call:
|
|
1019
|
+
*
|
|
1020
|
+
* reserve('foo') // 'foo'
|
|
1021
|
+
* reserve('foo') // 'foo2'
|
|
1022
|
+
* reserve('foo') // 'foo3'
|
|
1023
|
+
* reserve('bar') // 'bar' (independent counter)
|
|
1024
|
+
*
|
|
1025
|
+
* The resolver holds no module-level state — create one per generation pass
|
|
1026
|
+
* and let it go out of scope when the pass completes.
|
|
683
1027
|
*/
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
1028
|
+
const createUniqueNameResolver = () => {
|
|
1029
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1030
|
+
return (name) => {
|
|
1031
|
+
const next = (seen.get(name) ?? 0) + 1;
|
|
1032
|
+
seen.set(name, next);
|
|
1033
|
+
return next === 1 ? name : `${name}${next}`;
|
|
1034
|
+
};
|
|
1035
|
+
};
|
|
1036
|
+
// src/core/generator/index.ts
|
|
689
1037
|
var Generator = class Generator {
|
|
690
1038
|
/**
|
|
691
1039
|
* Converts an array of TypeScript statements into a formatted string of code.
|
|
@@ -700,19 +1048,11 @@ var Generator = class Generator {
|
|
|
700
1048
|
return (0, typescript.createPrinter)().printFile(sourceFile);
|
|
701
1049
|
}
|
|
702
1050
|
static async write(code, filepath) {
|
|
703
|
-
const { mkdir } = await import("node:fs/promises");
|
|
704
|
-
const { dirname } = await import("node:path");
|
|
705
1051
|
try {
|
|
706
|
-
await mkdir(dirname(filepath), { recursive: true });
|
|
1052
|
+
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filepath), { recursive: true });
|
|
707
1053
|
await (0, node_fs_promises.writeFile)(filepath, code);
|
|
708
1054
|
} catch (error) {
|
|
709
|
-
throw new
|
|
710
|
-
code: ErrorCodes.OUTPUT_DIR_MISSING,
|
|
711
|
-
message: "Failed to write generated code to output file",
|
|
712
|
-
location: filepath,
|
|
713
|
-
cause: error instanceof Error ? error : new Error(String(error)),
|
|
714
|
-
suggestions: ["Verify the output directory path is writable", "Check that the parent directory exists or can be created"]
|
|
715
|
-
});
|
|
1055
|
+
throw createErrors.writeFailed(filepath, error instanceof Error ? error : new Error(String(error)));
|
|
716
1056
|
}
|
|
717
1057
|
}
|
|
718
1058
|
/**
|
|
@@ -724,22 +1064,84 @@ var Generator = class Generator {
|
|
|
724
1064
|
* @param basePath - Optional base path to prepend (default: "").
|
|
725
1065
|
* @returns A TypeScript template expressi
|
|
726
1066
|
*/
|
|
727
|
-
static toUrlTemplate(path, parameters, basePath = "") {
|
|
1067
|
+
static toUrlTemplate(path, parameters, basePath = "", auth) {
|
|
1068
|
+
const pathExpression = Generator.toPathTemplate(path, basePath);
|
|
728
1069
|
const queryParameters = parameters.filter((p) => p.in === "query");
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
1070
|
+
const hasAuthQuery = auth?.injections.some((injection) => injection.location === "query");
|
|
1071
|
+
if (queryParameters.length === 0 && !hasAuthQuery) return pathExpression;
|
|
1072
|
+
return typescript.factory.createBinaryExpression(pathExpression, typescript.factory.createToken(typescript.SyntaxKind.PlusToken), Generator.toQueryStringExpression(queryParameters, auth));
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Builds the path part of a URL, encoding every `{param}` interpolation.
|
|
1076
|
+
*/
|
|
1077
|
+
static toPathTemplate(path, basePath) {
|
|
733
1078
|
const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
|
|
734
1079
|
if (pathSegments.length === 1) return typescript.factory.createNoSubstitutionTemplateLiteral(basePath + path);
|
|
735
1080
|
return typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(basePath + pathSegments[0]), pathSegments.slice(1).map((segment, index) => {
|
|
736
1081
|
const match = /^{(.+)}(.+)?/gm.exec(segment);
|
|
737
1082
|
const isLastSegment = index === pathSegments.length - 2;
|
|
738
1083
|
if (!match) throw new Error(`Invalid path segment: ${segment}`);
|
|
739
|
-
return typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(Base.
|
|
1084
|
+
return typescript.factory.createTemplateSpan(typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(match[1]))])]), !isLastSegment ? typescript.factory.createTemplateMiddle(match[2]) : typescript.factory.createTemplateTail(match[2] || ""));
|
|
740
1085
|
}));
|
|
741
1086
|
}
|
|
742
1087
|
/**
|
|
1088
|
+
* Emits an IIFE that builds a query string, omitting undefined/null
|
|
1089
|
+
* values and honouring array `explode` / delimiter styles.
|
|
1090
|
+
*/
|
|
1091
|
+
static toQueryStringExpression(parameters, auth) {
|
|
1092
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1093
|
+
const unique = (base) => {
|
|
1094
|
+
let name = base;
|
|
1095
|
+
let suffix = 2;
|
|
1096
|
+
while (taken.has(name)) name = `${base}${suffix++}`;
|
|
1097
|
+
taken.add(name);
|
|
1098
|
+
return name;
|
|
1099
|
+
};
|
|
1100
|
+
const qName = unique("q");
|
|
1101
|
+
const vName = unique("v");
|
|
1102
|
+
const sName = unique("s");
|
|
1103
|
+
const statements = [typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(qName), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("URLSearchParams"), void 0, []))], typescript.NodeFlags.Const))];
|
|
1104
|
+
const append = (name, value) => typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier(qName), typescript.factory.createIdentifier("append")), void 0, [typeof name === "string" ? typescript.factory.createStringLiteral(name) : name, value]));
|
|
1105
|
+
const stringify = (value) => typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [value]);
|
|
1106
|
+
const isNotNull = (value) => typescript.factory.createBinaryExpression(value, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
1107
|
+
for (const parameter of parameters) {
|
|
1108
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1109
|
+
const isArray = parameter.schema?.type === "array";
|
|
1110
|
+
if (parameter.style === "deepObject" && !isArray) {
|
|
1111
|
+
const addName = unique("addDeepObject");
|
|
1112
|
+
const prefix = typescript.factory.createIdentifier("prefix");
|
|
1113
|
+
const value = typescript.factory.createIdentifier("value");
|
|
1114
|
+
const key = typescript.factory.createIdentifier("k");
|
|
1115
|
+
const entry = typescript.factory.createIdentifier("v");
|
|
1116
|
+
const path = typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead(""), [typescript.factory.createTemplateSpan(prefix, typescript.factory.createTemplateMiddle("[")), typescript.factory.createTemplateSpan(key, typescript.factory.createTemplateTail("]"))]);
|
|
1117
|
+
const recurse = typescript.factory.createCallExpression(typescript.factory.createIdentifier(addName), void 0, [path, typescript.factory.createAsExpression(entry, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))]);
|
|
1118
|
+
const forOf = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createArrayBindingPattern([typescript.factory.createBindingElement(void 0, void 0, key), typescript.factory.createBindingElement(void 0, void 0, entry)]))], typescript.NodeFlags.Const), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("Object"), typescript.factory.createIdentifier("entries")), void 0, [value]), typescript.factory.createBlock([typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(entry, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(typescript.factory.createTypeOfExpression(entry), typescript.factory.createToken(typescript.SyntaxKind.EqualsEqualsEqualsToken), typescript.factory.createStringLiteral("object")), typescript.factory.createExpressionStatement(recurse), append(path, stringify(entry)))], true))], true));
|
|
1119
|
+
const declaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(addName), void 0, void 0, typescript.factory.createArrowFunction(void 0, void 0, [typescript.factory.createParameterDeclaration(void 0, void 0, prefix, void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword)), typescript.factory.createParameterDeclaration(void 0, void 0, value, void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock([forOf], true)))], typescript.NodeFlags.Const));
|
|
1120
|
+
const invoke = typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(addName), void 0, [typescript.factory.createStringLiteral(parameter.name), typescript.factory.createAsExpression(id, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]))]));
|
|
1121
|
+
statements.push(parameter.required ? typescript.factory.createBlock([declaration, invoke], true) : typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([declaration, invoke], true)));
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
if (isArray) {
|
|
1125
|
+
if (parameter.explode ?? (parameter.style === void 0 || parameter.style === "form")) {
|
|
1126
|
+
statements.push(typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(vName), void 0, void 0, void 0)], typescript.NodeFlags.Const), typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.QuestionQuestionToken), typescript.factory.createArrayLiteralExpression([])), typescript.factory.createBlock([append(parameter.name, stringify(typescript.factory.createIdentifier(vName)))], true)));
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
const separator = parameter.style === "spaceDelimited" ? " " : parameter.style === "pipeDelimited" ? "|" : ",";
|
|
1130
|
+
const join = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(id, typescript.factory.createIdentifier("join")), void 0, [typescript.factory.createStringLiteral(separator)]);
|
|
1131
|
+
statements.push(typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([append(parameter.name, join)], true)));
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
const statement = append(parameter.name, stringify(id));
|
|
1135
|
+
statements.push(parameter.required ? statement : typescript.factory.createIfStatement(isNotNull(id), typescript.factory.createBlock([statement], true)));
|
|
1136
|
+
}
|
|
1137
|
+
if (auth) for (const injection of auth.injections.filter((item) => item.location === "query")) {
|
|
1138
|
+
const access = authAccess(auth, injection.scheme);
|
|
1139
|
+
statements.push(typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(access, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([append(injection.name, stringify(access))], true)));
|
|
1140
|
+
}
|
|
1141
|
+
statements.push(typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier(sName), void 0, void 0, typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier(qName), typescript.factory.createIdentifier("toString")), void 0, []))], typescript.NodeFlags.Const)), typescript.factory.createReturnStatement(typescript.factory.createConditionalExpression(typescript.factory.createIdentifier(sName), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("?"), [typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(sName), typescript.factory.createTemplateTail(""))]), typescript.factory.createToken(typescript.SyntaxKind.ColonToken), typescript.factory.createStringLiteral(""))));
|
|
1142
|
+
return typescript.factory.createCallExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createArrowFunction(void 0, void 0, [], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock(statements, true))), void 0, []);
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
743
1145
|
* Adds synthetic comments to a TypeScript AST node.
|
|
744
1146
|
*
|
|
745
1147
|
* @param node - The target AST node.
|
|
@@ -749,11 +1151,14 @@ var Generator = class Generator {
|
|
|
749
1151
|
if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
|
|
750
1152
|
const formatComment = (comment) => {
|
|
751
1153
|
if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
|
|
752
|
-
if (comment.tag === "param")
|
|
1154
|
+
if (comment.tag === "param") {
|
|
1155
|
+
const typePart = comment.type ? `{${comment.type}} ` : "";
|
|
1156
|
+
return comment.comment ? `* @param ${typePart}${comment.paramName} - ${comment.comment}` : `* @param ${typePart}${comment.paramName}`;
|
|
1157
|
+
}
|
|
753
1158
|
if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
|
|
754
1159
|
return `* ${comment.comment}`;
|
|
755
1160
|
};
|
|
756
|
-
const formattedComments = comments.map(formatComment).join("\n").trim() + "\n";
|
|
1161
|
+
const formattedComments = comments.map(formatComment).join("\n").replaceAll("*/", "*\\/").trim() + "\n";
|
|
757
1162
|
(0, typescript.addSyntheticLeadingComment)(node, typescript.SyntaxKind.MultiLineCommentTrivia, formattedComments, true);
|
|
758
1163
|
}
|
|
759
1164
|
/**
|
|
@@ -770,6 +1175,16 @@ var Generator = class Generator {
|
|
|
770
1175
|
const nonArraySchema = schema;
|
|
771
1176
|
return nonArraySchema.format === "blob" || nonArraySchema.format === "binary" || nonArraySchema.type === "file";
|
|
772
1177
|
}
|
|
1178
|
+
/** Whether a schema is a primitive text part (not binary, ref, or object). */
|
|
1179
|
+
static isTextSchema(schema) {
|
|
1180
|
+
if (!schema || schema.isRef) return false;
|
|
1181
|
+
if (Generator.isBinarySchema(schema)) return false;
|
|
1182
|
+
if (schema.type === "array") {
|
|
1183
|
+
const items = schema.items;
|
|
1184
|
+
return items ? Generator.isTextSchema(items) : false;
|
|
1185
|
+
}
|
|
1186
|
+
return schema.type === "string" || schema.type === "integer" || schema.type === "number" || schema.type === "boolean";
|
|
1187
|
+
}
|
|
773
1188
|
static schemaToTypeString(schema) {
|
|
774
1189
|
if (schema.type === "array") {
|
|
775
1190
|
const arraySchema = schema;
|
|
@@ -788,15 +1203,16 @@ var Generator = class Generator {
|
|
|
788
1203
|
static generateParamTags(parameters, requestBody) {
|
|
789
1204
|
const tags = [];
|
|
790
1205
|
for (const p of parameters) {
|
|
791
|
-
const paramName = Base.
|
|
1206
|
+
const paramName = Base.toIdentifier(p.name);
|
|
792
1207
|
let paramType = "unknown";
|
|
793
1208
|
if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
|
|
794
1209
|
const isOptional = p.required === false;
|
|
1210
|
+
const inPrefix = p.in ? `[${p.in}] ` : "";
|
|
795
1211
|
tags.push({
|
|
796
1212
|
tag: "param",
|
|
797
1213
|
paramName,
|
|
798
1214
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
799
|
-
comment: p.description ?? ""
|
|
1215
|
+
comment: `${inPrefix}${p.description?.trim() ?? ""}`
|
|
800
1216
|
});
|
|
801
1217
|
}
|
|
802
1218
|
if (requestBody?.schema && "properties" in requestBody.schema) {
|
|
@@ -811,7 +1227,7 @@ var Generator = class Generator {
|
|
|
811
1227
|
tag: "param",
|
|
812
1228
|
paramName,
|
|
813
1229
|
type: `${paramType}${isOptional ? " | undefined" : ""}`,
|
|
814
|
-
comment: schema.description ?? ""
|
|
1230
|
+
comment: schema.description?.trim() ?? ""
|
|
815
1231
|
});
|
|
816
1232
|
}
|
|
817
1233
|
}
|
|
@@ -820,8 +1236,47 @@ var Generator = class Generator {
|
|
|
820
1236
|
static toRequestBodyTypeNode(schema) {
|
|
821
1237
|
return typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("req"), void 0, Generator.toTypeNode(schema));
|
|
822
1238
|
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Narrows a `oneOf` member with its discriminator mapping value:
|
|
1241
|
+
* `Cat & { petType: 'cat' }`.
|
|
1242
|
+
*/
|
|
1243
|
+
static discriminatedMember(schema, discriminator) {
|
|
1244
|
+
const node = Generator.toTypeNode(schema);
|
|
1245
|
+
const ref = schema.ref;
|
|
1246
|
+
if (!ref) return node;
|
|
1247
|
+
const name = Base.ref2name(ref);
|
|
1248
|
+
const value = Object.entries(discriminator.mapping ?? {}).find(([, target]) => Base.ref2name(target) === name)?.[0];
|
|
1249
|
+
if (value === void 0) return node;
|
|
1250
|
+
return typescript.factory.createIntersectionTypeNode([node, typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(discriminator.propertyName), void 0, typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value)))])]);
|
|
1251
|
+
}
|
|
823
1252
|
static toTypeNode(schema) {
|
|
1253
|
+
if ("const" in schema && schema.const !== void 0) return Generator.toLiteralTypeNode(schema.const);
|
|
1254
|
+
const base = Generator.toTypeNodeInner(schema);
|
|
1255
|
+
if (schema.nullable) return typescript.factory.createUnionTypeNode([base, typescript.factory.createLiteralTypeNode(typescript.factory.createNull())]);
|
|
1256
|
+
return base;
|
|
1257
|
+
}
|
|
1258
|
+
static toLiteralTypeNode(value) {
|
|
1259
|
+
if (typeof value === "string") return typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value));
|
|
1260
|
+
if (typeof value === "number") return typescript.factory.createLiteralTypeNode(typescript.factory.createNumericLiteral(value));
|
|
1261
|
+
return typescript.factory.createLiteralTypeNode(value ? typescript.factory.createTrue() : typescript.factory.createFalse());
|
|
1262
|
+
}
|
|
1263
|
+
static primitiveTypeNode(type) {
|
|
1264
|
+
switch (type) {
|
|
1265
|
+
case "string": return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
1266
|
+
case "integer":
|
|
1267
|
+
case "number": return typescript.factory.createToken(typescript.SyntaxKind.NumberKeyword);
|
|
1268
|
+
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
1269
|
+
case "object": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]);
|
|
1270
|
+
default: return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(type)));
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
static toTypeNodeInner(schema) {
|
|
824
1274
|
const { type, ref } = schema;
|
|
1275
|
+
const unionTypes = schema.types;
|
|
1276
|
+
if (unionTypes && unionTypes.length > 0) {
|
|
1277
|
+
const nodes = Generator.deduplicateTypes(unionTypes.map((name) => Generator.primitiveTypeNode(name)));
|
|
1278
|
+
return nodes.length === 1 ? nodes[0] : typescript.factory.createUnionTypeNode(nodes);
|
|
1279
|
+
}
|
|
825
1280
|
if (ref) {
|
|
826
1281
|
const identify = Base.ref2name(ref);
|
|
827
1282
|
return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(identify === "unknown" ? identify : Base.upperCamelCase(identify)));
|
|
@@ -833,19 +1288,28 @@ var Generator = class Generator {
|
|
|
833
1288
|
}
|
|
834
1289
|
case "object": {
|
|
835
1290
|
const propsCount = Object.keys(schema.properties ?? {}).length;
|
|
836
|
-
|
|
1291
|
+
const additional = schema.additionalProperties;
|
|
1292
|
+
const additionalValue = additional && additional !== true ? Generator.toTypeNode(additional) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword);
|
|
1293
|
+
if (!schema.properties || propsCount === 0) return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), additionalValue]);
|
|
837
1294
|
const props = Object.keys(schema.properties);
|
|
838
|
-
|
|
1295
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
1296
|
+
const literal = typescript.factory.createTypeLiteralNode(props.map((propKey) => {
|
|
839
1297
|
const propSchema = schema.properties[propKey];
|
|
840
|
-
return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(propKey),
|
|
1298
|
+
return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(propKey), required.includes(propKey) ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
|
|
841
1299
|
}));
|
|
1300
|
+
const additionalProps = schema.additionalProperties;
|
|
1301
|
+
if (additionalProps === void 0 || additionalProps === false) return literal;
|
|
1302
|
+
return typescript.factory.createIntersectionTypeNode([literal, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), additionalProps === true ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(additionalProps)])]);
|
|
842
1303
|
}
|
|
843
1304
|
case "integer":
|
|
844
1305
|
case "number":
|
|
845
|
-
if (schema.enum)
|
|
1306
|
+
if (schema.enum) {
|
|
1307
|
+
const values = schema.enum.filter((value) => typeof value === "number");
|
|
1308
|
+
if (values.length > 0) return typescript.factory.createUnionTypeNode(values.map((value) => typescript.factory.createLiteralTypeNode(typescript.factory.createNumericLiteral(value))));
|
|
1309
|
+
}
|
|
846
1310
|
return typescript.factory.createToken(typescript.SyntaxKind.NumberKeyword);
|
|
847
1311
|
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
848
|
-
case "file": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Blob"));
|
|
1312
|
+
case "file": return typescript.factory.createTypeReferenceNode(typescript.factory.createQualifiedName(typescript.factory.createIdentifier("globalThis"), typescript.factory.createIdentifier("Blob")));
|
|
849
1313
|
default: {
|
|
850
1314
|
const { format, oneOf, allOf, anyOf, type, enum: enum_ } = schema;
|
|
851
1315
|
switch (format) {
|
|
@@ -853,94 +1317,334 @@ var Generator = class Generator {
|
|
|
853
1317
|
case "string": return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
854
1318
|
case "boolean": return typescript.factory.createToken(typescript.SyntaxKind.BooleanKeyword);
|
|
855
1319
|
case "blob":
|
|
856
|
-
case "binary": return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Blob"));
|
|
857
|
-
|
|
1320
|
+
case "binary": return typescript.factory.createTypeReferenceNode(typescript.factory.createQualifiedName(typescript.factory.createIdentifier("globalThis"), typescript.factory.createIdentifier("Blob")));
|
|
1321
|
+
}
|
|
1322
|
+
if (enum_) {
|
|
1323
|
+
const values = enum_.filter((value) => typeof value === "string");
|
|
1324
|
+
if (values.length > 0) return typescript.factory.createUnionTypeNode(values.map((value) => typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(value))));
|
|
858
1325
|
}
|
|
859
|
-
if (enum_) return typescript.factory.createUnionTypeNode(enum_.map((e) => typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(e))));
|
|
860
1326
|
if (type === "string") return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
|
|
861
|
-
if (oneOf)
|
|
862
|
-
|
|
1327
|
+
if (oneOf) {
|
|
1328
|
+
const discriminator = schema.discriminator;
|
|
1329
|
+
if (discriminator?.mapping) return typescript.factory.createUnionTypeNode(Generator.deduplicateTypes(oneOf.map((member) => Generator.discriminatedMember(member, discriminator))));
|
|
1330
|
+
const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
|
|
1331
|
+
return typescript.factory.createUnionTypeNode(uniqueTypes);
|
|
1332
|
+
}
|
|
1333
|
+
if (anyOf) {
|
|
1334
|
+
const uniqueTypes = Generator.deduplicateTypes(anyOf.map((s) => Generator.toTypeNode(s)));
|
|
1335
|
+
return typescript.factory.createUnionTypeNode(uniqueTypes);
|
|
1336
|
+
}
|
|
863
1337
|
if (allOf) return typescript.factory.createIntersectionTypeNode(allOf.map((schema) => Generator.toTypeNode(schema)));
|
|
864
1338
|
if (type && typeof type === "string") return typescript.factory.createTypeReferenceNode(type !== "unknown" && type !== "null" ? typescript.factory.createIdentifier(Base.upperCamelCase(type)) : type);
|
|
865
1339
|
}
|
|
866
1340
|
}
|
|
867
1341
|
return typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword);
|
|
868
1342
|
}
|
|
1343
|
+
static toResponsesTypeNode(responses) {
|
|
1344
|
+
return typescript.factory.createTypeLiteralNode(Object.entries(responses).map(([code, mediaTypes]) => {
|
|
1345
|
+
const schema = mediaTypes[0]?.schema;
|
|
1346
|
+
return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(code), void 0, schema ? Generator.toTypeNode(schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword));
|
|
1347
|
+
}));
|
|
1348
|
+
}
|
|
1349
|
+
static deduplicateTypes(types) {
|
|
1350
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1351
|
+
const unique = [];
|
|
1352
|
+
for (const type of types) {
|
|
1353
|
+
const key = Generator.getTypeNodeKey(type);
|
|
1354
|
+
if (!seen.has(key)) {
|
|
1355
|
+
seen.add(key);
|
|
1356
|
+
unique.push(type);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
return unique;
|
|
1360
|
+
}
|
|
1361
|
+
static getTypeNodeKey(type) {
|
|
1362
|
+
return JSON.stringify(type);
|
|
1363
|
+
}
|
|
869
1364
|
static toDeclarationNodes(parameters) {
|
|
870
1365
|
const objectElements = [];
|
|
871
1366
|
const typeObjectElements = [];
|
|
872
1367
|
const refParameters = [];
|
|
873
1368
|
for (const parameter of parameters) if (parameter.ref) {
|
|
874
1369
|
const refName = Base.ref2name(parameter.ref);
|
|
875
|
-
refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.
|
|
1370
|
+
refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.toIdentifier(refName)), void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
|
|
876
1371
|
} else {
|
|
877
1372
|
const { name, schema, required } = parameter;
|
|
878
|
-
|
|
879
|
-
|
|
1373
|
+
const key = Base.camelCase(Base.normalize(name));
|
|
1374
|
+
const id = Base.toIdentifier(name);
|
|
1375
|
+
objectElements.push(typescript.factory.createBindingElement(void 0, key === id ? void 0 : typescript.factory.createIdentifier(key), typescript.factory.createIdentifier(id)));
|
|
1376
|
+
typeObjectElements.push(typescript.factory.createPropertySignature([], typescript.factory.createIdentifier(key), required ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), !schema ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
|
|
880
1377
|
}
|
|
881
1378
|
if (objectElements.length > 0) return [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createObjectBindingPattern(objectElements), void 0, typescript.factory.createTypeLiteralNode(typeObjectElements), void 0), ...refParameters];
|
|
882
1379
|
return refParameters;
|
|
883
1380
|
}
|
|
1381
|
+
/** Property keys listed in a parent schema's `required` array. */
|
|
1382
|
+
static requiredPropertyKeys(schema) {
|
|
1383
|
+
return schema && Array.isArray(schema.required) ? schema.required : [];
|
|
1384
|
+
}
|
|
884
1385
|
static toFormDataStatement(parameters, requestBody) {
|
|
885
1386
|
const statements = [];
|
|
1387
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
886
1388
|
const fdDeclaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("fd"), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("FormData"), void 0, []))], typescript.NodeFlags.Const));
|
|
887
1389
|
statements.push(fdDeclaration);
|
|
888
1390
|
parameters.forEach((parameter) => {
|
|
889
|
-
|
|
1391
|
+
const id = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1392
|
+
statements.push(typescript.factory.createExpressionStatement(typescript.factory.createBinaryExpression(id, typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(parameter.name), id]))));
|
|
890
1393
|
});
|
|
891
1394
|
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) Object.keys(requestBody.properties).forEach((key) => {
|
|
892
1395
|
const schemaByKey = requestBody.properties[key];
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
typescript.factory.
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
1396
|
+
const accessor = typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key));
|
|
1397
|
+
if (schemaByKey.type === "array" && Generator.isBinarySchema(schemaByKey)) {
|
|
1398
|
+
const loop = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration("file")], typescript.NodeFlags.Const), accessor, typescript.factory.createBlock([typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), [], [
|
|
1399
|
+
typescript.factory.createStringLiteral(key),
|
|
1400
|
+
typescript.factory.createIdentifier("file"),
|
|
1401
|
+
typescript.factory.createPropertyAccessExpression(typescript.factory.createAsExpression(typescript.factory.createIdentifier("file"), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("File"), void 0)), typescript.factory.createIdentifier("name"))
|
|
1402
|
+
]))]));
|
|
1403
|
+
statements.push(requiredKeys.includes(key) ? loop : typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([loop], true)));
|
|
1404
|
+
} else if (requiredKeys.includes(key)) statements.push(typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))])])));
|
|
899
1405
|
else statements.push(typescript.factory.createExpressionStatement(typescript.factory.createBinaryExpression(typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)), typescript.factory.createToken(typescript.SyntaxKind.AmpersandAmpersandToken), typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("fd"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), schemaByKey.type === "string" || Generator.isBinarySchema(schemaByKey) || schemaByKey.isRef ? typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key)) : schemaByKey.type === "array" || schemaByKey.type === "object" ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key))])]))));
|
|
900
1406
|
});
|
|
901
1407
|
return statements;
|
|
902
1408
|
}
|
|
903
|
-
|
|
904
|
-
|
|
1409
|
+
/**
|
|
1410
|
+
* Build statements that construct a `URLSearchParams` from request body
|
|
1411
|
+
* fields for an `application/x-www-form-urlencoded` request.
|
|
1412
|
+
*
|
|
1413
|
+
* Skips `undefined` / `null` values so optional fields don't end up as
|
|
1414
|
+
* the literal string `"undefined"` in the URL (fixes #8).
|
|
1415
|
+
*
|
|
1416
|
+
* The resulting `sp` variable is referenced by the adapter as the
|
|
1417
|
+
* `body` payload.
|
|
1418
|
+
*/
|
|
1419
|
+
static toURLSearchParamsStatement(parameters, requestBody) {
|
|
1420
|
+
const statements = [];
|
|
1421
|
+
const spDeclaration = typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("sp"), void 0, void 0, typescript.factory.createNewExpression(typescript.factory.createIdentifier("URLSearchParams"), void 0, []))], typescript.NodeFlags.Const));
|
|
1422
|
+
statements.push(spDeclaration);
|
|
1423
|
+
const appendValue = (key, valueExpr) => typescript.factory.createExpressionStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("sp"), typescript.factory.createIdentifier("append")), void 0, [typescript.factory.createStringLiteral(key), valueExpr]));
|
|
1424
|
+
if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) {
|
|
1425
|
+
const requiredKeys = Generator.requiredPropertyKeys(requestBody);
|
|
1426
|
+
for (const key of Object.keys(requestBody.properties)) {
|
|
1427
|
+
const fieldSchema = requestBody.properties[key];
|
|
1428
|
+
const required = requiredKeys.includes(key);
|
|
1429
|
+
const accessor = typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key));
|
|
1430
|
+
const nonNull = typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword));
|
|
1431
|
+
if (fieldSchema.type === "array") {
|
|
1432
|
+
const item = typescript.factory.createIdentifier("item");
|
|
1433
|
+
const loop = typescript.factory.createForOfStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(item)], typescript.NodeFlags.Const), accessor, typescript.factory.createBlock([appendValue(key, Generator.toFormDataCompatibleString(item, fieldSchema.items))], true));
|
|
1434
|
+
statements.push(required ? loop : typescript.factory.createIfStatement(nonNull, typescript.factory.createBlock([loop], true)));
|
|
1435
|
+
continue;
|
|
1436
|
+
}
|
|
1437
|
+
const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
|
|
1438
|
+
statements.push(required ? append : typescript.factory.createIfStatement(nonNull, typescript.factory.createBlock([append], true)));
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
for (const parameter of parameters) {
|
|
1442
|
+
if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
|
|
1443
|
+
const accessor = typescript.factory.createIdentifier(Base.toIdentifier(parameter.name));
|
|
1444
|
+
statements.push(typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([appendValue(parameter.name, Generator.toFormDataCompatibleString(accessor))], true)));
|
|
1445
|
+
}
|
|
1446
|
+
return statements;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Render `expr` as a string suitable for `FormData.append` /
|
|
1450
|
+
* `URLSearchParams.append`. Object/array schemas are JSON-stringified,
|
|
1451
|
+
* everything else is coerced via `String(...)`.
|
|
1452
|
+
*/
|
|
1453
|
+
static toFormDataCompatibleString(expr, schema) {
|
|
1454
|
+
if (schema && (schema.type === "object" || schema.type === "array")) return typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), void 0, [expr]);
|
|
1455
|
+
return typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [expr]);
|
|
1456
|
+
}
|
|
1457
|
+
static bodyBlock(uri, method, parameters, requestBody, response, adapter, errorMode, auth, requestControl) {
|
|
905
1458
|
const shouldParseResponseToJSON = "application/json" === response?.type;
|
|
906
|
-
const isEventStream = response?.type === "text/event-stream";
|
|
907
|
-
const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
|
|
908
1459
|
const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
|
|
909
1460
|
const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
|
|
1461
|
+
const inBody = parametersShouldNotPutInFormData.filter((p) => !p.in || p.in === "body");
|
|
910
1462
|
const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
|
|
911
1463
|
const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
|
|
912
|
-
const
|
|
913
|
-
|
|
1464
|
+
const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
|
|
1465
|
+
const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
|
|
1466
|
+
const multipartParts = requestBody?.schema && "properties" in requestBody.schema && requestBody.schema.properties ? Object.values(requestBody.schema.properties) : [];
|
|
1467
|
+
const hasOnlyTextParts = multipartParts.length > 0 && multipartParts.every((part) => Generator.isTextSchema(part));
|
|
1468
|
+
let bodyKind = "none";
|
|
1469
|
+
let bodyContentType;
|
|
1470
|
+
if (mediaType === "multipart/form-data") {
|
|
1471
|
+
if (hasBinaryInParameters || isRequestBodyContainsBinary || hasOnlyTextParts || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
|
|
1472
|
+
} else if (mediaType === "application/x-www-form-urlencoded") {
|
|
1473
|
+
bodyKind = "urlencoded";
|
|
1474
|
+
bodyContentType = "application/x-www-form-urlencoded";
|
|
1475
|
+
} else if (mediaType === "application/json") {
|
|
1476
|
+
if (requestBody?.schema || inBody.length > 0) {
|
|
1477
|
+
bodyKind = "json";
|
|
1478
|
+
bodyContentType = "application/json";
|
|
1479
|
+
}
|
|
1480
|
+
} else if (requestSchemaIsBinary) {
|
|
1481
|
+
bodyKind = "binary";
|
|
1482
|
+
bodyContentType = requestBody?.type;
|
|
1483
|
+
} else if (requestBody?.schema) {
|
|
1484
|
+
bodyKind = "json";
|
|
1485
|
+
bodyContentType = requestBody?.type;
|
|
1486
|
+
}
|
|
1487
|
+
const preStatements = [];
|
|
1488
|
+
if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
|
|
1489
|
+
else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
|
|
1490
|
+
return typescript.factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON, errorMode, auth, requestControl)]);
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Resolves effective security requirements into concrete injections.
|
|
1494
|
+
* Requirements are OR-ed by the spec; we inject every credential the
|
|
1495
|
+
* caller provides, so either branch of an OR works.
|
|
1496
|
+
*/
|
|
1497
|
+
static toAuthInjections(security, schemes) {
|
|
1498
|
+
const injections = [];
|
|
1499
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1500
|
+
for (const requirement of security ?? []) for (const schemeName of Object.keys(requirement)) {
|
|
1501
|
+
const scheme = schemes[schemeName];
|
|
1502
|
+
if (!scheme) continue;
|
|
1503
|
+
let injection;
|
|
1504
|
+
if (scheme.type === "apiKey" && scheme.in && scheme.name) injection = {
|
|
1505
|
+
scheme: schemeName,
|
|
1506
|
+
location: scheme.in,
|
|
1507
|
+
name: scheme.name,
|
|
1508
|
+
kind: "raw"
|
|
1509
|
+
};
|
|
1510
|
+
else if (scheme.type === "http") injection = {
|
|
1511
|
+
scheme: schemeName,
|
|
1512
|
+
location: "header",
|
|
1513
|
+
name: "Authorization",
|
|
1514
|
+
kind: scheme.scheme === "basic" ? "basic" : "bearer"
|
|
1515
|
+
};
|
|
1516
|
+
else if (scheme.type === "basic" || scheme.type === "oauth2" || scheme.type === "openIdConnect") injection = {
|
|
1517
|
+
scheme: schemeName,
|
|
1518
|
+
location: "header",
|
|
1519
|
+
name: "Authorization",
|
|
1520
|
+
kind: scheme.type === "basic" ? "basic" : "bearer"
|
|
1521
|
+
};
|
|
1522
|
+
if (!injection) continue;
|
|
1523
|
+
const key = `${injection.location}:${injection.name}`;
|
|
1524
|
+
if (seen.has(key)) continue;
|
|
1525
|
+
seen.add(key);
|
|
1526
|
+
injections.push(injection);
|
|
1527
|
+
}
|
|
1528
|
+
return injections;
|
|
1529
|
+
}
|
|
1530
|
+
/** `{ [scheme: string]: string | { username: string; password: string } }` */
|
|
1531
|
+
static authOptionsTypeNode() {
|
|
1532
|
+
return typescript.factory.createTypeLiteralNode([typescript.factory.createIndexSignature(void 0, [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("scheme"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword))], typescript.factory.createUnionTypeNode([typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("username"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword)), typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("password"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword))])]))]);
|
|
1533
|
+
}
|
|
1534
|
+
/** `{ signal?: AbortSignal; headers?: Record<string, string>; timeout?: number }` */
|
|
1535
|
+
static requestOptionsTypeNode() {
|
|
1536
|
+
const stringType = typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.StringKeyword);
|
|
1537
|
+
return typescript.factory.createTypeLiteralNode([
|
|
1538
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("signal"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("AbortSignal"))),
|
|
1539
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("headers"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [stringType, stringType])),
|
|
1540
|
+
typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("timeout"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.NumberKeyword))
|
|
1541
|
+
]);
|
|
914
1542
|
}
|
|
915
1543
|
static schemaToStatemets(parsedDoc, adaptor, options) {
|
|
916
1544
|
const statements = [];
|
|
917
|
-
const { apis, schemas = {}, enums } = parsedDoc;
|
|
1545
|
+
const { apis, schemas = {}, enums, securitySchemes = {} } = parsedDoc;
|
|
918
1546
|
const enumNames = [];
|
|
919
1547
|
for (const enumObject of enums) {
|
|
920
1548
|
enumNames.push(Base.upperCamelCase(enumObject.name));
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1549
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1550
|
+
const members = enumObject.enum.filter((member) => typeof member === "string" || typeof member === "number").map((member, index) => {
|
|
1551
|
+
let key = typeof member === "string" && !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(member) ? member : `Value_${String(member).replace(/[^A-Za-z0-9]/g, "_")}`;
|
|
1552
|
+
if (usedKeys.has(key)) key = `${key}_${index}`;
|
|
1553
|
+
usedKeys.add(key);
|
|
1554
|
+
return typescript.factory.createEnumMember(typescript.factory.createStringLiteral(key), typeof member === "string" ? typescript.factory.createStringLiteral(member) : typescript.factory.createNumericLiteral(member));
|
|
1555
|
+
});
|
|
1556
|
+
statements.push(typescript.factory.createEnumDeclaration([typescript.factory.createToken(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(enumObject.name)), members));
|
|
924
1557
|
}
|
|
925
1558
|
for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
|
|
926
1559
|
const schema = schemas[schemaKey];
|
|
927
1560
|
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
|
|
928
1561
|
}
|
|
1562
|
+
const reserveUnique = createUniqueNameResolver();
|
|
1563
|
+
let authTypeName;
|
|
1564
|
+
let requestOptionsTypeName;
|
|
929
1565
|
for (const uri in apis) {
|
|
930
1566
|
const operations = apis[uri];
|
|
931
1567
|
for (const operation of operations) {
|
|
932
1568
|
const { method, operationId, requestBody = [], responses = [], summary, deprecated, description } = operation;
|
|
933
|
-
|
|
934
|
-
|
|
1569
|
+
const { parameters = [] } = operation;
|
|
1570
|
+
const authInjections = Generator.toAuthInjections(operation.security, securitySchemes);
|
|
1571
|
+
let authArgument;
|
|
1572
|
+
let authTypeReference;
|
|
1573
|
+
if (authInjections.length > 0) {
|
|
1574
|
+
const typeName = authTypeName ?? (() => {
|
|
1575
|
+
let candidate = "AuthOptions";
|
|
1576
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1577
|
+
return candidate;
|
|
1578
|
+
})();
|
|
1579
|
+
if (!authTypeName) {
|
|
1580
|
+
authTypeName = typeName;
|
|
1581
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(typeName), void 0, Generator.authOptionsTypeNode()));
|
|
1582
|
+
}
|
|
1583
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1584
|
+
taken.add("req");
|
|
1585
|
+
let name = "auth";
|
|
1586
|
+
let suffix = 2;
|
|
1587
|
+
while (taken.has(name)) {
|
|
1588
|
+
name = `auth${suffix}`;
|
|
1589
|
+
suffix++;
|
|
1590
|
+
}
|
|
1591
|
+
authArgument = {
|
|
1592
|
+
name,
|
|
1593
|
+
injections: authInjections
|
|
1594
|
+
};
|
|
1595
|
+
authTypeReference = typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(typeName));
|
|
1596
|
+
}
|
|
1597
|
+
const optionsTypeName = requestOptionsTypeName ?? (() => {
|
|
1598
|
+
let candidate = "RequestOptions";
|
|
1599
|
+
while (Object.keys(schemas).some((key) => Base.upperCamelCase(key) === candidate) || enumNames.includes(candidate)) candidate += "2";
|
|
1600
|
+
return candidate;
|
|
1601
|
+
})();
|
|
1602
|
+
if (!requestOptionsTypeName) {
|
|
1603
|
+
requestOptionsTypeName = optionsTypeName;
|
|
1604
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(optionsTypeName), void 0, Generator.requestOptionsTypeNode()));
|
|
1605
|
+
}
|
|
1606
|
+
const taken = new Set(parameters.map((p) => Base.toIdentifier(p.name)));
|
|
1607
|
+
taken.add("req");
|
|
1608
|
+
if (authArgument) taken.add(authArgument.name);
|
|
1609
|
+
let requestControlName = "options";
|
|
1610
|
+
let requestControlSuffix = 2;
|
|
1611
|
+
while (taken.has(requestControlName)) {
|
|
1612
|
+
requestControlName = `options${requestControlSuffix}`;
|
|
1613
|
+
requestControlSuffix++;
|
|
1614
|
+
}
|
|
1615
|
+
const requestControl = { name: requestControlName };
|
|
935
1616
|
if (requestBody.length === 0) requestBody.push({ type: "application/json" });
|
|
1617
|
+
const { responseTypes } = operation;
|
|
1618
|
+
const responseCodes = Object.keys(responseTypes ?? {});
|
|
1619
|
+
if (responseTypes && (responseCodes.length > 1 || !/^2\d\d$/.test(responseCodes[0] ?? ""))) {
|
|
1620
|
+
const responsesName = reserveUnique(`${Base.pathToFnName(uri, method, operationId)}Responses`);
|
|
1621
|
+
statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(responsesName), void 0, Generator.toResponsesTypeNode(responseTypes)));
|
|
1622
|
+
}
|
|
936
1623
|
const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
|
|
937
1624
|
for (const req of requestBody) {
|
|
938
|
-
const statement = typescript.factory.createFunctionDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword), typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], void 0, Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.
|
|
939
|
-
|
|
1625
|
+
const statement = typescript.factory.createFunctionDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword), typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], void 0, reserveUnique(Base.pathToFnName(uri, method, operationId) + (shouldAddExtraMethodNameSuffix ? Base.mediaTypeToSuffix(req.type) : "")), void 0, [
|
|
1626
|
+
...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [],
|
|
1627
|
+
...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : [],
|
|
1628
|
+
...authArgument && authTypeReference ? [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(authArgument.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), authTypeReference)] : [],
|
|
1629
|
+
typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(requestControl.name), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(optionsTypeName)))
|
|
1630
|
+
].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor, options.errorMode, authArgument, requestControl));
|
|
1631
|
+
const mergedDescription = [description, summary].filter(Boolean).map((part) => part?.trim()).join(". ");
|
|
940
1632
|
Generator.addComments(statement, [
|
|
941
1633
|
mergedDescription && { comment: mergedDescription },
|
|
942
1634
|
deprecated && { tag: "deprecated" },
|
|
943
|
-
...Generator.generateParamTags(parameters, req)
|
|
1635
|
+
...Generator.generateParamTags(parameters, req),
|
|
1636
|
+
...authArgument ? [{
|
|
1637
|
+
tag: "param",
|
|
1638
|
+
paramName: authArgument.name,
|
|
1639
|
+
type: "AuthOptions",
|
|
1640
|
+
comment: "Optional security credentials, keyed by scheme name"
|
|
1641
|
+
}] : [],
|
|
1642
|
+
{
|
|
1643
|
+
tag: "param",
|
|
1644
|
+
paramName: requestControl.name,
|
|
1645
|
+
type: optionsTypeName,
|
|
1646
|
+
comment: "Optional abort signal, extra headers and timeout"
|
|
1647
|
+
}
|
|
944
1648
|
].filter(Boolean));
|
|
945
1649
|
statements.push(statement);
|
|
946
1650
|
}
|
|
@@ -951,19 +1655,79 @@ var Generator = class Generator {
|
|
|
951
1655
|
static async prettier(code) {
|
|
952
1656
|
return await (0, prettier.format)(code, { parser: "typescript" });
|
|
953
1657
|
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Splits generated code into `types.ts`, one file per tag, and `index.ts`.
|
|
1660
|
+
* Shared type declarations live in `types.ts`; tag files import them and
|
|
1661
|
+
* export only their functions.
|
|
1662
|
+
*/
|
|
1663
|
+
static async genCodeMulti(schema, initOptions, adaptor) {
|
|
1664
|
+
const genOptions = {
|
|
1665
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1666
|
+
errorMode: initOptions.errorMode === "throw" || initOptions.errorMode === "result" ? initOptions.errorMode : void 0
|
|
1667
|
+
};
|
|
1668
|
+
const isTypeDeclaration = (statement) => (0, typescript.isEnumDeclaration)(statement) || (0, typescript.isTypeAliasDeclaration)(statement) || (0, typescript.isInterfaceDeclaration)(statement);
|
|
1669
|
+
const typeStatements = Generator.schemaToStatemets(schema, adaptor, genOptions).filter(isTypeDeclaration);
|
|
1670
|
+
const typeNames = typeStatements.map((statement) => (0, typescript.isEnumDeclaration)(statement) || (0, typescript.isTypeAliasDeclaration)(statement) || (0, typescript.isInterfaceDeclaration)(statement) ? statement.name.text : void 0).filter((name) => Boolean(name));
|
|
1671
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1672
|
+
for (const [uri, operations] of Object.entries(schema.apis)) for (const operation of operations) {
|
|
1673
|
+
const tag = operation.tags?.[0] ?? "default";
|
|
1674
|
+
const apis = groups.get(tag) ?? {};
|
|
1675
|
+
apis[uri] ??= [];
|
|
1676
|
+
apis[uri].push(operation);
|
|
1677
|
+
groups.set(tag, apis);
|
|
1678
|
+
}
|
|
1679
|
+
const files = {};
|
|
1680
|
+
const used = /* @__PURE__ */ new Set(["index", "types"]);
|
|
1681
|
+
files["types.ts"] = await Generator.prettier(Generator.toCode(typeStatements));
|
|
1682
|
+
const exportLines = ["export * from './types.js';"];
|
|
1683
|
+
for (const [tag, apis] of groups) {
|
|
1684
|
+
const tagStatements = Generator.schemaToStatemets({
|
|
1685
|
+
...schema,
|
|
1686
|
+
apis
|
|
1687
|
+
}, adaptor, genOptions).filter((statement) => !isTypeDeclaration(statement));
|
|
1688
|
+
const nodes = [];
|
|
1689
|
+
if (typeNames.length > 0) nodes.push(typescript.factory.createImportDeclaration(void 0, typescript.factory.createImportClause(true, void 0, typescript.factory.createNamedImports(typeNames.map((name) => typescript.factory.createImportSpecifier(false, void 0, typescript.factory.createIdentifier(name))))), typescript.factory.createStringLiteral("./types.js")));
|
|
1690
|
+
nodes.push(...tagStatements);
|
|
1691
|
+
let code = Generator.toCode(nodes);
|
|
1692
|
+
if (initOptions.importClientSource) code = initOptions.importClientSource + "\n\n" + code;
|
|
1693
|
+
const fileName = Generator.uniqueFileName(tag, used);
|
|
1694
|
+
files[`${fileName}.ts`] = await Generator.prettier(code);
|
|
1695
|
+
exportLines.push(`export * from './${fileName}.js';`);
|
|
1696
|
+
}
|
|
1697
|
+
const index = await Generator.prettier(exportLines.join("\n"));
|
|
1698
|
+
files["index.ts"] = index;
|
|
1699
|
+
return {
|
|
1700
|
+
code: index,
|
|
1701
|
+
files
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
/** Lower-case file stem that cannot collide with reserved or earlier names. */
|
|
1705
|
+
static uniqueFileName(tag, used) {
|
|
1706
|
+
const base = tag.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "default";
|
|
1707
|
+
let name = base;
|
|
1708
|
+
let suffix = 2;
|
|
1709
|
+
while (used.has(name)) {
|
|
1710
|
+
name = `${base}-${suffix}`;
|
|
1711
|
+
suffix++;
|
|
1712
|
+
}
|
|
1713
|
+
used.add(name);
|
|
1714
|
+
return name;
|
|
1715
|
+
}
|
|
954
1716
|
static async genCode(schema, initOptions, adaptor) {
|
|
955
|
-
const { importClientSource } = initOptions;
|
|
956
|
-
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1717
|
+
const { importClientSource, errorMode } = initOptions;
|
|
1718
|
+
const statements = Generator.schemaToStatemets(schema, adaptor, {
|
|
1719
|
+
baseURL: initOptions.baseURL ?? "",
|
|
1720
|
+
errorMode: errorMode === "throw" || errorMode === "result" ? errorMode : void 0
|
|
1721
|
+
});
|
|
957
1722
|
let code = Generator.toCode(statements);
|
|
958
1723
|
if (importClientSource) code = importClientSource + "\n\n" + code;
|
|
959
1724
|
return await Generator.prettier(code);
|
|
960
1725
|
}
|
|
961
1726
|
};
|
|
962
|
-
|
|
963
|
-
//#region src/core/client/axios.ts
|
|
1727
|
+
// src/core/client/axios.ts
|
|
964
1728
|
/**
|
|
965
1729
|
* Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
|
|
966
|
-
* This
|
|
1730
|
+
* This adapter defines custom behavior and field mappings specific to the Axios client.
|
|
967
1731
|
*/
|
|
968
1732
|
var AxiosAdapter = class extends Adapter {
|
|
969
1733
|
/**
|
|
@@ -987,40 +1751,59 @@ var AxiosAdapter = class extends Adapter {
|
|
|
987
1751
|
*/
|
|
988
1752
|
name = "axios";
|
|
989
1753
|
/**
|
|
990
|
-
*
|
|
991
|
-
*
|
|
992
|
-
* @
|
|
993
|
-
* @param parameters - Array of parameters to include in the request
|
|
994
|
-
* @param requestBody - The request body media type definition
|
|
995
|
-
* @param response - The response media type definition
|
|
996
|
-
* @param adapter - The adapter instance
|
|
997
|
-
* @param shouldUseFormData - Flag to use FormData for the request body
|
|
998
|
-
* @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
|
|
999
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
|
|
1000
|
-
* @return - An array of generated TypeScript statements
|
|
1754
|
+
* Method that should generate and return the client-specific configuration statements.
|
|
1755
|
+
*
|
|
1756
|
+
* @returns {Statement[]} An array of TypeScript statements that define the client configuration.
|
|
1001
1757
|
*/
|
|
1002
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1758
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1003
1759
|
const statements = [];
|
|
1004
|
-
|
|
1760
|
+
parameters.filter((p) => !p.in || p.in === "body");
|
|
1005
1761
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1762
|
+
const toLiterlExpression = () => {
|
|
1763
|
+
const headerEntries = [];
|
|
1764
|
+
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1765
|
+
if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
|
|
1766
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1767
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1768
|
+
const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
|
|
1769
|
+
if (headerEntries.length > 0 || requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1770
|
+
if (requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("signal"), optionalAccess(requestControl, "signal")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("timeout"), optionalAccess(requestControl, "timeout")));
|
|
1771
|
+
let bodyExpr;
|
|
1772
|
+
switch (bodyKind) {
|
|
1773
|
+
case "form-data":
|
|
1774
|
+
bodyExpr = typescript.factory.createIdentifier("fd");
|
|
1775
|
+
break;
|
|
1776
|
+
case "urlencoded":
|
|
1777
|
+
bodyExpr = typescript.factory.createIdentifier("sp");
|
|
1778
|
+
break;
|
|
1779
|
+
case "json":
|
|
1780
|
+
case "binary": bodyExpr = typescript.factory.createIdentifier("req");
|
|
1781
|
+
}
|
|
1782
|
+
if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1783
|
+
return typescript.factory.createObjectLiteralExpression(properties, true);
|
|
1013
1784
|
};
|
|
1014
|
-
|
|
1015
|
-
|
|
1785
|
+
const axiosCall = typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : [typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("unknown"))], [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1786
|
+
if (errorMode !== "result") {
|
|
1787
|
+
statements.push(typescript.factory.createReturnStatement(axiosCall));
|
|
1016
1788
|
return statements;
|
|
1017
1789
|
}
|
|
1018
|
-
|
|
1790
|
+
const prop = (name, value) => typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(name), value);
|
|
1791
|
+
const resProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("res"), typescript.factory.createIdentifier(name));
|
|
1792
|
+
const errorProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("failure"), typescript.factory.createIdentifier("response")), typescript.factory.createIdentifier(name));
|
|
1793
|
+
const result = (ok, key, value) => typescript.factory.createObjectLiteralExpression([
|
|
1794
|
+
prop("ok", typescript.factory.createAsExpression(ok ? typescript.factory.createTrue() : typescript.factory.createFalse(), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("const")))),
|
|
1795
|
+
prop("status", ok ? resProp("status") : errorProp("status")),
|
|
1796
|
+
prop(key, value)
|
|
1797
|
+
], true);
|
|
1798
|
+
statements.push(typescript.factory.createTryStatement(typescript.factory.createBlock([typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("res"), void 0, void 0, typescript.factory.createAwaitExpression(axiosCall))], typescript.NodeFlags.Const)), typescript.factory.createReturnStatement(result(true, "data", resProp("data")))], true), typescript.factory.createCatchClause(typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("err")), typescript.factory.createBlock([
|
|
1799
|
+
typescript.factory.createVariableStatement(void 0, typescript.factory.createVariableDeclarationList([typescript.factory.createVariableDeclaration(typescript.factory.createIdentifier("failure"), void 0, void 0, typescript.factory.createAsExpression(typescript.factory.createIdentifier("err"), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("response"), typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), typescript.factory.createTypeLiteralNode([typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("status"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.NumberKeyword)), typescript.factory.createPropertySignature(void 0, typescript.factory.createIdentifier("data"), void 0, typescript.factory.createKeywordTypeNode(typescript.SyntaxKind.UnknownKeyword))]))])))], typescript.NodeFlags.Const)),
|
|
1800
|
+
typescript.factory.createIfStatement(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("failure"), typescript.factory.createIdentifier("response")), typescript.factory.createBlock([typescript.factory.createReturnStatement(result(false, "error", errorProp("data")))], true)),
|
|
1801
|
+
typescript.factory.createThrowStatement(typescript.factory.createIdentifier("err"))
|
|
1802
|
+
], true)), void 0));
|
|
1019
1803
|
return statements;
|
|
1020
1804
|
}
|
|
1021
1805
|
};
|
|
1022
|
-
|
|
1023
|
-
//#region src/core/client/fetch.ts
|
|
1806
|
+
// src/core/client/fetch.ts
|
|
1024
1807
|
/**
|
|
1025
1808
|
* FetchAdapter is an adapter class that generates client-side fetch requests.
|
|
1026
1809
|
* It handles parameters, headers, and request bodies to construct proper fetch calls.
|
|
@@ -1039,12 +1822,12 @@ var FetchAdapter = class extends Adapter {
|
|
|
1039
1822
|
* @param requestBody - The request body media type definition
|
|
1040
1823
|
* @param response - The response media type definition
|
|
1041
1824
|
* @param adapter - The adapter instance
|
|
1042
|
-
* @param
|
|
1825
|
+
* @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
|
|
1826
|
+
* @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
|
|
1043
1827
|
* @param shouldUseJSONResponse - Flag to use JSON parsing for the response
|
|
1044
|
-
* @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
|
|
1045
1828
|
* @return - An array of generated TypeScript statements
|
|
1046
1829
|
*/
|
|
1047
|
-
client(uri, method, parameters, requestBody, response, adapter,
|
|
1830
|
+
client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse, errorMode, auth, requestControl) {
|
|
1048
1831
|
const statements = [];
|
|
1049
1832
|
const inBody = parameters.filter((p) => !p.in || p.in === "body");
|
|
1050
1833
|
const inHeader = parameters.filter((p) => p.in === "header");
|
|
@@ -1054,18 +1837,67 @@ var FetchAdapter = class extends Adapter {
|
|
|
1054
1837
|
* @returns - The constructed fetch options object
|
|
1055
1838
|
*/
|
|
1056
1839
|
const toLiterlExpression = () => {
|
|
1057
|
-
|
|
1840
|
+
const headerEntries = [];
|
|
1841
|
+
for (const p of inHeader) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.toIdentifier(p.name))])])));
|
|
1842
|
+
if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
|
|
1843
|
+
if (parameters.some((p) => p.in === "cookie") || auth?.injections.some((injection) => injection.location === "cookie")) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Cookie"), cookieHeaderExpression(parameters, auth)));
|
|
1844
|
+
if (auth) headerEntries.push(...authHeaderEntries(auth));
|
|
1845
|
+
const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
|
|
1846
|
+
if (headerEntries.length > 0 || requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(withRequestHeaders(headerEntries, requestControl))));
|
|
1847
|
+
if (requestControl) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("signal"), fetchSignalExpression(requestControl)));
|
|
1848
|
+
let bodyExpr;
|
|
1849
|
+
switch (bodyKind) {
|
|
1850
|
+
case "form-data":
|
|
1851
|
+
bodyExpr = typescript.factory.createIdentifier("fd");
|
|
1852
|
+
break;
|
|
1853
|
+
case "urlencoded":
|
|
1854
|
+
bodyExpr = typescript.factory.createIdentifier("sp");
|
|
1855
|
+
break;
|
|
1856
|
+
case "json": {
|
|
1857
|
+
const arg = requestBody ? typescript.factory.createIdentifier("req") : typescript.factory.createObjectLiteralExpression(inBody.map((b) => typescript.factory.createShorthandPropertyAssignment(typescript.factory.createIdentifier(b.name))), true);
|
|
1858
|
+
bodyExpr = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), [], [arg]);
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
case "binary": bodyExpr = typescript.factory.createIdentifier("req");
|
|
1862
|
+
}
|
|
1863
|
+
if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
|
|
1864
|
+
return typescript.factory.createObjectLiteralExpression(properties, true);
|
|
1058
1865
|
};
|
|
1059
|
-
|
|
1060
|
-
|
|
1866
|
+
const fetchCall = typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters, "", auth), toLiterlExpression()]);
|
|
1867
|
+
const responseProp = (name) => typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier(name));
|
|
1868
|
+
const jsonExpression = typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(responseProp("json"), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword));
|
|
1869
|
+
const successExpression = shouldUseJSONResponse ? jsonExpression : typescript.factory.createIdentifier("response");
|
|
1870
|
+
if (!errorMode) {
|
|
1871
|
+
statements.push(typescript.factory.createReturnStatement(shouldUseJSONResponse ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(fetchCall, typescript.factory.createIdentifier("then")), void 0, [typescript.factory.createArrowFunction([typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], [], [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("response"))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), jsonExpression)]) : fetchCall));
|
|
1061
1872
|
return statements;
|
|
1062
1873
|
}
|
|
1063
|
-
|
|
1874
|
+
const notOk = typescript.factory.createPrefixUnaryExpression(typescript.SyntaxKind.ExclamationToken, responseProp("ok"));
|
|
1875
|
+
const responseText = typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(responseProp("text"), void 0, []));
|
|
1876
|
+
const thenStatements = [];
|
|
1877
|
+
if (errorMode === "throw") thenStatements.push(typescript.factory.createIfStatement(notOk, typescript.factory.createBlock([typescript.factory.createThrowStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("Object"), typescript.factory.createIdentifier("assign")), void 0, [typescript.factory.createNewExpression(typescript.factory.createIdentifier("Error"), void 0, [typescript.factory.createTemplateExpression(typescript.factory.createTemplateHead("HTTP "), [typescript.factory.createTemplateSpan(responseProp("status"), typescript.factory.createTemplateTail(""))])]), typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("status"), responseProp("status")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("body"), responseText)], true)]))], true)), typescript.factory.createReturnStatement(successExpression));
|
|
1878
|
+
else {
|
|
1879
|
+
const result = (ok, key, value) => typescript.factory.createObjectLiteralExpression([
|
|
1880
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("ok"), typescript.factory.createAsExpression(ok ? typescript.factory.createTrue() : typescript.factory.createFalse(), typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("const")))),
|
|
1881
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("status"), responseProp("status")),
|
|
1882
|
+
typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(key), value)
|
|
1883
|
+
], true);
|
|
1884
|
+
thenStatements.push(typescript.factory.createIfStatement(notOk, typescript.factory.createBlock([typescript.factory.createReturnStatement(result(false, "error", responseText))], true)), typescript.factory.createReturnStatement(result(true, "data", successExpression)));
|
|
1885
|
+
}
|
|
1886
|
+
statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(fetchCall, typescript.factory.createIdentifier("then")), void 0, [typescript.factory.createArrowFunction([typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], [], [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("response"))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), typescript.factory.createBlock(thenStatements, true))])));
|
|
1064
1887
|
return statements;
|
|
1065
1888
|
}
|
|
1066
1889
|
};
|
|
1067
|
-
|
|
1068
|
-
|
|
1890
|
+
// src/core/config.ts
|
|
1891
|
+
/**
|
|
1892
|
+
* Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
|
|
1893
|
+
*/
|
|
1894
|
+
const TRUTHY_STRINGS = /* @__PURE__ */ new Set([
|
|
1895
|
+
"true",
|
|
1896
|
+
"1",
|
|
1897
|
+
"yes",
|
|
1898
|
+
"on",
|
|
1899
|
+
"enable"
|
|
1900
|
+
]);
|
|
1069
1901
|
/**
|
|
1070
1902
|
* Environment variable mappings
|
|
1071
1903
|
*/
|
|
@@ -1076,7 +1908,10 @@ const ENV_MAPPINGS = {
|
|
|
1076
1908
|
APICODEGEN_ADAPTOR: "adaptor",
|
|
1077
1909
|
APICODEGEN_VERBOSE: "verbose",
|
|
1078
1910
|
APICODEGEN_WATCH: "watch",
|
|
1079
|
-
APICODEGEN_TYPE_CHECK: "typeCheck"
|
|
1911
|
+
APICODEGEN_TYPE_CHECK: "typeCheck",
|
|
1912
|
+
APICODEGEN_CHECK: "check",
|
|
1913
|
+
APICODEGEN_ERROR_MODE: "errorMode",
|
|
1914
|
+
APICODEGEN_SPLIT_BY: "splitBy"
|
|
1080
1915
|
};
|
|
1081
1916
|
/**
|
|
1082
1917
|
* Load config from environment variables
|
|
@@ -1089,19 +1924,23 @@ function loadFromEnv() {
|
|
|
1089
1924
|
case "verbose":
|
|
1090
1925
|
case "watch":
|
|
1091
1926
|
case "typeCheck":
|
|
1092
|
-
|
|
1927
|
+
case "check":
|
|
1928
|
+
config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
|
|
1093
1929
|
break;
|
|
1094
1930
|
case "adaptor":
|
|
1095
|
-
config[configKey] = value;
|
|
1931
|
+
if (Object.values(Adaptors).includes(value)) config[configKey] = value;
|
|
1932
|
+
break;
|
|
1933
|
+
case "errorMode":
|
|
1934
|
+
if (value === "throw" || value === "result") config.errorMode = value;
|
|
1935
|
+
break;
|
|
1936
|
+
case "splitBy":
|
|
1937
|
+
if (value === "tag") config.splitBy = value;
|
|
1096
1938
|
break;
|
|
1097
1939
|
default: config[configKey] = value;
|
|
1098
1940
|
}
|
|
1099
1941
|
}
|
|
1100
1942
|
return config;
|
|
1101
1943
|
}
|
|
1102
|
-
/**
|
|
1103
|
-
* Load config from a file
|
|
1104
|
-
*/
|
|
1105
1944
|
async function loadFromFile(filePath) {
|
|
1106
1945
|
const ext = node_path.default.extname(filePath).toLowerCase();
|
|
1107
1946
|
try {
|
|
@@ -1110,17 +1949,16 @@ async function loadFromFile(filePath) {
|
|
|
1110
1949
|
return JSON.parse(content);
|
|
1111
1950
|
}
|
|
1112
1951
|
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
|
|
1113
|
-
const mod = await import(filePath);
|
|
1952
|
+
const mod = await import((0, node_url.pathToFileURL)(filePath).href);
|
|
1114
1953
|
return mod.default || mod;
|
|
1115
1954
|
}
|
|
1116
|
-
if (ext === ".ts") {
|
|
1955
|
+
if (ext === ".ts" || ext === ".mts" || ext === ".cts") {
|
|
1117
1956
|
const content = await fs_extra.default.readFile(filePath, "utf-8");
|
|
1118
1957
|
try {
|
|
1119
1958
|
return JSON.parse(content);
|
|
1120
|
-
} catch {
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
}
|
|
1959
|
+
} catch {}
|
|
1960
|
+
const mod = await import((0, node_url.pathToFileURL)(filePath).href);
|
|
1961
|
+
return mod.default || mod;
|
|
1124
1962
|
}
|
|
1125
1963
|
const content = await fs_extra.default.readFile(filePath, "utf-8");
|
|
1126
1964
|
return JSON.parse(content);
|
|
@@ -1136,10 +1974,13 @@ async function findConfigFile(cwd) {
|
|
|
1136
1974
|
"apicodegen.config.json",
|
|
1137
1975
|
"apicodegen.config.js",
|
|
1138
1976
|
"apicodegen.config.mjs",
|
|
1977
|
+
"apicodegen.config.ts",
|
|
1978
|
+
"apicodegen.config.mts",
|
|
1139
1979
|
".apicodegenrc",
|
|
1140
1980
|
".apicodegenrc.json",
|
|
1141
1981
|
".apicodegenrc.js",
|
|
1142
|
-
".apicodegenrc.mjs"
|
|
1982
|
+
".apicodegenrc.mjs",
|
|
1983
|
+
".apicodegenrc.ts"
|
|
1143
1984
|
]) {
|
|
1144
1985
|
const filePath = node_path.default.join(cwd, fileName);
|
|
1145
1986
|
if (await fs_extra.default.pathExists(filePath)) return filePath;
|
|
@@ -1159,11 +2000,40 @@ function mergeConfigs(base, ...sources) {
|
|
|
1159
2000
|
const result = { ...base };
|
|
1160
2001
|
for (const source of sources) {
|
|
1161
2002
|
if (!source) continue;
|
|
1162
|
-
for (const [key, value] of Object.entries(source)) if (value !== void 0) result[key] = value;
|
|
2003
|
+
for (const [key, value] of Object.entries(source)) if (value !== void 0 && value !== null) result[key] = value;
|
|
1163
2004
|
}
|
|
1164
2005
|
return result;
|
|
1165
2006
|
}
|
|
1166
2007
|
/**
|
|
2008
|
+
* Validate field types before the values reach the generator.
|
|
2009
|
+
*/
|
|
2010
|
+
function validateConfigShape(config) {
|
|
2011
|
+
const fail = (key, expected) => {
|
|
2012
|
+
throw new Error(`Invalid config field "${key}": expected ${expected}`);
|
|
2013
|
+
};
|
|
2014
|
+
if (config.spec !== void 0 && typeof config.spec !== "string") fail("spec", "a string");
|
|
2015
|
+
if (config.output !== void 0 && typeof config.output !== "string") fail("output", "a string");
|
|
2016
|
+
for (const key of [
|
|
2017
|
+
"verbose",
|
|
2018
|
+
"watch",
|
|
2019
|
+
"typeCheck",
|
|
2020
|
+
"check"
|
|
2021
|
+
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") fail(key, "a boolean");
|
|
2022
|
+
if (config.adaptor !== void 0 && !Object.values(Adaptors).includes(config.adaptor)) fail("adaptor", Object.values(Adaptors).join(" or "));
|
|
2023
|
+
if (config.errorMode !== void 0 && config.errorMode !== "throw" && config.errorMode !== "result") fail("errorMode", "throw or result");
|
|
2024
|
+
if (config.splitBy !== void 0 && config.splitBy !== "tag") fail("splitBy", "tag");
|
|
2025
|
+
for (const key of [
|
|
2026
|
+
"includeTags",
|
|
2027
|
+
"excludeTags",
|
|
2028
|
+
"includePaths",
|
|
2029
|
+
"excludePaths"
|
|
2030
|
+
]) {
|
|
2031
|
+
const value = config[key];
|
|
2032
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) fail(key, "an array of strings");
|
|
2033
|
+
}
|
|
2034
|
+
if (config.requestOptions !== void 0 && (typeof config.requestOptions !== "object" || config.requestOptions === null || Array.isArray(config.requestOptions))) fail("requestOptions", "an object");
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
1167
2037
|
* Validate config has required fields
|
|
1168
2038
|
*/
|
|
1169
2039
|
function validateConfig(config) {
|
|
@@ -1171,9 +2041,10 @@ function validateConfig(config) {
|
|
|
1171
2041
|
return true;
|
|
1172
2042
|
}
|
|
1173
2043
|
/**
|
|
1174
|
-
* Load and resolve config
|
|
2044
|
+
* Load and resolve every config entry. A config file may define a single
|
|
2045
|
+
* object or a `specs` array for multi-spec projects.
|
|
1175
2046
|
*/
|
|
1176
|
-
async function
|
|
2047
|
+
async function loadConfigs(options = {}) {
|
|
1177
2048
|
const cwd = options.cwd || process.cwd();
|
|
1178
2049
|
const cliOptions = options.cliOptions || {};
|
|
1179
2050
|
const envConfig = loadFromEnv();
|
|
@@ -1189,107 +2060,276 @@ async function loadConfig(options = {}) {
|
|
|
1189
2060
|
fileConfig = await loadFromFile(foundPath);
|
|
1190
2061
|
}
|
|
1191
2062
|
}
|
|
1192
|
-
const packageJsonPath = node_path.default.join(cwd, "package.json");
|
|
1193
|
-
let inlineConfig = {};
|
|
1194
|
-
if (await fs_extra.default.pathExists(packageJsonPath)) try {
|
|
1195
|
-
const pkg = JSON.parse(await fs_extra.default.readFile(packageJsonPath, "utf-8"));
|
|
1196
|
-
if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
|
|
1197
|
-
} catch {}
|
|
1198
|
-
const
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
const
|
|
2063
|
+
const packageJsonPath = node_path.default.join(cwd, "package.json");
|
|
2064
|
+
let inlineConfig = {};
|
|
2065
|
+
if (await fs_extra.default.pathExists(packageJsonPath)) try {
|
|
2066
|
+
const pkg = JSON.parse(await fs_extra.default.readFile(packageJsonPath, "utf-8"));
|
|
2067
|
+
if (pkg.apicodegen && typeof pkg.apicodegen === "object") inlineConfig = pkg.apicodegen;
|
|
2068
|
+
} catch {}
|
|
2069
|
+
const { specs, ...fileOptions } = fileConfig;
|
|
2070
|
+
const entries = Array.isArray(specs) && specs.length > 0 ? specs.map((entry) => mergeConfigs({
|
|
2071
|
+
spec: "",
|
|
2072
|
+
output: "./output.ts"
|
|
2073
|
+
}, fileOptions, entry)) : [fileOptions];
|
|
2074
|
+
const sharedCliOptions = entries.length === 1 ? cliOptions : Object.fromEntries(Object.entries(cliOptions).filter(([key]) => key !== "spec" && key !== "output"));
|
|
2075
|
+
return entries.map((entry, index) => {
|
|
2076
|
+
const merged = mergeConfigs({
|
|
2077
|
+
spec: "",
|
|
2078
|
+
output: "./output.ts"
|
|
2079
|
+
}, envConfig, inlineConfig, entry, sharedCliOptions);
|
|
2080
|
+
validateConfigShape(merged);
|
|
2081
|
+
validateConfig(merged);
|
|
2082
|
+
const name = options.name || merged.name || merged.baseURL || merged.spec || `api-${index + 1}`;
|
|
2083
|
+
return {
|
|
2084
|
+
...merged,
|
|
2085
|
+
configFilePath,
|
|
2086
|
+
name
|
|
2087
|
+
};
|
|
2088
|
+
});
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* Load a single config. Throws when the file defines no entries.
|
|
2092
|
+
*/
|
|
2093
|
+
async function loadConfig(options = {}) {
|
|
2094
|
+
const config = (await loadConfigs(options))[0];
|
|
2095
|
+
if (!config) throw new Error("No API configs found");
|
|
2096
|
+
return config;
|
|
2097
|
+
}
|
|
2098
|
+
/**
|
|
2099
|
+
* Create CLI options from config for commander
|
|
2100
|
+
*/
|
|
2101
|
+
function configToCLIOptions(config) {
|
|
2102
|
+
const options = {};
|
|
2103
|
+
if (config.spec) options.spec = config.spec;
|
|
2104
|
+
if (config.output) options.output = config.output;
|
|
2105
|
+
if (config.adaptor) options.adaptor = config.adaptor;
|
|
2106
|
+
if (config.errorMode) options.errorMode = config.errorMode;
|
|
2107
|
+
if (config.splitBy) options.splitBy = config.splitBy;
|
|
2108
|
+
if (config.includeTags) options.includeTags = config.includeTags;
|
|
2109
|
+
if (config.excludeTags) options.excludeTags = config.excludeTags;
|
|
2110
|
+
if (config.includePaths) options.includePaths = config.includePaths;
|
|
2111
|
+
if (config.excludePaths) options.excludePaths = config.excludePaths;
|
|
2112
|
+
if (config.baseURL !== void 0) options.baseURL = config.baseURL;
|
|
2113
|
+
if (config.verbose) options.verbose = config.verbose;
|
|
2114
|
+
if (config.typeCheck) options.typeCheck = config.typeCheck;
|
|
2115
|
+
if (config.watch) options.watch = config.watch;
|
|
2116
|
+
if (config.check) options.check = config.check;
|
|
2117
|
+
if (config.importClientSource) options.importClientSource = config.importClientSource;
|
|
2118
|
+
return options;
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Convert resolved config to provider options format
|
|
2122
|
+
*/
|
|
2123
|
+
function toProviderOptions(config) {
|
|
2124
|
+
return {
|
|
2125
|
+
docURL: config.spec,
|
|
2126
|
+
output: config.output,
|
|
2127
|
+
adaptor: config.adaptor,
|
|
2128
|
+
baseURL: config.baseURL,
|
|
2129
|
+
importClientSource: config.importClientSource,
|
|
2130
|
+
verbose: config.verbose,
|
|
2131
|
+
requestOptions: config.requestOptions,
|
|
2132
|
+
errorMode: config.errorMode,
|
|
2133
|
+
splitBy: config.splitBy,
|
|
2134
|
+
includeTags: config.includeTags,
|
|
2135
|
+
excludeTags: config.excludeTags,
|
|
2136
|
+
includePaths: config.includePaths,
|
|
2137
|
+
excludePaths: config.excludePaths
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
// src/openapi/filter.ts
|
|
2141
|
+
function matchesPrefix(path, prefixes) {
|
|
2142
|
+
return !!prefixes?.length && prefixes.some((prefix) => path.startsWith(prefix));
|
|
2143
|
+
}
|
|
2144
|
+
/**
|
|
2145
|
+
* Keep only the operations selected by tag and path filters.
|
|
2146
|
+
*
|
|
2147
|
+
* Paths use prefix matching (`/admin` covers `/admin/users`). Operations with
|
|
2148
|
+
* no tags are kept only when no `includeTags` filter is active.
|
|
2149
|
+
*/
|
|
2150
|
+
function filterApis(apis, filters) {
|
|
2151
|
+
const keepTag = (op) => {
|
|
2152
|
+
const tags = op.tags ?? [];
|
|
2153
|
+
if (filters.includeTags?.length && !tags.some((tag) => filters.includeTags?.includes(tag))) return false;
|
|
2154
|
+
if (filters.excludeTags?.length && tags.some((tag) => filters.excludeTags?.includes(tag))) return false;
|
|
2155
|
+
return true;
|
|
2156
|
+
};
|
|
2157
|
+
const filtered = {};
|
|
2158
|
+
for (const [path, operations] of Object.entries(apis)) {
|
|
2159
|
+
if (filters.includePaths?.length && !matchesPrefix(path, filters.includePaths)) continue;
|
|
2160
|
+
if (matchesPrefix(path, filters.excludePaths)) continue;
|
|
2161
|
+
const kept = operations.filter(keepTag);
|
|
2162
|
+
if (kept.length > 0) filtered[path] = kept;
|
|
2163
|
+
}
|
|
2164
|
+
return filtered;
|
|
2165
|
+
}
|
|
2166
|
+
// src/openapi/read-write.ts
|
|
2167
|
+
function single(schema) {
|
|
2168
|
+
return schema;
|
|
2169
|
+
}
|
|
2170
|
+
/** True when a schema carries the flag anywhere except through a `$ref`. */
|
|
2171
|
+
function containsFlag(schema, flag) {
|
|
2172
|
+
if (!schema) return false;
|
|
2173
|
+
const value = single(schema);
|
|
2174
|
+
if (value[flag]) return true;
|
|
2175
|
+
if (value.properties) {
|
|
2176
|
+
for (const prop of Object.values(value.properties)) if (containsFlag(prop, flag)) return true;
|
|
2177
|
+
}
|
|
2178
|
+
if (schema.type === "array") return containsFlag(schema.items, flag);
|
|
2179
|
+
for (const key of [
|
|
2180
|
+
"allOf",
|
|
2181
|
+
"anyOf",
|
|
2182
|
+
"oneOf"
|
|
2183
|
+
]) if (value[key]?.some((member) => containsFlag(member, flag))) return true;
|
|
2184
|
+
const additional = value.additionalProperties;
|
|
2185
|
+
return !!additional && typeof additional === "object" && containsFlag(additional, flag);
|
|
2186
|
+
}
|
|
2187
|
+
/** The referenced emitted type name, when a schema is only a reference. */
|
|
2188
|
+
function refType(schema) {
|
|
2189
|
+
const value = single(schema);
|
|
2190
|
+
if (value.ref) return Base.upperCamelCase(Base.ref2name(value.ref));
|
|
2191
|
+
if (value.properties || value.oneOf || value.anyOf || value.allOf) return;
|
|
2192
|
+
if (schema.type === "array") return void 0;
|
|
2193
|
+
return typeof value.type === "string" ? Base.upperCamelCase(value.type) : void 0;
|
|
2194
|
+
}
|
|
2195
|
+
function dependsOn(schema, names) {
|
|
2196
|
+
const ref = refType(schema);
|
|
2197
|
+
if (ref && names.has(ref)) return true;
|
|
2198
|
+
const value = single(schema);
|
|
2199
|
+
if (value.properties) {
|
|
2200
|
+
for (const prop of Object.values(value.properties)) if (dependsOn(prop, names)) return true;
|
|
2201
|
+
}
|
|
2202
|
+
if (schema.type === "array") {
|
|
2203
|
+
const items = schema.items;
|
|
2204
|
+
return !!items && dependsOn(items, names);
|
|
2205
|
+
}
|
|
2206
|
+
for (const key of [
|
|
2207
|
+
"allOf",
|
|
2208
|
+
"anyOf",
|
|
2209
|
+
"oneOf"
|
|
2210
|
+
]) if (value[key]?.some((member) => dependsOn(member, names))) return true;
|
|
2211
|
+
const additional = value.additionalProperties;
|
|
2212
|
+
return !!additional && typeof additional === "object" && dependsOn(additional, names);
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Pick the schemas that need an Input/Output variant.
|
|
2216
|
+
*
|
|
2217
|
+
* A schema qualifies when it contains the flag directly, or references a
|
|
2218
|
+
* schema that does. The fixed point makes nested references follow.
|
|
2219
|
+
*/
|
|
2220
|
+
function buildVariant(schemas, flag, suffix) {
|
|
2221
|
+
const seeded = /* @__PURE__ */ new Set();
|
|
2222
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
2223
|
+
for (const key of Object.keys(schemas)) {
|
|
2224
|
+
emitted.set(Base.upperCamelCase(key), key);
|
|
2225
|
+
if (containsFlag(schemas[key], flag)) seeded.add(key);
|
|
2226
|
+
}
|
|
2227
|
+
let changed = true;
|
|
2228
|
+
while (changed) {
|
|
2229
|
+
changed = false;
|
|
2230
|
+
const seededNames = new Set([...seeded].map((key) => Base.upperCamelCase(key)));
|
|
2231
|
+
for (const key of Object.keys(schemas)) if (!seeded.has(key) && dependsOn(schemas[key], seededNames)) {
|
|
2232
|
+
seeded.add(key);
|
|
2233
|
+
changed = true;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
const names = /* @__PURE__ */ new Map();
|
|
2237
|
+
const keys = /* @__PURE__ */ new Map();
|
|
2238
|
+
const taken = new Set(emitted.keys());
|
|
2239
|
+
for (const key of seeded) {
|
|
2240
|
+
const variantKey = key + suffix;
|
|
2241
|
+
const variantName = Base.upperCamelCase(variantKey);
|
|
2242
|
+
if (taken.has(variantName)) continue;
|
|
2243
|
+
taken.add(variantName);
|
|
2244
|
+
names.set(Base.upperCamelCase(key), variantName);
|
|
2245
|
+
keys.set(key, variantKey);
|
|
2246
|
+
}
|
|
2247
|
+
return {
|
|
2248
|
+
names,
|
|
2249
|
+
keys
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
/** Clone a schema with flagged properties removed and variant refs remapped. */
|
|
2253
|
+
function transform(schema, flag, names) {
|
|
2254
|
+
const ref = refType(schema);
|
|
2255
|
+
if (ref && names.has(ref)) {
|
|
2256
|
+
const { ref: _ref, ...rest } = single(schema);
|
|
2257
|
+
return {
|
|
2258
|
+
...rest,
|
|
2259
|
+
type: names.get(ref)
|
|
2260
|
+
};
|
|
2261
|
+
}
|
|
2262
|
+
if (schema.type === "array") {
|
|
2263
|
+
const array = schema;
|
|
2264
|
+
return {
|
|
2265
|
+
...array,
|
|
2266
|
+
items: array.items ? transform(array.items, flag, names) : void 0
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
const value = single(schema);
|
|
2270
|
+
const next = { ...value };
|
|
2271
|
+
if (value.properties) {
|
|
2272
|
+
const properties = {};
|
|
2273
|
+
for (const [key, prop] of Object.entries(value.properties)) {
|
|
2274
|
+
if (single(prop)[flag]) continue;
|
|
2275
|
+
properties[key] = transform(prop, flag, names);
|
|
2276
|
+
}
|
|
2277
|
+
next.properties = properties;
|
|
2278
|
+
if (Array.isArray(value.required)) next.required = value.required.filter((key) => key in properties);
|
|
2279
|
+
}
|
|
2280
|
+
for (const key of [
|
|
2281
|
+
"allOf",
|
|
2282
|
+
"anyOf",
|
|
2283
|
+
"oneOf"
|
|
2284
|
+
]) {
|
|
2285
|
+
const members = value[key];
|
|
2286
|
+
if (members) next[key] = members.map((m) => transform(m, flag, names));
|
|
2287
|
+
}
|
|
2288
|
+
const additional = value.additionalProperties;
|
|
2289
|
+
if (additional && typeof additional === "object") next.additionalProperties = transform(additional, flag, names);
|
|
2290
|
+
return next;
|
|
2291
|
+
}
|
|
2292
|
+
function transformMedia(media, flag, names) {
|
|
2293
|
+
return media.map((entry) => entry.schema ? {
|
|
2294
|
+
...entry,
|
|
2295
|
+
schema: transform(entry.schema, flag, names)
|
|
2296
|
+
} : entry);
|
|
2297
|
+
}
|
|
2298
|
+
function transformOperation(operation, input, output) {
|
|
1204
2299
|
return {
|
|
1205
|
-
...
|
|
1206
|
-
|
|
1207
|
-
|
|
2300
|
+
...operation,
|
|
2301
|
+
...operation.requestBody ? { requestBody: transformMedia(operation.requestBody, "readOnly", input) } : {},
|
|
2302
|
+
...operation.responses ? { responses: transformMedia(operation.responses, "writeOnly", output) } : {},
|
|
2303
|
+
...operation.responseTypes ? { responseTypes: Object.fromEntries(Object.entries(operation.responseTypes).map(([code, media]) => [code, transformMedia(media, "writeOnly", output)])) } : {}
|
|
1208
2304
|
};
|
|
1209
2305
|
}
|
|
1210
2306
|
/**
|
|
1211
|
-
*
|
|
2307
|
+
* Add `XxxInput` / `XxxOutput` schema aliases and point operations at them:
|
|
2308
|
+
* requests drop `readOnly` properties, responses drop `writeOnly` ones.
|
|
2309
|
+
*
|
|
2310
|
+
* Existing type names are untouched; variants are only created when the name
|
|
2311
|
+
* is free. With no `readOnly` / `writeOnly` in the document this is a no-op.
|
|
1212
2312
|
*/
|
|
1213
|
-
function
|
|
2313
|
+
function splitReadWrite(parsed) {
|
|
2314
|
+
const input = buildVariant(parsed.schemas, "readOnly", "Input");
|
|
2315
|
+
const output = buildVariant(parsed.schemas, "writeOnly", "Output");
|
|
2316
|
+
if (input.keys.size === 0 && output.keys.size === 0) return parsed;
|
|
2317
|
+
const schemas = { ...parsed.schemas };
|
|
2318
|
+
for (const [key, variantKey] of input.keys) schemas[variantKey] = transform(parsed.schemas[key], "readOnly", input.names);
|
|
2319
|
+
for (const [key, variantKey] of output.keys) schemas[variantKey] = transform(parsed.schemas[key], "writeOnly", output.names);
|
|
2320
|
+
const apis = Object.fromEntries(Object.entries(parsed.apis).map(([path, operations]) => [path, operations.map((operation) => transformOperation(operation, input.names, output.names))]));
|
|
1214
2321
|
return {
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
baseURL: config.baseURL,
|
|
1219
|
-
importClientSource: config.importClientSource,
|
|
1220
|
-
verbose: config.verbose,
|
|
1221
|
-
requestOptions: config.requestOptions
|
|
2322
|
+
...parsed,
|
|
2323
|
+
schemas,
|
|
2324
|
+
apis
|
|
1222
2325
|
};
|
|
1223
2326
|
}
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
const blue = (s) => `\x1b[34m${s}\x1b[0m`;
|
|
1230
|
-
const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
|
|
1231
|
-
const magenta = (s) => `\x1b[35m${s}\x1b[0m`;
|
|
1232
|
-
const gray = (s) => `\x1b[90m${s}\x1b[0m`;
|
|
1233
|
-
const bold = (s) => `\x1b[1m${s}\x1b[0m`;
|
|
1234
|
-
const logger = {
|
|
1235
|
-
success(msg) {
|
|
1236
|
-
console.log(`${green("✓")} ${msg}`);
|
|
1237
|
-
},
|
|
1238
|
-
error(err, verbose = false) {
|
|
1239
|
-
if (isApicodegenError(err)) console.error(`${red("✗")} ${err.toString(verbose)}`);
|
|
1240
|
-
else if (err instanceof Error) {
|
|
1241
|
-
const msg = `Error: ${err.message}`;
|
|
1242
|
-
console.error(`${red("✗")} ${msg}${verbose && err.stack ? `\n${gray(err.stack)}` : ""}`);
|
|
1243
|
-
} else console.error(`${red("✗")} ${String(err)}`);
|
|
1244
|
-
},
|
|
1245
|
-
info(msg) {
|
|
1246
|
-
console.log(`${blue("ℹ")} ${msg}`);
|
|
1247
|
-
},
|
|
1248
|
-
warn(msg) {
|
|
1249
|
-
console.log(`${yellow("⚠")} ${msg}`);
|
|
1250
|
-
},
|
|
1251
|
-
loading(msg) {
|
|
1252
|
-
console.log(`${yellow("🔄")} ${msg}`);
|
|
1253
|
-
},
|
|
1254
|
-
watching(msg) {
|
|
1255
|
-
console.log(`${magenta("⟳")} ${msg}`);
|
|
1256
|
-
},
|
|
1257
|
-
fileChange(filePath) {
|
|
1258
|
-
console.log(`${yellow("↓")} ${filePath}`);
|
|
1259
|
-
},
|
|
1260
|
-
fileAdd(filePath) {
|
|
1261
|
-
console.log(`${green("+")} ${filePath}`);
|
|
1262
|
-
},
|
|
1263
|
-
shutdown() {
|
|
1264
|
-
console.log(`\n${gray("👋 Shutting down...")}`);
|
|
1265
|
-
},
|
|
1266
|
-
divider(width = 50) {
|
|
1267
|
-
console.log(`${bold(cyan("─".repeat(width)))}`);
|
|
1268
|
-
},
|
|
1269
|
-
heading(text, mode, width = 50) {
|
|
1270
|
-
console.log(`${bold(cyan("─".repeat(width)))}`);
|
|
1271
|
-
console.log(`${bold(cyan(text))}`);
|
|
1272
|
-
console.log(`${gray("Mode:")} ${mode || "unknown"}`);
|
|
1273
|
-
console.log(`${bold(cyan("─".repeat(width)))}`);
|
|
1274
|
-
},
|
|
1275
|
-
item(label, color = "green") {
|
|
1276
|
-
const icon = color === "green" ? "✓" : color === "red" ? "✗" : "⚠";
|
|
1277
|
-
console.log(`${color === "green" ? green(icon) : color === "red" ? red(icon) : yellow(icon)} ${label}`);
|
|
1278
|
-
},
|
|
1279
|
-
summary(stats) {
|
|
1280
|
-
const { succeeded, failed, endpoints, schemas, duration } = stats;
|
|
1281
|
-
const label = `API Code Gen - Complete (${succeeded} succeeded${failed > 0 ? `, ${failed} failed` : ""}, ${endpoints} endpoints, ${schemas} schemas, ${duration}ms)`;
|
|
1282
|
-
if (failed === 0) console.log(`${green("✓")} ${label}`);
|
|
1283
|
-
else console.log(`${yellow("⚠")} ${label}`);
|
|
2327
|
+
// src/openapi/V2.ts
|
|
2328
|
+
var V2 = class {
|
|
2329
|
+
doc;
|
|
2330
|
+
constructor(doc) {
|
|
2331
|
+
this.doc = doc;
|
|
1284
2332
|
}
|
|
1285
|
-
};
|
|
1286
|
-
//#endregion
|
|
1287
|
-
//#region src/openapi/VersionedProvider.ts
|
|
1288
|
-
/**
|
|
1289
|
-
* Abstract base class. Subclasses implement the four container accessors
|
|
1290
|
-
* and a version tag. The shared logic lives here.
|
|
1291
|
-
*/
|
|
1292
|
-
var VersionedProvider = class {
|
|
1293
2333
|
/**
|
|
1294
2334
|
* Resolves a path $ref to the actual path object.
|
|
1295
2335
|
*/
|
|
@@ -1301,37 +2341,295 @@ var VersionedProvider = class {
|
|
|
1301
2341
|
* Is array schema.
|
|
1302
2342
|
*/
|
|
1303
2343
|
isOpenAPIArraySchema(schema) {
|
|
1304
|
-
return typeof schema === "object" && schema
|
|
2344
|
+
return typeof schema === "object" && schema.type === "array";
|
|
1305
2345
|
}
|
|
1306
2346
|
/**
|
|
1307
|
-
* OpenAPI schema to base schema.
|
|
1308
|
-
* (V3_1 throws on missing ref; V3 returns `{ type: 'unknown' }`).
|
|
2347
|
+
* OpenAPI schema to base schema.
|
|
1309
2348
|
*/
|
|
1310
2349
|
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
1311
2350
|
let refName = "";
|
|
1312
2351
|
if (Base.isRef(schema)) {
|
|
1313
|
-
refName =
|
|
2352
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
1314
2353
|
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
schema = resolvedSchema;
|
|
2354
|
+
if (!this.doc.definitions) this.doc.definitions = {};
|
|
2355
|
+
schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
|
|
1318
2356
|
}
|
|
1319
2357
|
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1320
2358
|
}
|
|
1321
2359
|
/**
|
|
1322
|
-
*
|
|
1323
|
-
|
|
2360
|
+
* Transform all OpenAPI schema to Base Schema
|
|
2361
|
+
*/
|
|
2362
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
2363
|
+
if (!schema) return { type: "unknown" };
|
|
2364
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2365
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
2366
|
+
const { type, description, items, required } = schema;
|
|
2367
|
+
return {
|
|
2368
|
+
type,
|
|
2369
|
+
required: !!required,
|
|
2370
|
+
description,
|
|
2371
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2372
|
+
};
|
|
2373
|
+
} else {
|
|
2374
|
+
const { required = [], allOf, anyOf, description, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2375
|
+
let { type } = schema;
|
|
2376
|
+
if (enum_ && type !== "boolean") {
|
|
2377
|
+
const enumObject = {
|
|
2378
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2379
|
+
enum: [...new Set(enum_)]
|
|
2380
|
+
};
|
|
2381
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2382
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2383
|
+
return {
|
|
2384
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2385
|
+
required,
|
|
2386
|
+
description
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2390
|
+
return {
|
|
2391
|
+
type,
|
|
2392
|
+
required,
|
|
2393
|
+
description,
|
|
2394
|
+
discriminator: discriminator ? { propertyName: discriminator } : void 0,
|
|
2395
|
+
enum: enum_,
|
|
2396
|
+
format,
|
|
2397
|
+
readOnly: schema.readOnly,
|
|
2398
|
+
writeOnly: schema.writeOnly,
|
|
2399
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2400
|
+
...s,
|
|
2401
|
+
ref: s.$ref,
|
|
2402
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2403
|
+
} : this.toBaseSchema(s, enums)),
|
|
2404
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2405
|
+
...s,
|
|
2406
|
+
ref: s.$ref,
|
|
2407
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2408
|
+
} : this.toBaseSchema(s, enums)),
|
|
2409
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2410
|
+
...s,
|
|
2411
|
+
ref: s.$ref,
|
|
2412
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2413
|
+
} : this.toBaseSchema(s, enums)),
|
|
2414
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
2415
|
+
const propSchema = properties[p];
|
|
2416
|
+
return {
|
|
2417
|
+
...acc,
|
|
2418
|
+
[p]: Base.isRef(propSchema) ? { type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)) } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
2419
|
+
};
|
|
2420
|
+
}, {})
|
|
2421
|
+
};
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* OpenAPI parameter to base parameter.
|
|
2426
|
+
*/
|
|
2427
|
+
getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
|
|
2428
|
+
if (Base.isRef(parameter)) {
|
|
2429
|
+
const refName = Base.ref2name(parameter.$ref, this.doc);
|
|
2430
|
+
const resolved = this.doc.parameters?.[refName];
|
|
2431
|
+
if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
|
|
2432
|
+
parameter = resolved;
|
|
2433
|
+
}
|
|
2434
|
+
const p = parameter;
|
|
2435
|
+
const collectionFormat = p.collectionFormat;
|
|
2436
|
+
const style = collectionFormat === "ssv" ? "spaceDelimited" : collectionFormat === "pipes" ? "pipeDelimited" : "form";
|
|
2437
|
+
const explode = collectionFormat === "multi";
|
|
2438
|
+
const { name, required, description, type, items, enum: enum_, properties, schema } = p;
|
|
2439
|
+
if (enum_) {
|
|
2440
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
2441
|
+
const enumSchema = {
|
|
2442
|
+
name: type,
|
|
2443
|
+
enum: [...new Set(enum_)]
|
|
2444
|
+
};
|
|
2445
|
+
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
2446
|
+
if (!sameEnum && Base.isValidEnumType({
|
|
2447
|
+
type,
|
|
2448
|
+
enum: enum_
|
|
2449
|
+
})) enums.push(enumSchema);
|
|
2450
|
+
return {
|
|
2451
|
+
name,
|
|
2452
|
+
required,
|
|
2453
|
+
description,
|
|
2454
|
+
in: p.in,
|
|
2455
|
+
style,
|
|
2456
|
+
explode,
|
|
2457
|
+
schema: { type: sameEnum?.name ?? type }
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
if (items) return {
|
|
2461
|
+
name,
|
|
2462
|
+
required,
|
|
2463
|
+
description,
|
|
2464
|
+
in: p.in,
|
|
2465
|
+
style,
|
|
2466
|
+
explode,
|
|
2467
|
+
schema: {
|
|
2468
|
+
type,
|
|
2469
|
+
items
|
|
2470
|
+
}
|
|
2471
|
+
};
|
|
2472
|
+
if (schema && Base.isRef(schema)) return {
|
|
2473
|
+
name,
|
|
2474
|
+
required,
|
|
2475
|
+
description,
|
|
2476
|
+
in: p.in,
|
|
2477
|
+
style,
|
|
2478
|
+
explode,
|
|
2479
|
+
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
2480
|
+
};
|
|
2481
|
+
return {
|
|
2482
|
+
name,
|
|
2483
|
+
required,
|
|
2484
|
+
description,
|
|
2485
|
+
in: p.in,
|
|
2486
|
+
style,
|
|
2487
|
+
explode,
|
|
2488
|
+
schema: {
|
|
2489
|
+
type,
|
|
2490
|
+
properties
|
|
2491
|
+
}
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* OpenAPI schema to base response
|
|
2496
|
+
*/
|
|
2497
|
+
getResponseByRef(schema, enums = []) {
|
|
2498
|
+
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
2499
|
+
const { schema: responseSchema } = schema;
|
|
2500
|
+
return [{
|
|
2501
|
+
type: "application/json",
|
|
2502
|
+
schema: responseSchema && this.getSchemaByRef(responseSchema, true, enums)
|
|
2503
|
+
}];
|
|
2504
|
+
}
|
|
2505
|
+
init() {
|
|
2506
|
+
const { definitions = {}, responses = {}, paths = {}, security = [], securityDefinitions = {} } = this.doc;
|
|
2507
|
+
const enums = [];
|
|
2508
|
+
const definitions_ = Object.keys(definitions).reduce((acc, key) => {
|
|
2509
|
+
const schema = definitions[key];
|
|
2510
|
+
return {
|
|
2511
|
+
...acc,
|
|
2512
|
+
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
2513
|
+
};
|
|
2514
|
+
}, {});
|
|
2515
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
2516
|
+
const response = responses[key];
|
|
2517
|
+
return {
|
|
2518
|
+
...acc,
|
|
2519
|
+
[key]: this.getResponseByRef(response, enums)
|
|
2520
|
+
};
|
|
2521
|
+
}, {});
|
|
2522
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
2523
|
+
let pathObject = paths[path] ?? {};
|
|
2524
|
+
if (pathObject.$ref) {
|
|
2525
|
+
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
2526
|
+
if (resolved) pathObject = resolved;
|
|
2527
|
+
}
|
|
2528
|
+
const { parameters = [] } = pathObject;
|
|
2529
|
+
const methodApis = [];
|
|
2530
|
+
Object.values(HttpMethods).forEach((method) => {
|
|
2531
|
+
const methodObject = pathObject[method];
|
|
2532
|
+
if (methodObject) {
|
|
2533
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {} } = methodObject;
|
|
2534
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
2535
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
2536
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
2537
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2538
|
+
const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
|
|
2539
|
+
const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
|
|
2540
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2541
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2542
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2543
|
+
const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
2544
|
+
methodApis.push({
|
|
2545
|
+
method,
|
|
2546
|
+
operationId,
|
|
2547
|
+
summary: summary_,
|
|
2548
|
+
deprecated,
|
|
2549
|
+
description: description_,
|
|
2550
|
+
parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
|
|
2551
|
+
responses: responseTypes[successCode] ?? [],
|
|
2552
|
+
responseTypes,
|
|
2553
|
+
tags: methodObject.tags,
|
|
2554
|
+
security: methodObject.security ?? security,
|
|
2555
|
+
requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
|
|
2556
|
+
type: "application/json",
|
|
2557
|
+
schema: inBody[0].schema
|
|
2558
|
+
}] : [{
|
|
2559
|
+
type: "application/json",
|
|
2560
|
+
schema: {
|
|
2561
|
+
type: "object",
|
|
2562
|
+
properties: inBody.reduce((a, p) => {
|
|
2563
|
+
return {
|
|
2564
|
+
...a,
|
|
2565
|
+
[p.name]: {
|
|
2566
|
+
type: p.schema?.type ?? "unknown",
|
|
2567
|
+
required: p.schema?.required,
|
|
2568
|
+
items: p.schema?.items,
|
|
2569
|
+
description: p.schema?.description
|
|
2570
|
+
}
|
|
2571
|
+
};
|
|
2572
|
+
}, {})
|
|
2573
|
+
}
|
|
2574
|
+
}] : void 0
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
});
|
|
2578
|
+
return {
|
|
2579
|
+
...acc,
|
|
2580
|
+
[path]: methodApis
|
|
2581
|
+
};
|
|
2582
|
+
}, {});
|
|
2583
|
+
return {
|
|
2584
|
+
enums: Base.uniqueEnums(enums),
|
|
2585
|
+
schemas: definitions_,
|
|
2586
|
+
responses: responses_,
|
|
2587
|
+
parameters: {},
|
|
2588
|
+
requestBodies: {},
|
|
2589
|
+
securitySchemes: securityDefinitions,
|
|
2590
|
+
apis
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
};
|
|
2594
|
+
// src/openapi/V3.ts
|
|
2595
|
+
var V3 = class {
|
|
2596
|
+
doc;
|
|
2597
|
+
constructor(doc) {
|
|
2598
|
+
this.doc = doc;
|
|
2599
|
+
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Resolves a path $ref to the actual path object.
|
|
2602
|
+
*/
|
|
2603
|
+
resolvePathRef($ref) {
|
|
2604
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
2605
|
+
return this.doc.paths?.[refName];
|
|
2606
|
+
}
|
|
2607
|
+
/**
|
|
2608
|
+
* Is array schema.
|
|
2609
|
+
*/
|
|
2610
|
+
isOpenAPIArraySchema(schema) {
|
|
2611
|
+
return typeof schema === "object" && schema.type === "array";
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* OpenAPI schema to base schema.
|
|
1324
2615
|
*/
|
|
1325
|
-
|
|
1326
|
-
|
|
2616
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
2617
|
+
let refName = "";
|
|
2618
|
+
if (Base.isRef(schema)) {
|
|
2619
|
+
refName = Base.capitalize(Base.ref2name(schema.$ref));
|
|
2620
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
2621
|
+
const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2622
|
+
if (!resolvedSchema) return { type: "unknown" };
|
|
2623
|
+
schema = resolvedSchema;
|
|
2624
|
+
}
|
|
2625
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
1327
2626
|
}
|
|
1328
2627
|
/**
|
|
1329
|
-
* OpenAPI parameter to base parameter.
|
|
1330
|
-
* shape is structurally different (top-level `items`/`properties`/`enum`).
|
|
2628
|
+
* OpenAPI parameter to base parameter.
|
|
1331
2629
|
*/
|
|
1332
2630
|
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
1333
2631
|
if (Base.isRef(schema)) {
|
|
1334
|
-
const resolvedSchema = this.
|
|
2632
|
+
const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1335
2633
|
if (!resolvedSchema) return {
|
|
1336
2634
|
name: "unknown",
|
|
1337
2635
|
in: "query"
|
|
@@ -1353,7 +2651,9 @@ var VersionedProvider = class {
|
|
|
1353
2651
|
description,
|
|
1354
2652
|
deprecated,
|
|
1355
2653
|
in: schema.in,
|
|
1356
|
-
schema: { type: sameEnum?.name ?? type }
|
|
2654
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2655
|
+
style: schema.style,
|
|
2656
|
+
explode: schema.explode
|
|
1357
2657
|
};
|
|
1358
2658
|
}
|
|
1359
2659
|
return {
|
|
@@ -1362,38 +2662,39 @@ var VersionedProvider = class {
|
|
|
1362
2662
|
description,
|
|
1363
2663
|
deprecated,
|
|
1364
2664
|
in: schema.in,
|
|
1365
|
-
|
|
2665
|
+
style: schema.style,
|
|
2666
|
+
explode: schema.explode,
|
|
2667
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1366
2668
|
};
|
|
1367
2669
|
}
|
|
1368
2670
|
/**
|
|
1369
|
-
* OpenAPI schema to base response
|
|
1370
|
-
* lacks the `content` wrapper).
|
|
2671
|
+
* OpenAPI schema to base response
|
|
1371
2672
|
*/
|
|
1372
|
-
getResponseByRef(schema) {
|
|
2673
|
+
getResponseByRef(schema, enums = []) {
|
|
1373
2674
|
if (Base.isRef(schema)) {
|
|
1374
|
-
const resolvedSchema = this.
|
|
2675
|
+
const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1375
2676
|
if (!resolvedSchema) return [];
|
|
1376
2677
|
schema = resolvedSchema;
|
|
1377
2678
|
}
|
|
1378
2679
|
const { content = {} } = schema;
|
|
1379
2680
|
return Object.keys(content).map((c) => ({
|
|
1380
2681
|
type: c,
|
|
1381
|
-
schema: content[c].schema
|
|
2682
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
1382
2683
|
}));
|
|
1383
2684
|
}
|
|
1384
2685
|
/**
|
|
1385
|
-
* OpenAPI schema to requestBody.
|
|
2686
|
+
* OpenAPI schema to requestBody.
|
|
1386
2687
|
*/
|
|
1387
2688
|
getRequestBodyByRef(schema, enums = []) {
|
|
1388
2689
|
if (Base.isRef(schema)) {
|
|
1389
|
-
const resolvedSchema = this.
|
|
2690
|
+
const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
1390
2691
|
if (!resolvedSchema) return [];
|
|
1391
2692
|
schema = resolvedSchema;
|
|
1392
2693
|
}
|
|
1393
2694
|
const { content = {} } = schema;
|
|
1394
2695
|
return Object.keys(content).map((c) => ({
|
|
1395
2696
|
type: c,
|
|
1396
|
-
schema: content[c].schema
|
|
2697
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
|
|
1397
2698
|
}));
|
|
1398
2699
|
}
|
|
1399
2700
|
/**
|
|
@@ -1403,99 +2704,100 @@ var VersionedProvider = class {
|
|
|
1403
2704
|
if (!schema) return { type: "unknown" };
|
|
1404
2705
|
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
1405
2706
|
if (this.isOpenAPIArraySchema(schema)) {
|
|
1406
|
-
const { type, description, items, required } = schema;
|
|
1407
|
-
const itemsSchema = items ? this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey) : { type: "unknown" };
|
|
2707
|
+
const { type, description, items, required, nullable } = schema;
|
|
1408
2708
|
return {
|
|
1409
2709
|
type,
|
|
2710
|
+
nullable,
|
|
1410
2711
|
required: !!required,
|
|
1411
2712
|
description,
|
|
1412
|
-
items:
|
|
1413
|
-
};
|
|
1414
|
-
}
|
|
1415
|
-
const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
1416
|
-
let { type } = schema;
|
|
1417
|
-
if (enum_ && type !== "boolean") {
|
|
1418
|
-
const enumObject = {
|
|
1419
|
-
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
|
|
1420
|
-
enum: [...new Set(enum_)]
|
|
1421
|
-
};
|
|
1422
|
-
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
1423
|
-
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1424
|
-
return {
|
|
1425
|
-
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
1426
|
-
required,
|
|
1427
|
-
description,
|
|
1428
|
-
deprecated
|
|
2713
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
1429
2714
|
};
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
type
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
...s,
|
|
1441
|
-
ref: s.$ref,
|
|
1442
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1443
|
-
} : this.toBaseSchema(s, enums)),
|
|
1444
|
-
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
1445
|
-
...s,
|
|
1446
|
-
ref: s.$ref,
|
|
1447
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1448
|
-
} : this.toBaseSchema(s, enums)),
|
|
1449
|
-
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
1450
|
-
...s,
|
|
1451
|
-
ref: s.$ref,
|
|
1452
|
-
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
1453
|
-
} : this.toBaseSchema(s, enums)),
|
|
1454
|
-
properties: Object.keys(properties).reduce((acc, p) => {
|
|
1455
|
-
const propSchema = properties[p];
|
|
2715
|
+
} else {
|
|
2716
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {} } = schema;
|
|
2717
|
+
let { type } = schema;
|
|
2718
|
+
if (enum_ && type !== "boolean") {
|
|
2719
|
+
const enumObject = {
|
|
2720
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2721
|
+
enum: [...new Set(enum_)]
|
|
2722
|
+
};
|
|
2723
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2724
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
1456
2725
|
return {
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
2726
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2727
|
+
nullable: schema.nullable,
|
|
2728
|
+
required,
|
|
2729
|
+
description,
|
|
2730
|
+
deprecated
|
|
1462
2731
|
};
|
|
1463
|
-
}
|
|
1464
|
-
|
|
2732
|
+
}
|
|
2733
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2734
|
+
return {
|
|
2735
|
+
type,
|
|
2736
|
+
nullable: schema.nullable,
|
|
2737
|
+
additionalProperties: schema.additionalProperties && typeof schema.additionalProperties === "object" ? this.toBaseSchema(schema.additionalProperties, enums) : schema.additionalProperties,
|
|
2738
|
+
required,
|
|
2739
|
+
description,
|
|
2740
|
+
deprecated,
|
|
2741
|
+
discriminator,
|
|
2742
|
+
enum: enum_,
|
|
2743
|
+
format,
|
|
2744
|
+
readOnly: schema.readOnly,
|
|
2745
|
+
writeOnly: schema.writeOnly,
|
|
2746
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
2747
|
+
...s,
|
|
2748
|
+
ref: s.$ref,
|
|
2749
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2750
|
+
} : this.toBaseSchema(s, enums)),
|
|
2751
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
2752
|
+
...s,
|
|
2753
|
+
ref: s.$ref,
|
|
2754
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2755
|
+
} : this.toBaseSchema(s, enums)),
|
|
2756
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
2757
|
+
...s,
|
|
2758
|
+
ref: s.$ref,
|
|
2759
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
2760
|
+
} : this.toBaseSchema(s, enums)),
|
|
2761
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
2762
|
+
const propSchema = properties[p];
|
|
2763
|
+
return {
|
|
2764
|
+
...acc,
|
|
2765
|
+
[p]: Base.isRef(propSchema) ? {
|
|
2766
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
2767
|
+
isRef: true
|
|
2768
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
2769
|
+
};
|
|
2770
|
+
}, {})
|
|
2771
|
+
};
|
|
2772
|
+
}
|
|
1465
2773
|
}
|
|
1466
|
-
/**
|
|
1467
|
-
* Run the parsing pipeline and return a ProviderInitResult.
|
|
1468
|
-
*/
|
|
1469
2774
|
init() {
|
|
1470
|
-
const { paths = {} } = this.doc;
|
|
2775
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1471
2776
|
const enums = [];
|
|
1472
|
-
const
|
|
1473
|
-
const
|
|
1474
|
-
|
|
1475
|
-
const requestBodyContainer = this.getRequestBodyContainer() ?? {};
|
|
1476
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1477
|
-
const schema = schemaContainer[key];
|
|
2777
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
2778
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
2779
|
+
const schema = schemas[key];
|
|
1478
2780
|
return {
|
|
1479
2781
|
...acc,
|
|
1480
2782
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1481
2783
|
};
|
|
1482
2784
|
}, {});
|
|
1483
|
-
const parameters_ = Object.keys(
|
|
1484
|
-
const parameter =
|
|
2785
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
2786
|
+
const parameter = parameters[key];
|
|
1485
2787
|
return {
|
|
1486
2788
|
...acc,
|
|
1487
2789
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1488
2790
|
};
|
|
1489
2791
|
}, {});
|
|
1490
|
-
const responses_ = Object.keys(
|
|
1491
|
-
const response =
|
|
2792
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
2793
|
+
const response = responses[key];
|
|
1492
2794
|
return {
|
|
1493
2795
|
...acc,
|
|
1494
|
-
[key]: this.getResponseByRef(response)
|
|
2796
|
+
[key]: this.getResponseByRef(response, enums)
|
|
1495
2797
|
};
|
|
1496
2798
|
}, {});
|
|
1497
|
-
const requestBodies_ = Object.keys(
|
|
1498
|
-
const requestBody =
|
|
2799
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
2800
|
+
const requestBody = requestBodies[key];
|
|
1499
2801
|
return {
|
|
1500
2802
|
...acc,
|
|
1501
2803
|
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
@@ -1512,29 +2814,28 @@ var VersionedProvider = class {
|
|
|
1512
2814
|
Object.values(HttpMethods).forEach((method) => {
|
|
1513
2815
|
const methodObject = pathObject[method];
|
|
1514
2816
|
if (methodObject) {
|
|
1515
|
-
const { deprecated, operationId, responses, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1516
|
-
const responsesClone = responses ? { ...responses } : {};
|
|
2817
|
+
const { deprecated, operationId, responses = {}, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
|
|
1517
2818
|
const { parameters: parameters_ = [] } = methodObject;
|
|
1518
2819
|
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
1519
2820
|
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
1520
2821
|
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
1521
|
-
if (Object.keys(
|
|
1522
|
-
const httpCodes = Object.keys(
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
}
|
|
2822
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
2823
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
2824
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
2825
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
2826
|
+
methodApis.push({
|
|
2827
|
+
method,
|
|
2828
|
+
operationId,
|
|
2829
|
+
summary: summary_ ?? summary,
|
|
2830
|
+
description: description_ ?? description,
|
|
2831
|
+
deprecated,
|
|
2832
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
2833
|
+
responses: responseTypes[successCode] ?? [],
|
|
2834
|
+
responseTypes,
|
|
2835
|
+
tags: methodObject.tags,
|
|
2836
|
+
security: methodObject.security ?? security,
|
|
2837
|
+
requestBody: baseRequestBody
|
|
2838
|
+
});
|
|
1538
2839
|
}
|
|
1539
2840
|
});
|
|
1540
2841
|
return {
|
|
@@ -1548,252 +2849,275 @@ var VersionedProvider = class {
|
|
|
1548
2849
|
responses: responses_,
|
|
1549
2850
|
parameters: parameters_,
|
|
1550
2851
|
requestBodies: requestBodies_,
|
|
2852
|
+
securitySchemes,
|
|
1551
2853
|
apis
|
|
1552
2854
|
};
|
|
1553
2855
|
}
|
|
1554
2856
|
};
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
var V2 = class extends VersionedProvider {
|
|
2857
|
+
// src/openapi/V3_1.ts
|
|
2858
|
+
var V3_1 = class {
|
|
1558
2859
|
doc;
|
|
1559
|
-
version = "v2";
|
|
1560
2860
|
constructor(doc) {
|
|
1561
|
-
super();
|
|
1562
2861
|
this.doc = doc;
|
|
1563
2862
|
}
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
2863
|
+
/**
|
|
2864
|
+
* Resolves a path $ref to the actual path object.
|
|
2865
|
+
*/
|
|
2866
|
+
resolvePathRef($ref) {
|
|
2867
|
+
const refName = Base.ref2name($ref, this.doc);
|
|
2868
|
+
return this.doc.paths?.[refName];
|
|
1569
2869
|
}
|
|
1570
|
-
|
|
1571
|
-
|
|
2870
|
+
/**
|
|
2871
|
+
* Is array schema.
|
|
2872
|
+
*/
|
|
2873
|
+
isOpenAPIArraySchema(schema) {
|
|
2874
|
+
if (typeof schema !== "object") return false;
|
|
2875
|
+
return schema.type === "array" || Array.isArray(schema.type) && schema.type.includes("array");
|
|
1572
2876
|
}
|
|
1573
|
-
getRequestBodyContainer() {}
|
|
1574
2877
|
/**
|
|
1575
|
-
*
|
|
1576
|
-
* rather than nested under `schema`. Override accordingly.
|
|
2878
|
+
* OpenAPI schema to base schema.
|
|
1577
2879
|
*/
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
if (
|
|
1583
|
-
|
|
2880
|
+
getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
|
|
2881
|
+
let refName = "";
|
|
2882
|
+
if (Base.isRef(schema)) {
|
|
2883
|
+
refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
|
|
2884
|
+
if (reserveRef) return { type: upLevelSchemaKey + refName };
|
|
2885
|
+
if (!this.doc.components) this.doc.components = { schemas: {} };
|
|
2886
|
+
const resolvedSchema = this.doc.components.schemas?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2887
|
+
if (!resolvedSchema) throw new Error(`Schema reference not found: ${refName}`);
|
|
2888
|
+
schema = resolvedSchema;
|
|
1584
2889
|
}
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
2890
|
+
return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
|
|
2891
|
+
}
|
|
2892
|
+
/**
|
|
2893
|
+
* OpenAPI parameter to base parameter.
|
|
2894
|
+
*/
|
|
2895
|
+
getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
|
|
2896
|
+
if (Base.isRef(schema)) schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2897
|
+
const { name, required, deprecated, description, schema: parameterSchema } = schema;
|
|
2898
|
+
if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
|
|
2899
|
+
const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
|
|
1589
2900
|
const enumSchema = {
|
|
1590
|
-
name:
|
|
1591
|
-
enum: [...new Set(
|
|
2901
|
+
name: type,
|
|
2902
|
+
enum: [...new Set(parameterSchema.enum)]
|
|
1592
2903
|
};
|
|
1593
2904
|
const sameEnum = Base.findSameSchema(enumSchema, enums);
|
|
1594
|
-
if (!sameEnum && Base.isValidEnumType(
|
|
1595
|
-
type: enumType,
|
|
1596
|
-
enum: enum_
|
|
1597
|
-
})) enums.push(enumSchema);
|
|
2905
|
+
if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
|
|
1598
2906
|
return {
|
|
1599
2907
|
name,
|
|
1600
2908
|
required,
|
|
1601
2909
|
description,
|
|
1602
|
-
|
|
1603
|
-
|
|
2910
|
+
deprecated,
|
|
2911
|
+
in: schema.in,
|
|
2912
|
+
schema: { type: sameEnum?.name ?? type },
|
|
2913
|
+
style: schema.style,
|
|
2914
|
+
explode: schema.explode
|
|
1604
2915
|
};
|
|
1605
2916
|
}
|
|
1606
|
-
if (items) return {
|
|
1607
|
-
name,
|
|
1608
|
-
required,
|
|
1609
|
-
description,
|
|
1610
|
-
in: p.in,
|
|
1611
|
-
schema: {
|
|
1612
|
-
type,
|
|
1613
|
-
items
|
|
1614
|
-
}
|
|
1615
|
-
};
|
|
1616
|
-
if (schema && Base.isRef(schema)) return {
|
|
1617
|
-
name,
|
|
1618
|
-
required,
|
|
1619
|
-
description,
|
|
1620
|
-
in: p.in,
|
|
1621
|
-
schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
|
|
1622
|
-
};
|
|
1623
2917
|
return {
|
|
1624
2918
|
name,
|
|
1625
2919
|
required,
|
|
1626
2920
|
description,
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
2921
|
+
deprecated,
|
|
2922
|
+
in: schema.in,
|
|
2923
|
+
style: schema.style,
|
|
2924
|
+
explode: schema.explode,
|
|
2925
|
+
schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
|
|
1632
2926
|
};
|
|
1633
2927
|
}
|
|
1634
2928
|
/**
|
|
1635
|
-
*
|
|
1636
|
-
* emits JSON.
|
|
2929
|
+
* OpenAPI schema to base response
|
|
1637
2930
|
*/
|
|
1638
|
-
getResponseByRef(schema) {
|
|
1639
|
-
if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
|
|
1640
|
-
const {
|
|
1641
|
-
return
|
|
1642
|
-
type:
|
|
1643
|
-
schema:
|
|
1644
|
-
}
|
|
2931
|
+
getResponseByRef(schema, enums = []) {
|
|
2932
|
+
if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2933
|
+
const { content = {} } = schema;
|
|
2934
|
+
return Object.keys(content).map((c) => ({
|
|
2935
|
+
type: c,
|
|
2936
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2937
|
+
}));
|
|
2938
|
+
}
|
|
2939
|
+
/**
|
|
2940
|
+
* OpenAPI schema to requestBody.
|
|
2941
|
+
*/
|
|
2942
|
+
getRequestBodyByRef(schema, enums = []) {
|
|
2943
|
+
if (Base.isRef(schema)) schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
|
|
2944
|
+
const { content = {} } = schema;
|
|
2945
|
+
return Object.keys(content).map((c) => ({
|
|
2946
|
+
type: c,
|
|
2947
|
+
schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
|
|
2948
|
+
}));
|
|
1645
2949
|
}
|
|
1646
2950
|
/**
|
|
1647
|
-
*
|
|
1648
|
-
* `in: formData` are split out and turned into a synthetic requestBody
|
|
1649
|
-
* here. A single body param named `body` is used directly; otherwise
|
|
1650
|
-
* the body / formData params are wrapped in a synthetic object.
|
|
2951
|
+
* Transform all OpenAPI schema to Base Schema
|
|
1651
2952
|
*/
|
|
2953
|
+
toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
|
|
2954
|
+
if (!schema) return { type: "unknown" };
|
|
2955
|
+
if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
|
|
2956
|
+
if (this.isOpenAPIArraySchema(schema)) {
|
|
2957
|
+
const { description, items, required } = schema;
|
|
2958
|
+
const rawType = schema.type;
|
|
2959
|
+
return {
|
|
2960
|
+
type: "array",
|
|
2961
|
+
nullable: Array.isArray(rawType) && rawType.includes("null"),
|
|
2962
|
+
required: !!required,
|
|
2963
|
+
description,
|
|
2964
|
+
items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
|
|
2965
|
+
};
|
|
2966
|
+
} else {
|
|
2967
|
+
const { required = [], allOf, anyOf, description, deprecated, discriminator, enum: enum_, format, oneOf, properties = {}, const: constValue, additionalProperties } = schema;
|
|
2968
|
+
const rawType = schema.type;
|
|
2969
|
+
const typeArray = Array.isArray(rawType) ? rawType.filter((t) => t !== "null") : void 0;
|
|
2970
|
+
let type = Array.isArray(rawType) ? typeArray?.[0] : schema.type;
|
|
2971
|
+
const nullableByType = Array.isArray(rawType) && rawType.includes("null");
|
|
2972
|
+
if (constValue !== void 0) return {
|
|
2973
|
+
type: typeof constValue === "number" ? "number" : typeof constValue === "boolean" ? "boolean" : "string",
|
|
2974
|
+
const: constValue,
|
|
2975
|
+
required,
|
|
2976
|
+
description,
|
|
2977
|
+
deprecated
|
|
2978
|
+
};
|
|
2979
|
+
if (enum_ && type !== "boolean") {
|
|
2980
|
+
const enumObject = {
|
|
2981
|
+
name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)) || `Enum${Base.upperCamelCase(Base.normalize(enum_.join("_")))}`,
|
|
2982
|
+
enum: [...new Set(enum_)]
|
|
2983
|
+
};
|
|
2984
|
+
const sameObject = Base.findSameSchema(enumObject, enums);
|
|
2985
|
+
if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
|
|
2986
|
+
return {
|
|
2987
|
+
type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
|
|
2988
|
+
nullable: nullableByType,
|
|
2989
|
+
required,
|
|
2990
|
+
description,
|
|
2991
|
+
deprecated
|
|
2992
|
+
};
|
|
2993
|
+
}
|
|
2994
|
+
if (type === void 0 && Object.keys(properties).length > 0) type = "object";
|
|
2995
|
+
return {
|
|
2996
|
+
type,
|
|
2997
|
+
types: typeArray,
|
|
2998
|
+
nullable: nullableByType,
|
|
2999
|
+
const: constValue,
|
|
3000
|
+
additionalProperties: additionalProperties && typeof additionalProperties === "object" ? this.toBaseSchema(additionalProperties, enums) : additionalProperties,
|
|
3001
|
+
required,
|
|
3002
|
+
description,
|
|
3003
|
+
deprecated,
|
|
3004
|
+
discriminator,
|
|
3005
|
+
enum: enum_,
|
|
3006
|
+
format,
|
|
3007
|
+
readOnly: schema.readOnly,
|
|
3008
|
+
writeOnly: schema.writeOnly,
|
|
3009
|
+
allOf: allOf?.map((s) => Base.isRef(s) ? {
|
|
3010
|
+
...s,
|
|
3011
|
+
ref: s.$ref,
|
|
3012
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
3013
|
+
} : this.toBaseSchema(s, enums)),
|
|
3014
|
+
anyOf: anyOf?.map((s) => Base.isRef(s) ? {
|
|
3015
|
+
...s,
|
|
3016
|
+
ref: s.$ref,
|
|
3017
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
3018
|
+
} : this.toBaseSchema(s, enums)),
|
|
3019
|
+
oneOf: oneOf?.map((s) => Base.isRef(s) ? {
|
|
3020
|
+
...s,
|
|
3021
|
+
ref: s.$ref,
|
|
3022
|
+
type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
|
|
3023
|
+
} : this.toBaseSchema(s, enums)),
|
|
3024
|
+
properties: Object.keys(properties).reduce((acc, p) => {
|
|
3025
|
+
const propSchema = properties[p];
|
|
3026
|
+
return {
|
|
3027
|
+
...acc,
|
|
3028
|
+
[p]: Base.isRef(propSchema) ? {
|
|
3029
|
+
type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
|
|
3030
|
+
isRef: true
|
|
3031
|
+
} : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
|
|
3032
|
+
};
|
|
3033
|
+
}, {})
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
1652
3037
|
init() {
|
|
1653
|
-
const { paths = {} } = this.doc;
|
|
3038
|
+
const { components = {}, paths = {}, security = [] } = this.doc;
|
|
1654
3039
|
const enums = [];
|
|
1655
|
-
const
|
|
1656
|
-
const
|
|
1657
|
-
|
|
1658
|
-
const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
|
|
1659
|
-
const schema = schemaContainer[key];
|
|
3040
|
+
const { requestBodies = {}, responses = {}, parameters = {}, schemas = {}, securitySchemes = {} } = components;
|
|
3041
|
+
const schemas_ = Object.keys(schemas).reduce((acc, key) => {
|
|
3042
|
+
const schema = schemas[key];
|
|
1660
3043
|
return {
|
|
1661
3044
|
...acc,
|
|
1662
3045
|
[key]: this.getSchemaByRef(schema, false, enums, key)
|
|
1663
3046
|
};
|
|
1664
3047
|
}, {});
|
|
1665
|
-
const parameters_ = Object.keys(
|
|
1666
|
-
const parameter =
|
|
3048
|
+
const parameters_ = Object.keys(parameters).reduce((acc, key) => {
|
|
3049
|
+
const parameter = parameters[key];
|
|
1667
3050
|
return {
|
|
1668
3051
|
...acc,
|
|
1669
3052
|
[key]: this.getParameterByRef(parameter, enums, key)
|
|
1670
3053
|
};
|
|
1671
3054
|
}, {});
|
|
1672
|
-
const responses_ = Object.keys(
|
|
1673
|
-
const response =
|
|
3055
|
+
const responses_ = Object.keys(responses).reduce((acc, key) => {
|
|
3056
|
+
const response = responses[key];
|
|
3057
|
+
return {
|
|
3058
|
+
...acc,
|
|
3059
|
+
[key]: this.getResponseByRef(response, enums)
|
|
3060
|
+
};
|
|
3061
|
+
}, {});
|
|
3062
|
+
const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
|
|
3063
|
+
const requestBody = requestBodies[key];
|
|
1674
3064
|
return {
|
|
1675
3065
|
...acc,
|
|
1676
|
-
[key]: this.
|
|
3066
|
+
[key]: this.getRequestBodyByRef(requestBody, enums)
|
|
1677
3067
|
};
|
|
1678
3068
|
}, {});
|
|
1679
|
-
const apis = {
|
|
1680
|
-
for (const path of Object.keys(paths)) {
|
|
3069
|
+
const apis = Object.keys(paths).reduce((acc, path) => {
|
|
1681
3070
|
let pathObject = paths[path] ?? {};
|
|
1682
3071
|
if (pathObject.$ref) {
|
|
1683
3072
|
const resolved = this.resolvePathRef(pathObject.$ref);
|
|
1684
3073
|
if (resolved) pathObject = resolved;
|
|
1685
3074
|
}
|
|
1686
|
-
const { parameters = [] } = pathObject;
|
|
3075
|
+
const { parameters = [], description, summary } = pathObject;
|
|
1687
3076
|
const methodApis = [];
|
|
1688
3077
|
Object.values(HttpMethods).forEach((method) => {
|
|
1689
3078
|
const methodObject = pathObject[method];
|
|
1690
|
-
if (
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
for (const code of httpCodes) if (code in responsesClone) {
|
|
1701
|
-
const response = responsesClone[code];
|
|
1702
|
-
const responseSchema = this.getResponseByRef(response);
|
|
1703
|
-
const inBodyOnlyHasBody = inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
|
|
3079
|
+
if (methodObject) {
|
|
3080
|
+
const { deprecated, operationId, summary: summary_, description: description_, responses = {}, requestBody = { content: {} } } = methodObject;
|
|
3081
|
+
const { parameters: parameters_ = [] } = methodObject;
|
|
3082
|
+
const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
|
|
3083
|
+
const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
|
|
3084
|
+
const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
|
|
3085
|
+
if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
|
|
3086
|
+
const httpCodes = Object.keys(responses).filter((code) => code in responses);
|
|
3087
|
+
const responseTypes = Object.fromEntries(httpCodes.map((code) => [code, this.getResponseByRef(responses[code], enums)]));
|
|
3088
|
+
const successCode = httpCodes.find((code) => /^2\d\d$/.test(code)) ?? httpCodes[0];
|
|
1704
3089
|
methodApis.push({
|
|
1705
3090
|
method,
|
|
1706
3091
|
operationId,
|
|
1707
|
-
summary: summary_,
|
|
3092
|
+
summary: summary_ ?? summary,
|
|
3093
|
+
description: description_ ?? description,
|
|
1708
3094
|
deprecated,
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
}] : [{
|
|
1716
|
-
type: "application/json",
|
|
1717
|
-
schema: {
|
|
1718
|
-
type: "object",
|
|
1719
|
-
properties: inBody.reduce((a, p) => {
|
|
1720
|
-
return {
|
|
1721
|
-
...a,
|
|
1722
|
-
[p.name]: {
|
|
1723
|
-
type: p.schema?.type ?? "unknown",
|
|
1724
|
-
required: p.schema?.required,
|
|
1725
|
-
items: p.schema?.items,
|
|
1726
|
-
description: p.schema?.description
|
|
1727
|
-
}
|
|
1728
|
-
};
|
|
1729
|
-
}, {})
|
|
1730
|
-
}
|
|
1731
|
-
}] : void 0
|
|
3095
|
+
parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
|
|
3096
|
+
responses: responseTypes[successCode] ?? [],
|
|
3097
|
+
responseTypes,
|
|
3098
|
+
tags: methodObject.tags,
|
|
3099
|
+
security: methodObject.security ?? security,
|
|
3100
|
+
requestBody: baseRequestBody
|
|
1732
3101
|
});
|
|
1733
|
-
break;
|
|
1734
3102
|
}
|
|
1735
3103
|
});
|
|
1736
|
-
|
|
1737
|
-
|
|
3104
|
+
return {
|
|
3105
|
+
...acc,
|
|
3106
|
+
[path]: methodApis
|
|
3107
|
+
};
|
|
3108
|
+
}, {});
|
|
1738
3109
|
return {
|
|
1739
3110
|
enums: Base.uniqueEnums(enums),
|
|
1740
3111
|
schemas: schemas_,
|
|
1741
3112
|
responses: responses_,
|
|
1742
3113
|
parameters: parameters_,
|
|
1743
|
-
requestBodies:
|
|
3114
|
+
requestBodies: requestBodies_,
|
|
3115
|
+
securitySchemes,
|
|
1744
3116
|
apis
|
|
1745
3117
|
};
|
|
1746
3118
|
}
|
|
1747
3119
|
};
|
|
1748
|
-
|
|
1749
|
-
//#region src/openapi/V3.ts
|
|
1750
|
-
var V3 = class extends VersionedProvider {
|
|
1751
|
-
doc;
|
|
1752
|
-
version = "v3";
|
|
1753
|
-
constructor(doc) {
|
|
1754
|
-
super();
|
|
1755
|
-
this.doc = doc;
|
|
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
|
-
//#region src/openapi/V3_1.ts
|
|
1772
|
-
var V3_1 = class extends VersionedProvider {
|
|
1773
|
-
doc;
|
|
1774
|
-
version = "v3_1";
|
|
1775
|
-
constructor(doc) {
|
|
1776
|
-
super();
|
|
1777
|
-
this.doc = doc;
|
|
1778
|
-
}
|
|
1779
|
-
formatRefName(name) {
|
|
1780
|
-
return Base.upperCamelCase(name);
|
|
1781
|
-
}
|
|
1782
|
-
getSchemaContainer() {
|
|
1783
|
-
return this.doc.components?.schemas;
|
|
1784
|
-
}
|
|
1785
|
-
getParameterContainer() {
|
|
1786
|
-
return this.doc.components?.parameters;
|
|
1787
|
-
}
|
|
1788
|
-
getResponseContainer() {
|
|
1789
|
-
return this.doc.components?.responses;
|
|
1790
|
-
}
|
|
1791
|
-
getRequestBodyContainer() {
|
|
1792
|
-
return this.doc.components?.requestBodies;
|
|
1793
|
-
}
|
|
1794
|
-
};
|
|
1795
|
-
//#endregion
|
|
1796
|
-
//#region src/openapi/index.ts
|
|
3120
|
+
// src/openapi/index.ts
|
|
1797
3121
|
const logger$1 = (0, _moccona_logger.createScopedLogger)("OpenAPI");
|
|
1798
3122
|
let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
1799
3123
|
OpenAPIVersion["v2"] = "v2";
|
|
@@ -1803,7 +3127,9 @@ let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
|
|
|
1803
3127
|
return OpenAPIVersion;
|
|
1804
3128
|
}({});
|
|
1805
3129
|
function getDocVersion(doc) {
|
|
1806
|
-
|
|
3130
|
+
const raw = doc.openapi || doc.swagger;
|
|
3131
|
+
if (typeof raw !== "string" || raw.length === 0) return "unknown";
|
|
3132
|
+
switch (raw.slice(0, 3)) {
|
|
1807
3133
|
case "3.1": return "v3_1";
|
|
1808
3134
|
case "3.0": return "v3";
|
|
1809
3135
|
case "2.0": return "v2";
|
|
@@ -1828,92 +3154,170 @@ function getAdaptor(type) {
|
|
|
1828
3154
|
default: return new FetchAdapter();
|
|
1829
3155
|
}
|
|
1830
3156
|
}
|
|
3157
|
+
/**
|
|
3158
|
+
* Use the document's first server when the caller did not configure a base URL.
|
|
3159
|
+
* Server variables fall back to their declared defaults.
|
|
3160
|
+
*/
|
|
3161
|
+
function inferBaseURL(doc) {
|
|
3162
|
+
const server = doc.servers?.[0];
|
|
3163
|
+
if (server?.url) return server.url.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
3164
|
+
return server.variables?.[name]?.default ?? `{${name}}`;
|
|
3165
|
+
}).replace(/\/+$/, "");
|
|
3166
|
+
const v2 = doc;
|
|
3167
|
+
if (v2.host) return `${v2.schemes?.[0] ?? "https"}://${v2.host}${(v2.basePath ?? "").replace(/\/+$/, "")}`;
|
|
3168
|
+
}
|
|
1831
3169
|
async function codeGen(initOptions) {
|
|
1832
3170
|
const startTime = Date.now();
|
|
1833
3171
|
const { verbose } = initOptions;
|
|
1834
3172
|
if (verbose) logger$1.setLevel("debug");
|
|
1835
3173
|
else logger$1.setLevel("info");
|
|
1836
3174
|
logger$1.info(`Fetch document from ${initOptions.docURL}`);
|
|
1837
|
-
const {
|
|
3175
|
+
const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
|
|
3176
|
+
const rawDoc = transport === "file" ? await (async () => {
|
|
3177
|
+
let raw;
|
|
3178
|
+
try {
|
|
3179
|
+
raw = await (0, node_fs_promises.readFile)(source, "utf8");
|
|
3180
|
+
} catch (error) {
|
|
3181
|
+
if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
|
|
3182
|
+
throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3183
|
+
}
|
|
3184
|
+
return Base.parseDoc(raw, source);
|
|
3185
|
+
})() : await Base.fetchDoc(source, initOptions.requestOptions);
|
|
3186
|
+
const doc = await Base.bundleExternalRefs(rawDoc, source, initOptions.requestOptions);
|
|
3187
|
+
const options = {
|
|
3188
|
+
...initOptions,
|
|
3189
|
+
baseURL: initOptions.baseURL ?? inferBaseURL(doc)
|
|
3190
|
+
};
|
|
3191
|
+
const { enums, schemas, parameters, responses, requestBodies, securitySchemes, apis } = new OpenAPIProvider(options, doc);
|
|
1838
3192
|
const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
|
|
1839
|
-
const
|
|
3193
|
+
const split = splitReadWrite({
|
|
1840
3194
|
enums,
|
|
1841
3195
|
schemas,
|
|
1842
3196
|
parameters,
|
|
1843
3197
|
responses,
|
|
1844
3198
|
requestBodies,
|
|
3199
|
+
securitySchemes,
|
|
1845
3200
|
apis
|
|
1846
|
-
}
|
|
1847
|
-
|
|
3201
|
+
});
|
|
3202
|
+
const parsed = {
|
|
3203
|
+
...split,
|
|
3204
|
+
apis: filterApis(split.apis, options)
|
|
3205
|
+
};
|
|
3206
|
+
const multi = initOptions.splitBy === "tag" ? await Generator.genCodeMulti(parsed, options, adaptor) : void 0;
|
|
3207
|
+
const code = multi?.code ?? await Generator.genCode(parsed, options, adaptor);
|
|
3208
|
+
if (initOptions.output) {
|
|
3209
|
+
if (multi) for (const [name, content] of Object.entries(multi.files)) await Generator.write(content, (0, node_path.join)(initOptions.output, name));
|
|
3210
|
+
else await Generator.write(code, initOptions.output);
|
|
3211
|
+
}
|
|
1848
3212
|
const duration = Date.now() - startTime;
|
|
3213
|
+
const endpoints = Object.keys(apis).length;
|
|
3214
|
+
const schemasCount = Object.keys(schemas).length;
|
|
1849
3215
|
return {
|
|
1850
3216
|
code,
|
|
3217
|
+
...multi ? { files: multi.files } : {},
|
|
1851
3218
|
stats: {
|
|
1852
|
-
endpoints
|
|
1853
|
-
schemas:
|
|
3219
|
+
endpoints,
|
|
3220
|
+
schemas: schemasCount,
|
|
1854
3221
|
duration
|
|
1855
3222
|
}
|
|
1856
3223
|
};
|
|
1857
3224
|
}
|
|
1858
|
-
|
|
1859
|
-
//#region src/vite-plugin/index.ts
|
|
1860
|
-
const PLUGIN_NAME = "api-code-gen";
|
|
1861
|
-
const pluginLogger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
|
|
3225
|
+
// src/core/typecheck.ts
|
|
1862
3226
|
/**
|
|
1863
|
-
*
|
|
1864
|
-
*
|
|
1865
|
-
*
|
|
3227
|
+
* Type-check a generated file with the project's TypeScript.
|
|
3228
|
+
*
|
|
3229
|
+
* @param filePath - Path to the generated file.
|
|
3230
|
+
* @returns Collected error messages; an empty array means success.
|
|
1866
3231
|
*/
|
|
1867
|
-
async function
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
const configPath = node_path.default.join(dir, name);
|
|
1874
|
-
if (await fs_extra.default.pathExists(configPath)) return configPath;
|
|
1875
|
-
}
|
|
1876
|
-
if (dir === rootDir || dir === fsRoot) break;
|
|
1877
|
-
dir = node_path.default.dirname(dir);
|
|
3232
|
+
async function runTypeCheck(filePath) {
|
|
3233
|
+
try {
|
|
3234
|
+
await (0, execa.execaCommand)(`npx tsc ${filePath} --noEmit`, { shell: true });
|
|
3235
|
+
return [];
|
|
3236
|
+
} catch (error) {
|
|
3237
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
1878
3238
|
}
|
|
1879
|
-
return null;
|
|
1880
3239
|
}
|
|
3240
|
+
// package.json
|
|
3241
|
+
var version = "1.0.0";
|
|
3242
|
+
// src/vite-plugin/cache.ts
|
|
1881
3243
|
/**
|
|
1882
|
-
*
|
|
3244
|
+
* Cache for a single vite-plugin codegen run. Lives only for the duration
|
|
3245
|
+
* of one plugin invocation — there is no module-level state.
|
|
3246
|
+
*
|
|
3247
|
+
* Cache files are stored at:
|
|
3248
|
+
*
|
|
3249
|
+
* <cacheDir>/<optionsHash>.json
|
|
3250
|
+
*
|
|
3251
|
+
* where `<cacheDir>` defaults to `node_modules/.cache/apicodegen` but can
|
|
3252
|
+
* be overridden via `cacheDir`.
|
|
1883
3253
|
*/
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
3254
|
+
var CodegenCache = class CodegenCache {
|
|
3255
|
+
cacheDir;
|
|
3256
|
+
constructor(cacheDir) {
|
|
3257
|
+
this.cacheDir = cacheDir;
|
|
3258
|
+
}
|
|
3259
|
+
/** Hash the options that affect generated output (excluding the spec). */
|
|
3260
|
+
static hashOptions(options) {
|
|
3261
|
+
const keys = Object.keys(options).sort();
|
|
3262
|
+
const payload = [`generatorVersion=${version}`, ...keys.filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`)].join("|");
|
|
3263
|
+
return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
|
|
3264
|
+
}
|
|
3265
|
+
/** Hash the raw spec content so unrelated edits are detected. */
|
|
3266
|
+
static hashContent(content) {
|
|
3267
|
+
return (0, node_crypto.createHash)("sha256").update(content).digest("hex").slice(0, 16);
|
|
3268
|
+
}
|
|
3269
|
+
/**
|
|
3270
|
+
* Look up a cached entry. Returns `null` on miss / corruption / disabled.
|
|
3271
|
+
*
|
|
3272
|
+
* @param optionsHash Options hash from `hashOptions`.
|
|
3273
|
+
* @param specSource Resolved spec path or URL. Local paths use mtime +
|
|
3274
|
+
* content hash; URLs always miss (no cache).
|
|
3275
|
+
*/
|
|
3276
|
+
async lookup(optionsHash, specSource) {
|
|
3277
|
+
const cachePath = node_path.default.join(this.cacheDir, `${optionsHash}.json`);
|
|
3278
|
+
let raw;
|
|
1890
3279
|
try {
|
|
1891
|
-
await
|
|
1892
|
-
} catch
|
|
1893
|
-
|
|
3280
|
+
raw = await (0, node_fs_promises.readFile)(cachePath, "utf8");
|
|
3281
|
+
} catch {
|
|
3282
|
+
return null;
|
|
1894
3283
|
}
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
};
|
|
1905
|
-
try {
|
|
1906
|
-
await fs_extra.default.writeJson(tempConfigPath, tempConfig);
|
|
1907
|
-
await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
|
|
1908
|
-
} catch (error) {
|
|
1909
|
-
if (error instanceof Error) errors.push(error.message);
|
|
1910
|
-
} finally {
|
|
3284
|
+
let entry;
|
|
3285
|
+
try {
|
|
3286
|
+
entry = JSON.parse(raw);
|
|
3287
|
+
} catch {
|
|
3288
|
+
return null;
|
|
3289
|
+
}
|
|
3290
|
+
if (entry.optionsHash !== optionsHash) return null;
|
|
3291
|
+
if (specSource.startsWith("http://") || specSource.startsWith("https://")) return null;
|
|
3292
|
+
let currentMtimeMs;
|
|
1911
3293
|
try {
|
|
1912
|
-
await
|
|
1913
|
-
} catch {
|
|
3294
|
+
currentMtimeMs = (await (0, node_fs_promises.stat)(specSource)).mtimeMs;
|
|
3295
|
+
} catch {
|
|
3296
|
+
return null;
|
|
3297
|
+
}
|
|
3298
|
+
if (currentMtimeMs !== entry.specMtimeMs) return null;
|
|
3299
|
+
if (entry.specContentHash) {
|
|
3300
|
+
let content;
|
|
3301
|
+
try {
|
|
3302
|
+
content = await (0, node_fs_promises.readFile)(specSource, "utf8");
|
|
3303
|
+
} catch {
|
|
3304
|
+
return null;
|
|
3305
|
+
}
|
|
3306
|
+
if (CodegenCache.hashContent(content) !== entry.specContentHash) return null;
|
|
3307
|
+
}
|
|
3308
|
+
return entry;
|
|
1914
3309
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
3310
|
+
/** Persist a successful codegen result. */
|
|
3311
|
+
async store(entry) {
|
|
3312
|
+
const cachePath = node_path.default.join(this.cacheDir, `${entry.optionsHash}.json`);
|
|
3313
|
+
const dir = node_path.default.dirname(cachePath);
|
|
3314
|
+
await import("fs-extra").then((fs) => fs.ensureDir(dir));
|
|
3315
|
+
await (0, node_fs_promises.writeFile)(cachePath, JSON.stringify(entry));
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
// src/vite-plugin/index.ts
|
|
3319
|
+
const PLUGIN_NAME = "api-code-gen";
|
|
3320
|
+
const logger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
|
|
1917
3321
|
/**
|
|
1918
3322
|
* Validate spec path exists
|
|
1919
3323
|
*/
|
|
@@ -1923,13 +3327,19 @@ async function validateSpecPath(specPath) {
|
|
|
1923
3327
|
const absolutePath = node_path.default.isAbsolute(filePath) ? filePath : node_path.default.resolve(process.cwd(), filePath);
|
|
1924
3328
|
if (!await fs_extra.default.pathExists(absolutePath)) throw createErrors.specNotFound(absolutePath);
|
|
1925
3329
|
}
|
|
3330
|
+
/** Resolve a local spec to an absolute path; remote specs return null. */
|
|
3331
|
+
function toWatchPath(spec) {
|
|
3332
|
+
if (!spec || spec.startsWith("http://") || spec.startsWith("https://")) return null;
|
|
3333
|
+
const filePath = spec.replace(/^file:\/\//, "");
|
|
3334
|
+
return node_path.default.isAbsolute(filePath) ? filePath : node_path.default.resolve(process.cwd(), filePath);
|
|
3335
|
+
}
|
|
1926
3336
|
/**
|
|
1927
3337
|
* Generate code for a single API configuration
|
|
1928
3338
|
*/
|
|
1929
3339
|
async function generateForOption(option) {
|
|
1930
|
-
const { name, typeCheck = true, verbose, ...restOptions } = option;
|
|
3340
|
+
const { name, typeCheck = true, verbose, cache = true, cacheDir, ...restOptions } = option;
|
|
1931
3341
|
try {
|
|
1932
|
-
|
|
3342
|
+
console.log(`\x1b[36m├─\x1b[0m ${name}`);
|
|
1933
3343
|
const config = await loadConfig({
|
|
1934
3344
|
name,
|
|
1935
3345
|
cliOptions: {
|
|
@@ -1938,30 +3348,82 @@ async function generateForOption(option) {
|
|
|
1938
3348
|
}
|
|
1939
3349
|
});
|
|
1940
3350
|
await validateSpecPath(config.spec);
|
|
1941
|
-
if (config.output) {
|
|
1942
|
-
const outputDir = node_path.default.dirname(config.output);
|
|
1943
|
-
await fs_extra.default.ensureDir(outputDir);
|
|
1944
|
-
}
|
|
1945
3351
|
let docURL = config.spec;
|
|
1946
|
-
if (!docURL.startsWith("http://") && !docURL.startsWith("https://")
|
|
1947
|
-
|
|
1948
|
-
const
|
|
1949
|
-
|
|
1950
|
-
|
|
3352
|
+
if (!docURL.startsWith("http://") && !docURL.startsWith("https://") && !docURL.startsWith("file://") && !docURL.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(docURL)) docURL = node_path.default.resolve(process.cwd(), docURL);
|
|
3353
|
+
const resolvedCacheDir = cacheDir ?? node_path.default.join(process.cwd(), "node_modules", ".cache", "apicodegen");
|
|
3354
|
+
const codegenCache = cache && !config.splitBy ? new CodegenCache(resolvedCacheDir) : null;
|
|
3355
|
+
const optionsHash = CodegenCache.hashOptions({
|
|
3356
|
+
name,
|
|
3357
|
+
spec: docURL,
|
|
3358
|
+
output: config.output,
|
|
3359
|
+
adaptor: config.adaptor,
|
|
3360
|
+
errorMode: config.errorMode,
|
|
3361
|
+
splitBy: config.splitBy,
|
|
3362
|
+
includeTags: config.includeTags,
|
|
3363
|
+
excludeTags: config.excludeTags,
|
|
3364
|
+
includePaths: config.includePaths,
|
|
3365
|
+
excludePaths: config.excludePaths,
|
|
3366
|
+
baseURL: config.baseURL,
|
|
3367
|
+
importClientSource: config.importClientSource
|
|
1951
3368
|
});
|
|
1952
|
-
|
|
3369
|
+
let result = null;
|
|
3370
|
+
let cached = false;
|
|
3371
|
+
if (codegenCache) {
|
|
3372
|
+
const cachedEntry = await codegenCache.lookup(optionsHash, docURL);
|
|
3373
|
+
if (cachedEntry) {
|
|
3374
|
+
result = {
|
|
3375
|
+
code: cachedEntry.code,
|
|
3376
|
+
stats: cachedEntry.stats
|
|
3377
|
+
};
|
|
3378
|
+
cached = true;
|
|
3379
|
+
if (verbose) logger.debug(`Cache hit for ${name} (${optionsHash})`);
|
|
3380
|
+
}
|
|
3381
|
+
}
|
|
3382
|
+
if (!result) {
|
|
3383
|
+
result = await codeGen({
|
|
3384
|
+
...toProviderOptions(config),
|
|
3385
|
+
docURL
|
|
3386
|
+
});
|
|
3387
|
+
if (codegenCache) try {
|
|
3388
|
+
const fsPromises = await import("node:fs/promises");
|
|
3389
|
+
let specMtimeMs;
|
|
3390
|
+
let specContentHash;
|
|
3391
|
+
if (!(docURL.startsWith("http://") || docURL.startsWith("https://"))) try {
|
|
3392
|
+
specMtimeMs = (await fsPromises.stat(docURL)).mtimeMs;
|
|
3393
|
+
const content = await fsPromises.readFile(docURL, "utf8");
|
|
3394
|
+
specContentHash = CodegenCache.hashContent(content);
|
|
3395
|
+
} catch {}
|
|
3396
|
+
await codegenCache.store({
|
|
3397
|
+
optionsHash,
|
|
3398
|
+
specMtimeMs,
|
|
3399
|
+
specContentHash,
|
|
3400
|
+
code: result.code,
|
|
3401
|
+
stats: result.stats
|
|
3402
|
+
});
|
|
3403
|
+
} catch (cacheError) {
|
|
3404
|
+
if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
if (config.output) {
|
|
3408
|
+
if (result.files) {
|
|
3409
|
+
const dir = node_path.default.dirname(config.output);
|
|
3410
|
+
for (const [name, content] of Object.entries(result.files)) if (name !== "index.ts") await fs_extra.default.outputFile(node_path.default.join(dir, name), content);
|
|
3411
|
+
}
|
|
3412
|
+
await fs_extra.default.outputFile(config.output, result.code);
|
|
3413
|
+
}
|
|
1953
3414
|
if (typeCheck && config.output) {
|
|
1954
3415
|
const typeErrors = await runTypeCheck(config.output);
|
|
1955
3416
|
if (typeErrors.length > 0) {
|
|
1956
|
-
|
|
1957
|
-
if (verbose) for (const error of typeErrors)
|
|
3417
|
+
logger.warn(`Type check failed for ${config.output}`);
|
|
3418
|
+
if (verbose) for (const error of typeErrors) logger.warn(` ${error}`);
|
|
1958
3419
|
}
|
|
1959
3420
|
}
|
|
1960
3421
|
return {
|
|
1961
3422
|
success: true,
|
|
1962
3423
|
name,
|
|
1963
3424
|
output: config.output,
|
|
1964
|
-
stats: result.stats
|
|
3425
|
+
stats: result.stats,
|
|
3426
|
+
cached
|
|
1965
3427
|
};
|
|
1966
3428
|
} catch (error) {
|
|
1967
3429
|
return {
|
|
@@ -1995,52 +3457,75 @@ async function generateForOption(option) {
|
|
|
1995
3457
|
*/
|
|
1996
3458
|
function apiCodeGenPlugin(options) {
|
|
1997
3459
|
if (!Array.isArray(options) || options.length === 0) {
|
|
1998
|
-
|
|
3460
|
+
logger.warn("No API configurations provided to apiCodeGenPlugin");
|
|
1999
3461
|
return { name: PLUGIN_NAME };
|
|
2000
3462
|
}
|
|
3463
|
+
let mode = "unknown";
|
|
3464
|
+
const watched = /* @__PURE__ */ new Set();
|
|
3465
|
+
const printResults = (results) => {
|
|
3466
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3467
|
+
console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
|
|
3468
|
+
console.log(`\x1b[90mMode:\x1b[0m ${mode}`);
|
|
3469
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3470
|
+
const successCount = results.filter((r) => r.success).length;
|
|
3471
|
+
const failCount = results.length - successCount;
|
|
3472
|
+
for (const result of results) if (result.success) {
|
|
3473
|
+
const { name, output, stats, cached } = result;
|
|
3474
|
+
if (stats) {
|
|
3475
|
+
const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
|
|
3476
|
+
console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
|
|
3477
|
+
} else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
|
|
3478
|
+
} else {
|
|
3479
|
+
const { name, error } = result;
|
|
3480
|
+
const wrapped = isApicodegenError(error) ? error : wrapError(error, {
|
|
3481
|
+
code: "E_GENERATION_FAILED",
|
|
3482
|
+
message: `Failed to generate API "${name}"`
|
|
3483
|
+
});
|
|
3484
|
+
console.log(`\x1b[31m✗\x1b[0m ${name}`);
|
|
3485
|
+
console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
|
|
3486
|
+
}
|
|
3487
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3488
|
+
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
3489
|
+
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
3490
|
+
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
3491
|
+
if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${results.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
|
|
3492
|
+
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)`);
|
|
3493
|
+
console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
|
|
3494
|
+
};
|
|
3495
|
+
const regenerate = async (option) => {
|
|
3496
|
+
const result = await generateForOption(option);
|
|
3497
|
+
printResults([result]);
|
|
3498
|
+
};
|
|
2001
3499
|
return {
|
|
2002
3500
|
name: PLUGIN_NAME,
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
const results = await Promise.all(options.map(generateForOption));
|
|
2006
|
-
const successCount = results.filter((r) => r.success).length;
|
|
2007
|
-
const failCount = options.length - successCount;
|
|
2008
|
-
logger.divider();
|
|
2009
|
-
for (const result of results) if (result.success) {
|
|
2010
|
-
const { name, output, stats } = result;
|
|
2011
|
-
if (stats) logger.item(`${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms`, "green");
|
|
2012
|
-
else logger.item(`${name} → ${output || "N/A"}`, "green");
|
|
2013
|
-
} else {
|
|
2014
|
-
const { name, error } = result;
|
|
2015
|
-
if (isApicodegenError(error)) {
|
|
2016
|
-
logger.item(name, "red");
|
|
2017
|
-
logger.error(error, true);
|
|
2018
|
-
} else {
|
|
2019
|
-
const wrapped = wrapError(error, {
|
|
2020
|
-
code: ErrorCodes.GENERATION_FAILED,
|
|
2021
|
-
message: `Failed to generate API "${name}"`
|
|
2022
|
-
});
|
|
2023
|
-
logger.item(name, "red");
|
|
2024
|
-
logger.error(wrapped, true);
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
logger.divider();
|
|
2028
|
-
const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
|
|
2029
|
-
const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
|
|
2030
|
-
const totalSchemas = results.reduce((sum, r) => sum + (r.stats?.schemas || 0), 0);
|
|
2031
|
-
logger.summary({
|
|
2032
|
-
succeeded: successCount,
|
|
2033
|
-
failed: failCount,
|
|
2034
|
-
endpoints: totalEndpoints,
|
|
2035
|
-
schemas: totalSchemas,
|
|
2036
|
-
duration: totalDuration
|
|
2037
|
-
});
|
|
2038
|
-
logger.divider();
|
|
3501
|
+
config(_config, env) {
|
|
3502
|
+
mode = env?.command || "unknown";
|
|
2039
3503
|
return {};
|
|
3504
|
+
},
|
|
3505
|
+
async buildStart() {
|
|
3506
|
+
for (const option of options) {
|
|
3507
|
+
const specPath = toWatchPath(option.spec);
|
|
3508
|
+
if (specPath) this.addWatchFile(specPath);
|
|
3509
|
+
}
|
|
3510
|
+
printResults(await Promise.all(options.map(generateForOption)));
|
|
3511
|
+
},
|
|
3512
|
+
configureServer(server) {
|
|
3513
|
+
for (const option of options) {
|
|
3514
|
+
const specPath = toWatchPath(option.spec);
|
|
3515
|
+
if (!specPath || watched.has(specPath)) continue;
|
|
3516
|
+
watched.add(specPath);
|
|
3517
|
+
server.watcher.add(specPath);
|
|
3518
|
+
const onChange = async (changed) => {
|
|
3519
|
+
if (node_path.default.resolve(changed) !== node_path.default.resolve(specPath)) return;
|
|
3520
|
+
await regenerate(option);
|
|
3521
|
+
server.ws.send({ type: "full-reload" });
|
|
3522
|
+
};
|
|
3523
|
+
server.watcher.on("change", onChange);
|
|
3524
|
+
server.watcher.on("add", onChange);
|
|
3525
|
+
}
|
|
2040
3526
|
}
|
|
2041
3527
|
};
|
|
2042
3528
|
}
|
|
2043
|
-
//#endregion
|
|
2044
3529
|
exports.Adapter = Adapter;
|
|
2045
3530
|
exports.Adaptors = Adaptors;
|
|
2046
3531
|
exports.ApicodegenError = ApicodegenError;
|
|
@@ -2062,14 +3547,24 @@ exports.SchemaFormatType = SchemaFormatType;
|
|
|
2062
3547
|
exports.SchemaType = SchemaType;
|
|
2063
3548
|
exports.SuccessHttpStatusCode = SuccessHttpStatusCode;
|
|
2064
3549
|
exports.apiCodeGenPlugin = apiCodeGenPlugin;
|
|
3550
|
+
exports.authAccess = authAccess;
|
|
3551
|
+
exports.authHeaderEntries = authHeaderEntries;
|
|
2065
3552
|
exports.codeGen = codeGen;
|
|
3553
|
+
exports.configToCLIOptions = configToCLIOptions;
|
|
3554
|
+
exports.cookieHeaderExpression = cookieHeaderExpression;
|
|
2066
3555
|
exports.createErrors = createErrors;
|
|
3556
|
+
exports.fetchSignalExpression = fetchSignalExpression;
|
|
2067
3557
|
exports.formatError = formatError;
|
|
2068
3558
|
exports.isApicodegenError = isApicodegenError;
|
|
2069
3559
|
exports.loadConfig = loadConfig;
|
|
2070
|
-
exports.
|
|
3560
|
+
exports.loadConfigs = loadConfigs;
|
|
3561
|
+
exports.mergeConfigs = mergeConfigs;
|
|
3562
|
+
exports.optionalAccess = optionalAccess;
|
|
2071
3563
|
exports.printError = printError;
|
|
2072
3564
|
exports.toProviderOptions = toProviderOptions;
|
|
3565
|
+
exports.validateConfig = validateConfig;
|
|
3566
|
+
exports.validateConfigShape = validateConfigShape;
|
|
3567
|
+
exports.withRequestHeaders = withRequestHeaders;
|
|
2073
3568
|
exports.wrapError = wrapError;
|
|
2074
3569
|
|
|
2075
3570
|
//# sourceMappingURL=index.cjs.map
|