@moccona/apicodegen 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/npm/index.cjs CHANGED
@@ -21,15 +21,16 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
+ let node_fs_promises = require("node:fs/promises");
24
25
  let undici = require("undici");
25
26
  let typescript = require("typescript");
26
- let node_fs_promises = require("node:fs/promises");
27
27
  let prettier = require("prettier");
28
28
  let node_path = require("node:path");
29
29
  node_path = __toESM(node_path, 1);
30
30
  let fs_extra = require("fs-extra");
31
31
  fs_extra = __toESM(fs_extra, 1);
32
32
  let _moccona_logger = require("@moccona/logger");
33
+ let node_crypto = require("node:crypto");
33
34
  //#region src/core/base/Adaptor.ts
34
35
  /**
35
36
  * Base adapter for tool
@@ -115,6 +116,251 @@ const typescriptKeywords = new Set([
115
116
  "bigint"
116
117
  ]);
117
118
  //#endregion
119
+ //#region src/core/errors.ts
120
+ /**
121
+ * Error handling utilities for api-codegen
122
+ */
123
+ const ErrorCodes = {
124
+ SPEC_NOT_FOUND: "E_SPEC_NOT_FOUND",
125
+ SPEC_FETCH_FAILED: "E_SPEC_FETCH_FAILED",
126
+ SPEC_PARSE_FAILED: "E_SPEC_PARSE_FAILED",
127
+ OUTPUT_DIR_MISSING: "E_OUTPUT_DIR_MISSING",
128
+ CONFIG_INVALID: "E_CONFIG_INVALID",
129
+ VALIDATION_FAILED: "E_VALIDATION_FAILED",
130
+ GENERATION_FAILED: "E_GENERATION_FAILED",
131
+ TYPE_CHECK_FAILED: "E_TYPE_CHECK_FAILED"
132
+ };
133
+ /**
134
+ * Custom error class for api-codegen with rich context
135
+ */
136
+ var ApicodegenError = class ApicodegenError extends Error {
137
+ code;
138
+ location;
139
+ line;
140
+ column;
141
+ path;
142
+ suggestions;
143
+ cause;
144
+ constructor(context) {
145
+ super(context.message);
146
+ this.name = "ApicodegenError";
147
+ this.code = context.code;
148
+ this.location = context.location;
149
+ this.line = context.line;
150
+ this.column = context.column;
151
+ this.path = context.path;
152
+ this.suggestions = context.suggestions || [];
153
+ this.cause = context.cause;
154
+ if (Error.captureStackTrace) Error.captureStackTrace(this, ApicodegenError);
155
+ }
156
+ /**
157
+ * Convert error to formatted string for CLI output
158
+ */
159
+ toString(verbose = false) {
160
+ const lines = [];
161
+ lines.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`);
162
+ if (this.location) lines.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`);
163
+ if (this.path) lines.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`);
164
+ if (this.line !== void 0) {
165
+ let lineInfo = ` \x1b[36m→ Line:\x1b[0m ${this.line}`;
166
+ if (this.column !== void 0) lineInfo += `, Column: ${this.column}`;
167
+ lines.push(lineInfo);
168
+ }
169
+ if (this.suggestions.length > 0) for (const suggestion of this.suggestions) lines.push(` \x1b[32m→ Suggestion:\x1b[0m ${suggestion}`);
170
+ if (verbose && this.cause) {
171
+ lines.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`);
172
+ if (this.stack) {
173
+ const stackLines = this.stack.split("\n").slice(1).join("\n");
174
+ lines.push(`\x1b[90m${stackLines}\x1b[0m`);
175
+ }
176
+ }
177
+ return lines.join("\n");
178
+ }
179
+ /**
180
+ * Convert to JSON-serializable object
181
+ */
182
+ toJSON() {
183
+ return {
184
+ name: this.name,
185
+ code: this.code,
186
+ message: this.message,
187
+ location: this.location,
188
+ line: this.line,
189
+ column: this.column,
190
+ path: this.path,
191
+ suggestions: this.suggestions,
192
+ cause: this.cause?.message
193
+ };
194
+ }
195
+ };
196
+ /**
197
+ * ANSI color codes for terminal output
198
+ */
199
+ const Colors = {
200
+ reset: "\x1B[0m",
201
+ bold: "\x1B[1m",
202
+ red: "\x1B[31m",
203
+ green: "\x1B[32m",
204
+ yellow: "\x1B[33m",
205
+ blue: "\x1B[34m",
206
+ cyan: "\x1B[36m",
207
+ gray: "\x1B[90m",
208
+ brightRed: "\x1B[91m",
209
+ brightGreen: "\x1B[92m"
210
+ };
211
+ /**
212
+ * Format error for CLI output
213
+ */
214
+ function formatError(error, verbose = false) {
215
+ if (error instanceof ApicodegenError) return error.toString(verbose);
216
+ if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
217
+ return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
218
+ }
219
+ /**
220
+ * Print error to console with formatting
221
+ */
222
+ function printError(error, verbose = false, stream = process.stderr) {
223
+ stream.write(formatError(error, verbose));
224
+ stream.write("\n");
225
+ }
226
+ /**
227
+ * Create error with common patterns
228
+ */
229
+ const createErrors = {
230
+ specNotFound(path, cause) {
231
+ return new ApicodegenError({
232
+ code: ErrorCodes.SPEC_NOT_FOUND,
233
+ message: "OpenAPI spec file not found",
234
+ location: path,
235
+ suggestions: [
236
+ "Check if the file exists using 'ls -la'",
237
+ "Use --spec to provide the correct path",
238
+ "For remote specs, ensure the URL is accessible"
239
+ ],
240
+ cause
241
+ });
242
+ },
243
+ specFetchFailed(url, statusCode, cause) {
244
+ const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
245
+ return new ApicodegenError({
246
+ code: ErrorCodes.SPEC_FETCH_FAILED,
247
+ message,
248
+ location: url,
249
+ suggestions: [
250
+ "Check if the URL is accessible in a browser",
251
+ "Download the spec file locally and use the local path",
252
+ "Verify CORS settings if fetching from a different origin"
253
+ ],
254
+ cause
255
+ });
256
+ },
257
+ specParseFailed(path, line, column, cause) {
258
+ return new ApicodegenError({
259
+ code: ErrorCodes.SPEC_PARSE_FAILED,
260
+ message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
261
+ location: path,
262
+ line,
263
+ column,
264
+ suggestions: [
265
+ "Validate JSON syntax using jsonlint.com",
266
+ "For YAML specs, ensure proper indentation",
267
+ "Check for trailing commas or unquoted special characters"
268
+ ],
269
+ cause
270
+ });
271
+ },
272
+ outputDirMissing(path, cause) {
273
+ return new ApicodegenError({
274
+ code: ErrorCodes.OUTPUT_DIR_MISSING,
275
+ message: "Output directory does not exist",
276
+ location: path,
277
+ suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
278
+ cause
279
+ });
280
+ },
281
+ configInvalid(path, cause) {
282
+ return new ApicodegenError({
283
+ code: ErrorCodes.CONFIG_INVALID,
284
+ message: "Invalid configuration file",
285
+ location: path,
286
+ suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
287
+ cause
288
+ });
289
+ },
290
+ validationFailed(path, details, cause) {
291
+ return new ApicodegenError({
292
+ code: ErrorCodes.VALIDATION_FAILED,
293
+ message: "OpenAPI spec validation failed",
294
+ location: path,
295
+ path: details,
296
+ suggestions: [
297
+ "Check OpenAPI spec structure at the specified path",
298
+ "Ensure all required fields are present",
299
+ "Validate using swagger.io editor"
300
+ ],
301
+ cause
302
+ });
303
+ },
304
+ generationFailed(cause) {
305
+ return new ApicodegenError({
306
+ code: ErrorCodes.GENERATION_FAILED,
307
+ message: "Code generation failed",
308
+ suggestions: [
309
+ "Check for unsupported OpenAPI features",
310
+ "Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
311
+ "Use --verbose for more details"
312
+ ],
313
+ cause
314
+ });
315
+ },
316
+ typeCheckFailed(path, _errors, cause) {
317
+ return new ApicodegenError({
318
+ code: ErrorCodes.TYPE_CHECK_FAILED,
319
+ message: "TypeScript type check failed",
320
+ location: path,
321
+ suggestions: [
322
+ ..._errors.length > 0 ? _errors : [],
323
+ "Review type errors above",
324
+ "Check for schema inconsistencies",
325
+ "Update generated types or fix source schema"
326
+ ],
327
+ cause
328
+ });
329
+ },
330
+ missingRequiredField(field, context) {
331
+ return new ApicodegenError({
332
+ code: ErrorCodes.VALIDATION_FAILED,
333
+ message: `Missing required field: ${field}`,
334
+ path: context,
335
+ suggestions: [`Add the '${field}' field to your configuration`]
336
+ });
337
+ }
338
+ };
339
+ /**
340
+ * Wrap unknown error in ApicodegenError if needed
341
+ */
342
+ function wrapError(error, context) {
343
+ if (error instanceof ApicodegenError) return error;
344
+ if (error instanceof Error) return new ApicodegenError({
345
+ code: context?.code || ErrorCodes.GENERATION_FAILED,
346
+ message: context?.message || error.message,
347
+ location: context?.location,
348
+ suggestions: context?.suggestions,
349
+ cause: error
350
+ });
351
+ return new ApicodegenError({
352
+ code: context?.code || ErrorCodes.GENERATION_FAILED,
353
+ message: String(error),
354
+ suggestions: context?.suggestions
355
+ });
356
+ }
357
+ /**
358
+ * Check if error is an ApicodegenError
359
+ */
360
+ function isApicodegenError(error) {
361
+ return error instanceof ApicodegenError;
362
+ }
363
+ //#endregion
118
364
  //#region src/core/interface.ts
119
365
  let SchemaType = /* @__PURE__ */ function(SchemaType) {
120
366
  SchemaType["schemas"] = "schemas";
@@ -157,7 +403,6 @@ let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
157
403
  }({});
158
404
  let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
159
405
  MediaTypes["JSON"] = "application/json";
160
- MediaTypes["EVENT_STREAM"] = "text/event-stream";
161
406
  MediaTypes["TEXT"] = "text";
162
407
  MediaTypes["IMAGE"] = "image";
163
408
  MediaTypes["AUDIO"] = "audio";
@@ -236,8 +481,20 @@ var Base = class Base {
236
481
  * @param [operationId] - Unique identifier for the operation.
237
482
  * @returns - The generated function name.
238
483
  */
239
- static pathToFnName(path, method, _operationId = "") {
240
- return Base.normalize(Base.camelCase(Base.normalize(path))) + (method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "");
484
+ static pathToFnName(path, method, operationId) {
485
+ let name = "";
486
+ let keywordProtected = false;
487
+ if (operationId) {
488
+ keywordProtected = typescriptKeywords.has(operationId);
489
+ name = Base.camelCase(Base.normalize(operationId));
490
+ }
491
+ if (!name) {
492
+ keywordProtected = typescriptKeywords.has(path);
493
+ name = Base.camelCase(Base.normalize(path));
494
+ }
495
+ if (keywordProtected && !name.endsWith("_")) name = `${name}_`;
496
+ const suffix = method ? Base.capitalize(Base.upperCamelCase(`using_${method}`)) : "";
497
+ return name + suffix;
241
498
  }
242
499
  /**
243
500
  * Normalizes a string by replacing special characters and avoiding TypeScript keywords.
@@ -246,7 +503,37 @@ var Base = class Base {
246
503
  */
247
504
  static normalize(text) {
248
505
  if (typescriptKeywords.has(text)) text += "_";
249
- return text.replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d./gm, "").replaceAll("...", "");
506
+ return text.replaceAll("...", "").replace(/[/\-_{}():\s`,*<>$#.]/gm, "_").replace(/^\d/gm, "");
507
+ }
508
+ /**
509
+ * Map a request body media type to a stable function-name suffix.
510
+ *
511
+ * Used to disambiguate sibling operations sharing the same path+method
512
+ * but different request body media types. The result is appended (in
513
+ * upperCamelCase) to the operation's base function name.
514
+ *
515
+ * Known types are mapped to short, human-readable names. Unknown types
516
+ * fall back to `camelCase(normalize(<sub-type>))`.
517
+ *
518
+ * @param mediaType - The OpenAPI media type (e.g. `application/json`).
519
+ * @returns - The suffix without leading underscore, or empty string.
520
+ */
521
+ static mediaTypeToSuffix(mediaType) {
522
+ const known = {
523
+ "application/json": "Json",
524
+ "multipart/form-data": "FormData",
525
+ "application/x-www-form-urlencoded": "FormUrlencoded",
526
+ "application/octet-stream": "OctetStream",
527
+ "text/plain": "Text",
528
+ "text/html": "Html",
529
+ "application/xml": "Xml",
530
+ "text/xml": "Xml"
531
+ };
532
+ const normalized = mediaType.toLowerCase().split(";")[0]?.trim() ?? "";
533
+ if (known[normalized]) return known[normalized];
534
+ const sub = normalized.split("/")[1];
535
+ if (!sub || sub === "*" || normalized === "*/*" || normalized === "") return "";
536
+ return Base.upperCamelCase(Base.normalize(sub));
250
537
  }
251
538
  /**
252
539
  * Capitalizes the first character of a string.
@@ -274,25 +561,91 @@ var Base = class Base {
274
561
  * @returns - UpperCamelCase string.
275
562
  */
276
563
  static upperCamelCase(text) {
277
- return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map(Base.capitalize).join("");
564
+ return Base.normalize(text).replaceAll("...", "").split("_").filter(Boolean).map((part) => part.match(/^\d/) ? `N${part}` : Base.capitalize(part)).join("");
565
+ }
566
+ /**
567
+ * Classify a spec location string into a transport + source pair.
568
+ *
569
+ * Returns:
570
+ * - `{ transport: 'file', source }` when `input` looks like a local
571
+ * filesystem path (`file://...`, POSIX absolute, Windows absolute).
572
+ * - `{ transport: 'http', source }` for `http(s)://...` URLs.
573
+ *
574
+ * Relative paths are treated as `http` so that callers (CLI / Vite
575
+ * plugin) must resolve them against cwd first. This makes intent
576
+ * explicit and avoids accidentally reading from process.cwd().
577
+ */
578
+ static resolveSpecURL(input) {
579
+ if (input.startsWith("file://")) {
580
+ const stripped = input.replace(/^file:\/\//, "");
581
+ return {
582
+ transport: "file",
583
+ source: /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped
584
+ };
585
+ }
586
+ if (input.startsWith("/")) return {
587
+ transport: "file",
588
+ source: input
589
+ };
590
+ if (/^[A-Za-z]:[\\/]/.test(input)) return {
591
+ transport: "file",
592
+ source: input
593
+ };
594
+ return {
595
+ transport: "http",
596
+ source: input
597
+ };
598
+ }
599
+ /**
600
+ * Read and parse a local OpenAPI document from the filesystem.
601
+ *
602
+ * @param filePath - Absolute filesystem path to the spec.
603
+ * @returns - A promise resolving to the parsed document.
604
+ */
605
+ static async readLocalDoc(filePath) {
606
+ let raw;
607
+ try {
608
+ raw = await (0, node_fs_promises.readFile)(filePath, "utf8");
609
+ } catch (error) {
610
+ if (error?.code === "ENOENT") throw createErrors.specNotFound(filePath, error);
611
+ throw new Error(`Failed to read OpenAPI spec from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
612
+ }
613
+ try {
614
+ return JSON.parse(raw);
615
+ } catch (error) {
616
+ throw createErrors.specParseFailed(filePath, void 0, void 0, error);
617
+ }
278
618
  }
279
619
  /**
280
620
  * Fetches documentation from a given URL.
281
- * @param url - The URL to fetch the documentation from.
282
- * @param requestInit - Additional request parameters.
621
+ *
622
+ * Supports three transport modes:
623
+ * - `file://...` URLs → read from filesystem (parsed as JSON)
624
+ * - absolute filesystem paths → read from filesystem (parsed as JSON)
625
+ * - `http(s)://...` URLs (and unrecognised inputs like relative paths)
626
+ * → fetched via undici (existing behavior)
627
+ *
628
+ * Callers should pass an already-resolved absolute path or URL. Relative
629
+ * paths fall through to undici by design — CLI / Vite plugin should
630
+ * resolve them against cwd first.
631
+ *
632
+ * @param url - The URL or filesystem path to fetch the documentation from.
633
+ * @param requestInit - Additional request parameters (only used for http(s)).
283
634
  * @returns - A promise resolving to the fetched documentation data.
284
635
  */
285
636
  static async fetchDoc(url, requestInit = {}) {
286
- const { body, statusCode } = await (0, undici.request)(url, {
637
+ const { transport, source } = Base.resolveSpecURL(url);
638
+ if (transport === "file") return Base.readLocalDoc(source);
639
+ const { body, statusCode } = await (0, undici.request)(source, {
287
640
  method: "GET",
288
641
  dispatcher: new undici.Agent({ connect: { rejectUnauthorized: false } }),
289
642
  ...requestInit
290
643
  });
291
- if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${url}: HTTP ${statusCode}`);
644
+ if (statusCode >= 400) throw new Error(`Failed to fetch OpenAPI documentation from ${source}: HTTP ${statusCode}`);
292
645
  try {
293
646
  return body.json();
294
647
  } catch (error) {
295
- throw new Error(`Failed to parse JSON response from ${url}: ${error instanceof Error ? error.message : String(error)}`);
648
+ throw new Error(`Failed to parse JSON response from ${source}: ${error instanceof Error ? error.message : String(error)}`);
296
649
  }
297
650
  }
298
651
  /**
@@ -435,255 +788,35 @@ var Provider = class {
435
788
  this.enums = enums;
436
789
  this.schemas = schemas;
437
790
  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
- };
519
- }
520
- };
521
- /**
522
- * ANSI color codes for terminal output
523
- */
524
- const Colors = {
525
- reset: "\x1B[0m",
526
- bold: "\x1B[1m",
527
- red: "\x1B[31m",
528
- green: "\x1B[32m",
529
- yellow: "\x1B[33m",
530
- blue: "\x1B[34m",
531
- cyan: "\x1B[36m",
532
- gray: "\x1B[90m",
533
- brightRed: "\x1B[91m",
534
- brightGreen: "\x1B[92m"
535
- };
536
- /**
537
- * Format error for CLI output
538
- */
539
- function formatError(error, verbose = false) {
540
- if (error instanceof ApicodegenError) return error.toString(verbose);
541
- if (error instanceof Error) return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${error.message}${verbose && error.stack ? `\n\n${Colors.gray}${error.stack}${Colors.reset}` : ""}`;
542
- return `${Colors.red}${Colors.bold}Error${Colors.reset}: ${String(error)}`;
543
- }
544
- /**
545
- * Print error to console with formatting
546
- */
547
- function printError(error, verbose = false, stream = process.stderr) {
548
- stream.write(formatError(error, verbose));
549
- stream.write("\n");
550
- }
551
- /**
552
- * Create error with common patterns
553
- */
554
- const createErrors = {
555
- specNotFound(path, cause) {
556
- return new ApicodegenError({
557
- code: ErrorCodes.SPEC_NOT_FOUND,
558
- message: "OpenAPI spec file not found",
559
- location: path,
560
- suggestions: [
561
- "Check if the file exists using 'ls -la'",
562
- "Use --spec to provide the correct path",
563
- "For remote specs, ensure the URL is accessible"
564
- ],
565
- cause
566
- });
567
- },
568
- specFetchFailed(url, statusCode, cause) {
569
- const message = statusCode ? `Failed to fetch OpenAPI spec (HTTP ${statusCode})` : "Failed to fetch OpenAPI spec from URL";
570
- return new ApicodegenError({
571
- code: ErrorCodes.SPEC_FETCH_FAILED,
572
- message,
573
- location: url,
574
- suggestions: [
575
- "Check if the URL is accessible in a browser",
576
- "Download the spec file locally and use the local path",
577
- "Verify CORS settings if fetching from a different origin"
578
- ],
579
- cause
580
- });
581
- },
582
- specParseFailed(path, line, column, cause) {
583
- return new ApicodegenError({
584
- code: ErrorCodes.SPEC_PARSE_FAILED,
585
- message: "Failed to parse OpenAPI spec (invalid JSON or YAML)",
586
- location: path,
587
- line,
588
- column,
589
- suggestions: [
590
- "Validate JSON syntax using jsonlint.com",
591
- "For YAML specs, ensure proper indentation",
592
- "Check for trailing commas or unquoted special characters"
593
- ],
594
- cause
595
- });
596
- },
597
- outputDirMissing(path, cause) {
598
- return new ApicodegenError({
599
- code: ErrorCodes.OUTPUT_DIR_MISSING,
600
- message: "Output directory does not exist",
601
- location: path,
602
- suggestions: ["Create the directory: mkdir -p $(dirname <output>)", "Check if the path is correct"],
603
- cause
604
- });
605
- },
606
- configInvalid(path, cause) {
607
- return new ApicodegenError({
608
- code: ErrorCodes.CONFIG_INVALID,
609
- message: "Invalid configuration file",
610
- location: path,
611
- suggestions: ["Validate JSON syntax in the config file", "Check for required fields (spec, output)"],
612
- cause
613
- });
614
- },
615
- validationFailed(path, details, cause) {
616
- return new ApicodegenError({
617
- code: ErrorCodes.VALIDATION_FAILED,
618
- message: "OpenAPI spec validation failed",
619
- location: path,
620
- path: details,
621
- suggestions: [
622
- "Check OpenAPI spec structure at the specified path",
623
- "Ensure all required fields are present",
624
- "Validate using swagger.io editor"
625
- ],
626
- cause
627
- });
628
- },
629
- generationFailed(cause) {
630
- return new ApicodegenError({
631
- code: ErrorCodes.GENERATION_FAILED,
632
- message: "Code generation failed",
633
- suggestions: [
634
- "Check for unsupported OpenAPI features",
635
- "Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification",
636
- "Use --verbose for more details"
637
- ],
638
- cause
639
- });
640
- },
641
- typeCheckFailed(path, _errors, cause) {
642
- return new ApicodegenError({
643
- code: ErrorCodes.TYPE_CHECK_FAILED,
644
- message: "TypeScript type check failed",
645
- location: path,
646
- suggestions: [
647
- "Review type errors above",
648
- "Check for schema inconsistencies",
649
- "Update generated types or fix source schema"
650
- ],
651
- cause
652
- });
653
- },
654
- missingRequiredField(field, context) {
655
- return new ApicodegenError({
656
- code: ErrorCodes.VALIDATION_FAILED,
657
- message: `Missing required field: ${field}`,
658
- path: context,
659
- suggestions: [`Add the '${field}' field to your configuration`]
660
- });
791
+ this.parameters = parameters;
792
+ this.requestBodies = requestBodies;
793
+ this.apis = apis;
661
794
  }
662
795
  };
796
+ //#endregion
797
+ //#region src/core/generator/naming.ts
663
798
  /**
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
799
+ * Create a per-generation unique-name resolver.
800
+ *
801
+ * Tracks how many times each base name has been seen during a single
802
+ * code generation pass and returns a unique variant on every call:
803
+ *
804
+ * reserve('foo') // 'foo'
805
+ * reserve('foo') // 'foo2'
806
+ * reserve('foo') // 'foo3'
807
+ * reserve('bar') // 'bar' (independent counter)
808
+ *
809
+ * The resolver holds no module-level state — create one per generation pass
810
+ * and let it go out of scope when the pass completes.
683
811
  */
684
- function isApicodegenError(error) {
685
- return error instanceof ApicodegenError;
686
- }
812
+ const createUniqueNameResolver = () => {
813
+ const seen = /* @__PURE__ */ new Map();
814
+ return (name) => {
815
+ const next = (seen.get(name) ?? 0) + 1;
816
+ seen.set(name, next);
817
+ return next === 1 ? name : `${name}${next}`;
818
+ };
819
+ };
687
820
  //#endregion
688
821
  //#region src/core/generator/index.ts
689
822
  var Generator = class Generator {
@@ -700,19 +833,10 @@ var Generator = class Generator {
700
833
  return (0, typescript.createPrinter)().printFile(sourceFile);
701
834
  }
702
835
  static async write(code, filepath) {
703
- const { mkdir } = await import("node:fs/promises");
704
- const { dirname } = await import("node:path");
705
836
  try {
706
- await mkdir(dirname(filepath), { recursive: true });
707
837
  await (0, node_fs_promises.writeFile)(filepath, code);
708
838
  } catch (error) {
709
- throw new ApicodegenError({
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
- });
839
+ console.error(error);
716
840
  }
717
841
  }
718
842
  /**
@@ -727,7 +851,7 @@ var Generator = class Generator {
727
851
  static toUrlTemplate(path, parameters, basePath = "") {
728
852
  const queryParameters = parameters.filter((p) => p.in === "query");
729
853
  if (queryParameters.length > 0) {
730
- const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.normalize(qp.name)}}`).join("");
854
+ const queryString = queryParameters.map((qp, index) => `${index === 0 ? "?" : "&"}${encodeURIComponent(qp.name)}={${Base.camelCase(Base.normalize(qp.name))}}`).join("");
731
855
  path += queryString;
732
856
  }
733
857
  const pathSegments = path.replaceAll("{", "${").split("$").filter(Boolean);
@@ -736,7 +860,7 @@ var Generator = class Generator {
736
860
  const match = /^{(.+)}(.+)?/gm.exec(segment);
737
861
  const isLastSegment = index === pathSegments.length - 2;
738
862
  if (!match) throw new Error(`Invalid path segment: ${segment}`);
739
- return typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(Base.normalize(match[1])), !isLastSegment ? typescript.factory.createTemplateMiddle(match[2]) : typescript.factory.createTemplateTail(match[2] || ""));
863
+ return typescript.factory.createTemplateSpan(typescript.factory.createIdentifier(match[1]), !isLastSegment ? typescript.factory.createTemplateMiddle(match[2]) : typescript.factory.createTemplateTail(match[2] || ""));
740
864
  }));
741
865
  }
742
866
  /**
@@ -749,7 +873,10 @@ var Generator = class Generator {
749
873
  if (!Array.isArray(comments) || comments.filter(Boolean).length === 0) return;
750
874
  const formatComment = (comment) => {
751
875
  if (comment.tag === "returns") return `* @returns {${comment.type}} ${comment.comment ?? ""}`;
752
- if (comment.tag === "param") return comment.comment ? `* @param ${comment.paramName} - ${comment.comment}` : `* @param ${comment.paramName}`;
876
+ if (comment.tag === "param") {
877
+ const typePart = comment.type ? `{${comment.type}} ` : "";
878
+ return comment.comment ? `* @param ${typePart}${comment.paramName} - ${comment.comment}` : `* @param ${typePart}${comment.paramName}`;
879
+ }
753
880
  if (comment.tag) return `* @${comment.tag} ${comment.comment ?? ""}`;
754
881
  return `* ${comment.comment}`;
755
882
  };
@@ -788,15 +915,16 @@ var Generator = class Generator {
788
915
  static generateParamTags(parameters, requestBody) {
789
916
  const tags = [];
790
917
  for (const p of parameters) {
791
- const paramName = Base.normalize(p.name);
918
+ const paramName = Base.camelCase(Base.normalize(p.name));
792
919
  let paramType = "unknown";
793
920
  if (p.schema) paramType = Generator.schemaToTypeString(p.schema);
794
921
  const isOptional = p.required === false;
922
+ const inPrefix = p.in ? `[${p.in}] ` : "";
795
923
  tags.push({
796
924
  tag: "param",
797
925
  paramName,
798
926
  type: `${paramType}${isOptional ? " | undefined" : ""}`,
799
- comment: p.description ?? ""
927
+ comment: `${inPrefix}${p.description ?? ""}`
800
928
  });
801
929
  }
802
930
  if (requestBody?.schema && "properties" in requestBody.schema) {
@@ -835,9 +963,10 @@ var Generator = class Generator {
835
963
  const propsCount = Object.keys(schema.properties ?? {}).length;
836
964
  if (!schema.properties || propsCount === 0) return typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier("Record"), [typescript.factory.createToken(typescript.SyntaxKind.StringKeyword), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)]);
837
965
  const props = Object.keys(schema.properties);
966
+ const required = Array.isArray(schema.required) ? schema.required : [];
838
967
  return typescript.factory.createTypeLiteralNode(props.map((propKey) => {
839
968
  const propSchema = schema.properties[propKey];
840
- return typescript.factory.createPropertySignature(void 0, typescript.factory.createStringLiteral(propKey), schema.required || schema.ref || Generator.isBinarySchema(schema) ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), Generator.toTypeNode(propSchema));
969
+ 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
970
  }));
842
971
  }
843
972
  case "integer":
@@ -858,25 +987,46 @@ var Generator = class Generator {
858
987
  }
859
988
  if (enum_) return typescript.factory.createUnionTypeNode(enum_.map((e) => typescript.factory.createLiteralTypeNode(typescript.factory.createStringLiteral(e))));
860
989
  if (type === "string") return typescript.factory.createToken(typescript.SyntaxKind.StringKeyword);
861
- if (oneOf) return typescript.factory.createUnionTypeNode(oneOf.map((schema) => Generator.toTypeNode(schema)));
862
- if (anyOf) return typescript.factory.createUnionTypeNode(anyOf.map((schema) => Generator.toTypeNode(schema)));
990
+ if (oneOf) {
991
+ const uniqueTypes = Generator.deduplicateTypes(oneOf.map((s) => Generator.toTypeNode(s)));
992
+ return typescript.factory.createUnionTypeNode(uniqueTypes);
993
+ }
994
+ if (anyOf) {
995
+ const uniqueTypes = Generator.deduplicateTypes(anyOf.map((s) => Generator.toTypeNode(s)));
996
+ return typescript.factory.createUnionTypeNode(uniqueTypes);
997
+ }
863
998
  if (allOf) return typescript.factory.createIntersectionTypeNode(allOf.map((schema) => Generator.toTypeNode(schema)));
864
999
  if (type && typeof type === "string") return typescript.factory.createTypeReferenceNode(type !== "unknown" && type !== "null" ? typescript.factory.createIdentifier(Base.upperCamelCase(type)) : type);
865
1000
  }
866
1001
  }
867
1002
  return typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword);
868
1003
  }
1004
+ static deduplicateTypes(types) {
1005
+ const seen = /* @__PURE__ */ new Set();
1006
+ const unique = [];
1007
+ for (const type of types) {
1008
+ const key = Generator.getTypeNodeKey(type);
1009
+ if (!seen.has(key)) {
1010
+ seen.add(key);
1011
+ unique.push(type);
1012
+ }
1013
+ }
1014
+ return unique;
1015
+ }
1016
+ static getTypeNodeKey(type) {
1017
+ return JSON.stringify(type);
1018
+ }
869
1019
  static toDeclarationNodes(parameters) {
870
1020
  const objectElements = [];
871
1021
  const typeObjectElements = [];
872
1022
  const refParameters = [];
873
1023
  for (const parameter of parameters) if (parameter.ref) {
874
1024
  const refName = Base.ref2name(parameter.ref);
875
- refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.normalize(refName)), void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
1025
+ refParameters.push(typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier(Base.camelCase(Base.normalize(refName))), void 0, typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(Base.upperCamelCase(Base.normalize(refName)))), void 0));
876
1026
  } else {
877
1027
  const { name, schema, required } = parameter;
878
- objectElements.push(typescript.factory.createBindingElement(void 0, void 0, typescript.factory.createIdentifier(Base.normalize(name))));
879
- typeObjectElements.push(typescript.factory.createPropertySignature([], typescript.factory.createIdentifier(Base.normalize(name)), required ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), !schema ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
1028
+ objectElements.push(typescript.factory.createBindingElement(void 0, void 0, typescript.factory.createIdentifier(Base.camelCase(Base.normalize(name)))));
1029
+ typeObjectElements.push(typescript.factory.createPropertySignature([], typescript.factory.createIdentifier(Base.camelCase(Base.normalize(name))), required ? void 0 : typescript.factory.createToken(typescript.SyntaxKind.QuestionToken), !schema ? typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword) : Generator.toTypeNode(schema)));
880
1030
  }
881
1031
  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
1032
  return refParameters;
@@ -900,17 +1050,77 @@ var Generator = class Generator {
900
1050
  });
901
1051
  return statements;
902
1052
  }
1053
+ /**
1054
+ * Build statements that construct a `URLSearchParams` from request body
1055
+ * fields for an `application/x-www-form-urlencoded` request.
1056
+ *
1057
+ * Skips `undefined` / `null` values so optional fields don't end up as
1058
+ * the literal string `"undefined"` in the URL (fixes #8).
1059
+ *
1060
+ * The resulting `sp` variable is referenced by the adapter as the
1061
+ * `body` payload.
1062
+ */
1063
+ static toURLSearchParamsStatement(parameters, requestBody) {
1064
+ const statements = [];
1065
+ 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));
1066
+ statements.push(spDeclaration);
1067
+ 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]));
1068
+ if (requestBody && requestBody.type === "object" && requestBody.properties && Object.keys(requestBody.properties).length !== 0) for (const key of Object.keys(requestBody.properties)) {
1069
+ const fieldSchema = requestBody.properties[key];
1070
+ const required = !!fieldSchema.required;
1071
+ const accessor = typescript.factory.createElementAccessExpression(typescript.factory.createIdentifier("req"), typescript.factory.createStringLiteral(key));
1072
+ const append = appendValue(key, Generator.toFormDataCompatibleString(accessor, fieldSchema));
1073
+ if (required) statements.push(append);
1074
+ else statements.push(typescript.factory.createIfStatement(typescript.factory.createBinaryExpression(accessor, typescript.factory.createToken(typescript.SyntaxKind.ExclamationEqualsToken), typescript.factory.createToken(typescript.SyntaxKind.NullKeyword)), typescript.factory.createBlock([append], true)));
1075
+ }
1076
+ for (const parameter of parameters) {
1077
+ if (parameter.in === "header" || parameter.in === "cookie" || parameter.in === "path") continue;
1078
+ const accessor = typescript.factory.createIdentifier(Base.camelCase(Base.normalize(parameter.name)));
1079
+ 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)));
1080
+ }
1081
+ return statements;
1082
+ }
1083
+ /**
1084
+ * Render `expr` as a string suitable for `FormData.append` /
1085
+ * `URLSearchParams.append`. Object/array schemas are JSON-stringified,
1086
+ * everything else is coerced via `String(...)`.
1087
+ */
1088
+ static toFormDataCompatibleString(expr, schema) {
1089
+ 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]);
1090
+ return typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [expr]);
1091
+ }
903
1092
  static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
904
- const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(requestBody.type);
905
1093
  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
1094
  const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
909
1095
  const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
1096
+ const inBody = parametersShouldNotPutInFormData.filter((p) => !p.in || p.in === "body");
910
1097
  const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
911
1098
  const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
912
- const shouldPutParametersOrBodyInFormData = !!isFormDataRequest && (isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0);
913
- return typescript.factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON, isEventStream)]);
1099
+ const mediaType = (requestBody?.type ?? "").toLowerCase().split(";")[0]?.trim();
1100
+ const requestSchemaIsBinary = requestBody?.schema && Generator.isBinarySchema(requestBody.schema);
1101
+ let bodyKind = "none";
1102
+ let bodyContentType;
1103
+ if (mediaType === "multipart/form-data") {
1104
+ if (hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0) bodyKind = "form-data";
1105
+ } else if (mediaType === "application/x-www-form-urlencoded") {
1106
+ bodyKind = "urlencoded";
1107
+ bodyContentType = "application/x-www-form-urlencoded";
1108
+ } else if (mediaType === "application/json") {
1109
+ if (requestBody?.schema || inBody.length > 0) {
1110
+ bodyKind = "json";
1111
+ bodyContentType = "application/json";
1112
+ }
1113
+ } else if (requestSchemaIsBinary) {
1114
+ bodyKind = "binary";
1115
+ bodyContentType = requestBody?.type;
1116
+ } else if (requestBody?.schema) {
1117
+ bodyKind = "json";
1118
+ bodyContentType = requestBody?.type;
1119
+ }
1120
+ const preStatements = [];
1121
+ if (bodyKind === "form-data") preStatements.push(...Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema));
1122
+ else if (bodyKind === "urlencoded") preStatements.push(...Generator.toURLSearchParamsStatement(parametersShouldNotPutInFormData, requestBody?.schema));
1123
+ return typescript.factory.createBlock([...preStatements, ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, bodyKind, bodyContentType, shouldParseResponseToJSON)]);
914
1124
  }
915
1125
  static schemaToStatemets(parsedDoc, adaptor, options) {
916
1126
  const statements = [];
@@ -918,14 +1128,16 @@ var Generator = class Generator {
918
1128
  const enumNames = [];
919
1129
  for (const enumObject of enums) {
920
1130
  enumNames.push(Base.upperCamelCase(enumObject.name));
921
- statements.push(typescript.factory.createEnumDeclaration([typescript.factory.createToken(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member) => {
922
- return typescript.factory.createEnumMember(typescript.factory.createStringLiteral(typeof member === "string" ? member : `${member}_`), typeof member === "string" ? typescript.factory.createStringLiteral(member) : typescript.factory.createNumericLiteral(member));
1131
+ statements.push(typescript.factory.createEnumDeclaration([typescript.factory.createToken(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(enumObject.name)), enumObject.enum.map((member, index) => {
1132
+ const key = typeof member === "string" ? member : `Value${member}`;
1133
+ return typescript.factory.createEnumMember(typescript.factory.createStringLiteral(key), typeof member === "string" ? typescript.factory.createStringLiteral(member) : typescript.factory.createNumericLiteral(member));
923
1134
  })));
924
1135
  }
925
1136
  for (const schemaKey in schemas) if (Object.hasOwn(schemas, schemaKey) && !enumNames.includes(Base.upperCamelCase(schemaKey))) {
926
1137
  const schema = schemas[schemaKey];
927
1138
  statements.push(typescript.factory.createTypeAliasDeclaration([typescript.factory.createModifier(typescript.SyntaxKind.ExportKeyword)], typescript.factory.createIdentifier(Base.upperCamelCase(schemaKey)), void 0, Generator.toTypeNode(schema)));
928
1139
  }
1140
+ const reserveUnique = createUniqueNameResolver();
929
1141
  for (const uri in apis) {
930
1142
  const operations = apis[uri];
931
1143
  for (const operation of operations) {
@@ -935,7 +1147,7 @@ var Generator = class Generator {
935
1147
  if (requestBody.length === 0) requestBody.push({ type: "application/json" });
936
1148
  const shouldAddExtraMethodNameSuffix = requestBody.length > 1;
937
1149
  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.capitalize(req.type.split("/")[1]) : ""), void 0, [...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [], ...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : []].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor));
1150
+ 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, [...parameters.length > 0 ? Generator.toDeclarationNodes(parameters) : [], ...req?.schema ? [Generator.toRequestBodyTypeNode(req.schema)] : []].filter(Boolean), void 0, Generator.bodyBlock(options.baseURL + uri, method, parameters, req, responses[0], adaptor));
939
1151
  const mergedDescription = [description, summary].filter(Boolean).join(". ");
940
1152
  Generator.addComments(statement, [
941
1153
  mergedDescription && { comment: mergedDescription },
@@ -963,7 +1175,7 @@ var Generator = class Generator {
963
1175
  //#region src/core/client/axios.ts
964
1176
  /**
965
1177
  * Adapter class implementing support for generating code that makes use of the Axios HTTP client library.
966
- * This class defines custom behavior and field mappings specific to the Axios client.
1178
+ * This adapter defines custom behavior and field mappings specific to the Axios client.
967
1179
  */
968
1180
  var AxiosAdapter = class extends Adapter {
969
1181
  /**
@@ -987,35 +1199,38 @@ var AxiosAdapter = class extends Adapter {
987
1199
  */
988
1200
  name = "axios";
989
1201
  /**
990
- * Generates client code for making API requests using Axios.
991
- * @param uri - The API endpoint URI
992
- * @param method - The HTTP method (GET, POST, etc.)
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
1202
+ * Method that should generate and return the client-specific configuration statements.
1203
+ *
1204
+ * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
1001
1205
  */
1002
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, _shouldUseJSONResponse, isEventStream) {
1206
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, _shouldUseJSONResponse) {
1003
1207
  const statements = [];
1004
- const inBody = parameters.filter((p) => !p.in || p.in === "body");
1208
+ parameters.filter((p) => !p.in || p.in === "body");
1005
1209
  const inHeader = parameters.filter((p) => p.in === "header");
1006
- /**
1007
- * Creates the literal object expression for fetch options
1008
- * including method, headers, and body.
1009
- * @returns - The constructed fetch options object
1010
- */
1011
- const toLiterlExpression = (extraProperties = []) => {
1012
- return typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(inHeader.map((p) => 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.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? typescript.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? typescript.factory.createIdentifier("req") : typescript.factory.createIdentifier("req")) : []).concat(extraProperties), true);
1210
+ const toLiterlExpression = () => {
1211
+ const headerEntries = [];
1212
+ 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.camelCase(Base.normalize(p.name)))])])));
1213
+ if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
1214
+ const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
1215
+ if (headerEntries.length > 0) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(headerEntries)));
1216
+ let bodyExpr;
1217
+ switch (bodyKind) {
1218
+ case "form-data":
1219
+ bodyExpr = typescript.factory.createIdentifier("fd");
1220
+ break;
1221
+ case "urlencoded":
1222
+ bodyExpr = typescript.factory.createIdentifier("sp");
1223
+ break;
1224
+ case "json":
1225
+ case "binary":
1226
+ bodyExpr = typescript.factory.createIdentifier("req");
1227
+ break;
1228
+ case "none": break;
1229
+ }
1230
+ if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1231
+ return typescript.factory.createObjectLiteralExpression(properties, true);
1013
1232
  };
1014
- if (isEventStream) {
1015
- statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("adapter"), typescript.factory.createStringLiteral("fetch")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("responseType"), typescript.factory.createStringLiteral("stream"))])])));
1016
- return statements;
1017
- }
1018
- statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1233
+ statements.push(typescript.factory.createReturnStatement(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), toLiterlExpression()])));
1019
1234
  return statements;
1020
1235
  }
1021
1236
  };
@@ -1039,12 +1254,12 @@ var FetchAdapter = class extends Adapter {
1039
1254
  * @param requestBody - The request body media type definition
1040
1255
  * @param response - The response media type definition
1041
1256
  * @param adapter - The adapter instance
1042
- * @param shouldUseFormData - Flag to use FormData for the request body
1257
+ * @param bodyKind - How the body should be encoded (json / form-data / urlencoded / binary / none)
1258
+ * @param bodyContentType - Content-Type header to inject (undefined means "let runtime decide", e.g. multipart boundary)
1043
1259
  * @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
1260
  * @return - An array of generated TypeScript statements
1046
1261
  */
1047
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse, isEventStream) {
1262
+ client(uri, method, parameters, requestBody, response, adapter, bodyKind, bodyContentType, shouldUseJSONResponse) {
1048
1263
  const statements = [];
1049
1264
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1050
1265
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1054,19 +1269,49 @@ var FetchAdapter = class extends Adapter {
1054
1269
  * @returns - The constructed fetch options object
1055
1270
  */
1056
1271
  const toLiterlExpression = () => {
1057
- return typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(inHeader.map((p) => 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.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? typescript.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), [], [requestBody ? typescript.factory.createIdentifier("req") : typescript.factory.createObjectLiteralExpression(inBody.map((b) => typescript.factory.createShorthandPropertyAssignment(typescript.factory.createIdentifier(b.name))), true)]) : typescript.factory.createIdentifier("req")) : []), true);
1272
+ const headerEntries = [];
1273
+ 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.camelCase(Base.normalize(p.name)))])])));
1274
+ if (bodyContentType !== void 0) headerEntries.push(typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral("Content-Type"), typescript.factory.createStringLiteral(bodyContentType)));
1275
+ const properties = [typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))];
1276
+ if (headerEntries.length > 0) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(headerEntries)));
1277
+ let bodyExpr;
1278
+ switch (bodyKind) {
1279
+ case "form-data":
1280
+ bodyExpr = typescript.factory.createIdentifier("fd");
1281
+ break;
1282
+ case "urlencoded":
1283
+ bodyExpr = typescript.factory.createIdentifier("sp");
1284
+ break;
1285
+ case "json": {
1286
+ const arg = requestBody ? typescript.factory.createIdentifier("req") : typescript.factory.createObjectLiteralExpression(inBody.map((b) => typescript.factory.createShorthandPropertyAssignment(typescript.factory.createIdentifier(b.name))), true);
1287
+ bodyExpr = typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), [], [arg]);
1288
+ break;
1289
+ }
1290
+ case "binary":
1291
+ bodyExpr = typescript.factory.createIdentifier("req");
1292
+ break;
1293
+ case "none": break;
1294
+ }
1295
+ if (bodyExpr) properties.push(typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), bodyExpr));
1296
+ return typescript.factory.createObjectLiteralExpression(properties, true);
1058
1297
  };
1059
- if (isEventStream) {
1060
- statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1061
- return statements;
1062
- }
1063
- statements.push(typescript.factory.createReturnStatement(shouldUseJSONResponse ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), 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), response?.schema ? typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)) : typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1298
+ statements.push(typescript.factory.createReturnStatement(shouldUseJSONResponse ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), 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), response?.schema ? typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))), Generator.toTypeNode(response.schema)) : typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))), typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1064
1299
  return statements;
1065
1300
  }
1066
1301
  };
1067
1302
  //#endregion
1068
1303
  //#region src/core/config.ts
1069
1304
  /**
1305
+ * Strings considered truthy for boolean env vars (verbose/watch/typeCheck).
1306
+ */
1307
+ const TRUTHY_STRINGS = new Set([
1308
+ "true",
1309
+ "1",
1310
+ "yes",
1311
+ "on",
1312
+ "enable"
1313
+ ]);
1314
+ /**
1070
1315
  * Environment variable mappings
1071
1316
  */
1072
1317
  const ENV_MAPPINGS = {
@@ -1089,10 +1334,10 @@ function loadFromEnv() {
1089
1334
  case "verbose":
1090
1335
  case "watch":
1091
1336
  case "typeCheck":
1092
- config[configKey] = value === "true" || value === "1";
1337
+ config[configKey] = TRUTHY_STRINGS.has(value.toLowerCase());
1093
1338
  break;
1094
1339
  case "adaptor":
1095
- config[configKey] = value;
1340
+ if (Object.values(Adaptors).includes(value)) config[configKey] = value;
1096
1341
  break;
1097
1342
  default: config[configKey] = value;
1098
1343
  }
@@ -1159,7 +1404,7 @@ function mergeConfigs(base, ...sources) {
1159
1404
  const result = { ...base };
1160
1405
  for (const source of sources) {
1161
1406
  if (!source) continue;
1162
- for (const [key, value] of Object.entries(source)) if (value !== void 0) result[key] = value;
1407
+ for (const [key, value] of Object.entries(source)) if (value !== void 0 && value !== null) result[key] = value;
1163
1408
  }
1164
1409
  return result;
1165
1410
  }
@@ -1208,6 +1453,20 @@ async function loadConfig(options = {}) {
1208
1453
  };
1209
1454
  }
1210
1455
  /**
1456
+ * Create CLI options from config for commander
1457
+ */
1458
+ function configToCLIOptions(config) {
1459
+ const options = {};
1460
+ if (config.spec) options.spec = config.spec;
1461
+ if (config.output) options.output = config.output;
1462
+ if (config.adaptor) options.adaptor = config.adaptor;
1463
+ if (config.baseURL) options.baseURL = config.baseURL;
1464
+ if (config.verbose) options.verbose = config.verbose;
1465
+ if (config.watch) options.watch = config.watch;
1466
+ if (config.importClientSource) options.importClientSource = config.importClientSource;
1467
+ return options;
1468
+ }
1469
+ /**
1211
1470
  * Convert resolved config to provider options format
1212
1471
  */
1213
1472
  function toProviderOptions(config) {
@@ -1222,74 +1481,265 @@ function toProviderOptions(config) {
1222
1481
  };
1223
1482
  }
1224
1483
  //#endregion
1225
- //#region src/core/logger.ts
1226
- const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
1227
- const green = (s) => `\x1b[32m${s}\x1b[0m`;
1228
- const red = (s) => `\x1b[31m${s}\x1b[0m`;
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}`);
1484
+ //#region src/openapi/V2.ts
1485
+ var V2 = class {
1486
+ doc;
1487
+ constructor(doc) {
1488
+ this.doc = doc;
1489
+ }
1490
+ /**
1491
+ * Resolves a path $ref to the actual path object.
1492
+ */
1493
+ resolvePathRef($ref) {
1494
+ const refName = Base.ref2name($ref, this.doc);
1495
+ return this.doc.paths?.[refName];
1496
+ }
1497
+ /**
1498
+ * Is array schema.
1499
+ */
1500
+ isOpenAPIArraySchema(schema) {
1501
+ return typeof schema === "object" && schema.type === "array";
1502
+ }
1503
+ /**
1504
+ * OpenAPI schema to base schema.
1505
+ */
1506
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1507
+ let refName = "";
1508
+ if (Base.isRef(schema)) {
1509
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
1510
+ if (reserveRef) return { type: upLevelSchemaKey + refName };
1511
+ if (!this.doc.definitions) this.doc.definitions = {};
1512
+ schema = this.doc.definitions[Base.ref2name(schema.$ref, this.doc)];
1513
+ }
1514
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1515
+ }
1516
+ /**
1517
+ * Transform all OpenAPI schema to Base Schema
1518
+ */
1519
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
1520
+ if (!schema) return { type: "unknown" };
1521
+ if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1522
+ if (this.isOpenAPIArraySchema(schema)) {
1523
+ const { type, description, items, required } = schema;
1524
+ return {
1525
+ type,
1526
+ required: !!required,
1527
+ description,
1528
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1529
+ };
1530
+ } else {
1531
+ const { required = [], allOf, anyOf, description, enum: enum_, format, oneOf, properties = {} } = schema;
1532
+ let { type } = schema;
1533
+ if (enum_ && type !== "boolean") {
1534
+ const enumObject = {
1535
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1536
+ enum: [...new Set(enum_)]
1537
+ };
1538
+ const sameObject = Base.findSameSchema(enumObject, enums);
1539
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1540
+ return {
1541
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1542
+ required,
1543
+ description
1544
+ };
1545
+ }
1546
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1547
+ return {
1548
+ type,
1549
+ required,
1550
+ description,
1551
+ enum: enum_,
1552
+ format,
1553
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
1554
+ ...s,
1555
+ ref: s.$ref,
1556
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1557
+ } : this.toBaseSchema(s, enums)),
1558
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
1559
+ ...s,
1560
+ ref: s.$ref,
1561
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1562
+ } : this.toBaseSchema(s, enums)),
1563
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
1564
+ ...s,
1565
+ ref: s.$ref,
1566
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1567
+ } : this.toBaseSchema(s, enums)),
1568
+ properties: Object.keys(properties).reduce((acc, p) => {
1569
+ const propSchema = properties[p];
1570
+ return {
1571
+ ...acc,
1572
+ [p]: Base.isRef(propSchema) ? { type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)) } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1573
+ };
1574
+ }, {})
1575
+ };
1576
+ }
1577
+ }
1578
+ /**
1579
+ * OpenAPI parameter to base parameter.
1580
+ */
1581
+ getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1582
+ if (Base.isRef(parameter)) {
1583
+ const refName = Base.ref2name(parameter.$ref, this.doc);
1584
+ const resolved = this.doc.parameters?.[refName];
1585
+ if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
1586
+ parameter = resolved;
1587
+ }
1588
+ const p = parameter;
1589
+ const { name, required, description, type, items, enum: enum_, properties, schema } = p;
1590
+ if (enum_) {
1591
+ const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1592
+ const enumSchema = {
1593
+ name: type,
1594
+ enum: [...new Set(enum_)]
1595
+ };
1596
+ const sameEnum = Base.findSameSchema(enumSchema, enums);
1597
+ if (!sameEnum && Base.isValidEnumType({
1598
+ type,
1599
+ enum: enum_
1600
+ })) enums.push(enumSchema);
1601
+ return {
1602
+ name,
1603
+ required,
1604
+ description,
1605
+ in: p.in,
1606
+ schema: { type: sameEnum?.name ?? type }
1607
+ };
1608
+ }
1609
+ if (items) return {
1610
+ name,
1611
+ required,
1612
+ description,
1613
+ in: p.in,
1614
+ schema: {
1615
+ type,
1616
+ items
1617
+ }
1618
+ };
1619
+ if (schema && Base.isRef(schema)) return {
1620
+ name,
1621
+ required,
1622
+ description,
1623
+ in: p.in,
1624
+ schema: { type: Base.capitalize(Base.ref2name(schema.$ref)) }
1625
+ };
1626
+ return {
1627
+ name,
1628
+ required,
1629
+ description,
1630
+ in: p.in,
1631
+ schema: {
1632
+ type,
1633
+ properties
1634
+ }
1635
+ };
1636
+ }
1637
+ /**
1638
+ * OpenAPI schema to base response
1639
+ */
1640
+ getResponseByRef(schema) {
1641
+ if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1642
+ const { schema: responseSchema } = schema;
1643
+ return [{
1644
+ type: "application/json",
1645
+ schema: responseSchema && this.getSchemaByRef(responseSchema, true)
1646
+ }];
1647
+ }
1648
+ init() {
1649
+ const { definitions = {}, responses = {}, paths = {} } = this.doc;
1650
+ const enums = [];
1651
+ const definitions_ = Object.keys(definitions).reduce((acc, key) => {
1652
+ const schema = definitions[key];
1653
+ return {
1654
+ ...acc,
1655
+ [key]: this.getSchemaByRef(schema, false, enums, key)
1656
+ };
1657
+ }, {});
1658
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1659
+ const response = responses[key];
1660
+ return {
1661
+ ...acc,
1662
+ [key]: this.getResponseByRef(response)
1663
+ };
1664
+ }, {});
1665
+ const apis = Object.keys(paths).reduce((acc, path) => {
1666
+ let pathObject = paths[path] ?? {};
1667
+ if (pathObject.$ref) {
1668
+ const resolved = this.resolvePathRef(pathObject.$ref);
1669
+ if (resolved) pathObject = resolved;
1670
+ }
1671
+ const { parameters = [] } = pathObject;
1672
+ const methodApis = [];
1673
+ Object.values(HttpMethods).forEach((method) => {
1674
+ const methodObject = pathObject[method];
1675
+ if (methodObject) {
1676
+ const { deprecated, operationId, summary: summary_, description: description_, responses = {} } = methodObject;
1677
+ const { parameters: parameters_ = [] } = methodObject;
1678
+ const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
1679
+ const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1680
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1681
+ const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
1682
+ const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
1683
+ const httpCodes = Object.keys(responses);
1684
+ for (const code of httpCodes) if (code in responses) {
1685
+ const response = responses[code];
1686
+ const responseSchema = this.getResponseByRef(response);
1687
+ const inBodyOnlyHasBody = inBody && inBody.length === 1 && inBody[0].in === "body" && inBody[0].name === "body";
1688
+ methodApis.push({
1689
+ method,
1690
+ operationId,
1691
+ summary: summary_,
1692
+ deprecated,
1693
+ description: description_,
1694
+ parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter(Boolean),
1695
+ responses: responseSchema,
1696
+ requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
1697
+ type: "application/json",
1698
+ schema: inBody[0].schema
1699
+ }] : [{
1700
+ type: "application/json",
1701
+ schema: {
1702
+ type: "object",
1703
+ properties: inBody.reduce((a, p) => {
1704
+ return {
1705
+ ...a,
1706
+ [p.name]: {
1707
+ type: p.schema?.type ?? "unknown",
1708
+ required: p.schema?.required,
1709
+ items: p.schema?.items,
1710
+ description: p.schema?.description
1711
+ }
1712
+ };
1713
+ }, {})
1714
+ }
1715
+ }] : void 0
1716
+ });
1717
+ break;
1718
+ }
1719
+ }
1720
+ });
1721
+ return {
1722
+ ...acc,
1723
+ [path]: methodApis
1724
+ };
1725
+ }, {});
1726
+ return {
1727
+ enums: Base.uniqueEnums(enums),
1728
+ schemas: definitions_,
1729
+ responses: responses_,
1730
+ parameters: {},
1731
+ requestBodies: {},
1732
+ apis
1733
+ };
1284
1734
  }
1285
1735
  };
1286
1736
  //#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 {
1737
+ //#region src/openapi/V3.ts
1738
+ var V3 = class {
1739
+ doc;
1740
+ constructor(doc) {
1741
+ this.doc = doc;
1742
+ }
1293
1743
  /**
1294
1744
  * Resolves a path $ref to the actual path object.
1295
1745
  */
@@ -1301,37 +1751,28 @@ var VersionedProvider = class {
1301
1751
  * Is array schema.
1302
1752
  */
1303
1753
  isOpenAPIArraySchema(schema) {
1304
- return typeof schema === "object" && schema !== null && schema.type === "array";
1754
+ return typeof schema === "object" && schema.type === "array";
1305
1755
  }
1306
1756
  /**
1307
- * OpenAPI schema to base schema. Override for version-specific quirks
1308
- * (V3_1 throws on missing ref; V3 returns `{ type: 'unknown' }`).
1757
+ * OpenAPI schema to base schema.
1309
1758
  */
1310
1759
  getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
1311
1760
  let refName = "";
1312
1761
  if (Base.isRef(schema)) {
1313
- refName = this.formatRefName(Base.ref2name(schema.$ref));
1762
+ refName = Base.capitalize(Base.ref2name(schema.$ref));
1314
1763
  if (reserveRef) return { type: upLevelSchemaKey + refName };
1315
- const resolvedSchema = this.getSchemaContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1764
+ const resolvedSchema = this.doc.components?.schemas?.[Base.ref2name(schema.$ref, this.doc)];
1316
1765
  if (!resolvedSchema) return { type: "unknown" };
1317
1766
  schema = resolvedSchema;
1318
1767
  }
1319
1768
  return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
1320
1769
  }
1321
1770
  /**
1322
- * Format a ref name for the schema's `type` field.
1323
- * V3 uses `capitalize`; V3_1 uses `upperCamelCase` (preserved for compat).
1324
- */
1325
- formatRefName(name) {
1326
- return Base.capitalize(name);
1327
- }
1328
- /**
1329
- * OpenAPI parameter to base parameter. Override in V2 — its parameter
1330
- * shape is structurally different (top-level `items`/`properties`/`enum`).
1771
+ * OpenAPI parameter to base parameter.
1331
1772
  */
1332
1773
  getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
1333
1774
  if (Base.isRef(schema)) {
1334
- const resolvedSchema = this.getParameterContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1775
+ const resolvedSchema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
1335
1776
  if (!resolvedSchema) return {
1336
1777
  name: "unknown",
1337
1778
  in: "query"
@@ -1362,38 +1803,37 @@ var VersionedProvider = class {
1362
1803
  description,
1363
1804
  deprecated,
1364
1805
  in: schema.in,
1365
- schema: schema.schema ? this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name)) : void 0
1806
+ schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
1366
1807
  };
1367
1808
  }
1368
1809
  /**
1369
- * OpenAPI schema to base response. Override in V2 (its response shape
1370
- * lacks the `content` wrapper).
1810
+ * OpenAPI schema to base response
1371
1811
  */
1372
1812
  getResponseByRef(schema) {
1373
1813
  if (Base.isRef(schema)) {
1374
- const resolvedSchema = this.getResponseContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1814
+ const resolvedSchema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
1375
1815
  if (!resolvedSchema) return [];
1376
1816
  schema = resolvedSchema;
1377
1817
  }
1378
1818
  const { content = {} } = schema;
1379
1819
  return Object.keys(content).map((c) => ({
1380
1820
  type: c,
1381
- schema: content[c].schema ? this.getSchemaByRef(content[c].schema, true) : void 0
1821
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
1382
1822
  }));
1383
1823
  }
1384
1824
  /**
1385
- * OpenAPI schema to requestBody. V2 has no requestBody concept.
1825
+ * OpenAPI schema to requestBody.
1386
1826
  */
1387
1827
  getRequestBodyByRef(schema, enums = []) {
1388
1828
  if (Base.isRef(schema)) {
1389
- const resolvedSchema = this.getRequestBodyContainer()?.[Base.ref2name(schema.$ref, this.doc)];
1829
+ const resolvedSchema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
1390
1830
  if (!resolvedSchema) return [];
1391
1831
  schema = resolvedSchema;
1392
1832
  }
1393
1833
  const { content = {} } = schema;
1394
1834
  return Object.keys(content).map((c) => ({
1395
1835
  type: c,
1396
- schema: content[c].schema ? this.getSchemaByRef(content[c].schema, false, enums) : void 0
1836
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, false, enums)
1397
1837
  }));
1398
1838
  }
1399
1839
  /**
@@ -1404,98 +1844,92 @@ var VersionedProvider = class {
1404
1844
  if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
1405
1845
  if (this.isOpenAPIArraySchema(schema)) {
1406
1846
  const { type, description, items, required } = schema;
1407
- const itemsSchema = items ? this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey) : { type: "unknown" };
1408
1847
  return {
1409
1848
  type,
1410
1849
  required: !!required,
1411
1850
  description,
1412
- items: itemsSchema
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_)]
1851
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
1421
1852
  };
1422
- const sameObject = Base.findSameSchema(enumObject, enums);
1423
- if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1853
+ } else {
1854
+ const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
1855
+ let { type } = schema;
1856
+ if (enum_ && type !== "boolean") {
1857
+ const enumObject = {
1858
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
1859
+ enum: [...new Set(enum_)]
1860
+ };
1861
+ const sameObject = Base.findSameSchema(enumObject, enums);
1862
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
1863
+ return {
1864
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1865
+ required,
1866
+ description,
1867
+ deprecated
1868
+ };
1869
+ }
1870
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1424
1871
  return {
1425
- type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
1872
+ type,
1426
1873
  required,
1427
1874
  description,
1428
- deprecated
1875
+ deprecated,
1876
+ enum: enum_,
1877
+ format,
1878
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
1879
+ ...s,
1880
+ ref: s.$ref,
1881
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1882
+ } : this.toBaseSchema(s, enums)),
1883
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
1884
+ ...s,
1885
+ ref: s.$ref,
1886
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1887
+ } : this.toBaseSchema(s, enums)),
1888
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
1889
+ ...s,
1890
+ ref: s.$ref,
1891
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
1892
+ } : this.toBaseSchema(s, enums)),
1893
+ properties: Object.keys(properties).reduce((acc, p) => {
1894
+ const propSchema = properties[p];
1895
+ return {
1896
+ ...acc,
1897
+ [p]: Base.isRef(propSchema) ? {
1898
+ type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
1899
+ isRef: true
1900
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1901
+ };
1902
+ }, {})
1429
1903
  };
1430
1904
  }
1431
- if (type === void 0 && Object.keys(properties).length > 0) type = "object";
1432
- return {
1433
- type,
1434
- required,
1435
- description,
1436
- deprecated,
1437
- enum: enum_,
1438
- format,
1439
- allOf: allOf?.map((s) => Base.isRef(s) ? {
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];
1456
- return {
1457
- ...acc,
1458
- [p]: Base.isRef(propSchema) ? {
1459
- type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
1460
- isRef: true
1461
- } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
1462
- };
1463
- }, {})
1464
- };
1465
1905
  }
1466
- /**
1467
- * Run the parsing pipeline and return a ProviderInitResult.
1468
- */
1469
1906
  init() {
1470
- const { paths = {} } = this.doc;
1907
+ const { components = {}, paths = {} } = this.doc;
1471
1908
  const enums = [];
1472
- const schemaContainer = this.getSchemaContainer() ?? {};
1473
- const parameterContainer = this.getParameterContainer() ?? {};
1474
- const responseContainer = this.getResponseContainer() ?? {};
1475
- const requestBodyContainer = this.getRequestBodyContainer() ?? {};
1476
- const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
1477
- const schema = schemaContainer[key];
1909
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
1910
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
1911
+ const schema = schemas[key];
1478
1912
  return {
1479
1913
  ...acc,
1480
1914
  [key]: this.getSchemaByRef(schema, false, enums, key)
1481
1915
  };
1482
1916
  }, {});
1483
- const parameters_ = Object.keys(parameterContainer).reduce((acc, key) => {
1484
- const parameter = parameterContainer[key];
1917
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
1918
+ const parameter = parameters[key];
1485
1919
  return {
1486
1920
  ...acc,
1487
1921
  [key]: this.getParameterByRef(parameter, enums, key)
1488
1922
  };
1489
1923
  }, {});
1490
- const responses_ = Object.keys(responseContainer).reduce((acc, key) => {
1491
- const response = responseContainer[key];
1924
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
1925
+ const response = responses[key];
1492
1926
  return {
1493
1927
  ...acc,
1494
1928
  [key]: this.getResponseByRef(response)
1495
1929
  };
1496
1930
  }, {});
1497
- const requestBodies_ = Object.keys(requestBodyContainer).reduce((acc, key) => {
1498
- const requestBody = requestBodyContainer[key];
1931
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
1932
+ const requestBody = requestBodies[key];
1499
1933
  return {
1500
1934
  ...acc,
1501
1935
  [key]: this.getRequestBodyByRef(requestBody, enums)
@@ -1512,16 +1946,15 @@ var VersionedProvider = class {
1512
1946
  Object.values(HttpMethods).forEach((method) => {
1513
1947
  const methodObject = pathObject[method];
1514
1948
  if (methodObject) {
1515
- const { deprecated, operationId, responses, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
1516
- const responsesClone = responses ? { ...responses } : {};
1949
+ const { deprecated, operationId, responses = {}, summary: summary_, description: description_, requestBody = { content: {} } } = methodObject;
1517
1950
  const { parameters: parameters_ = [] } = methodObject;
1518
1951
  const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
1519
1952
  const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
1520
1953
  const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1521
- if (Object.keys(responsesClone).length === 0) responsesClone[200] = { description: "Successful response" };
1522
- const httpCodes = Object.keys(responsesClone);
1523
- for (const code of httpCodes) if (code in responsesClone) {
1524
- const response = responsesClone[code];
1954
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
1955
+ const httpCodes = Object.keys(responses);
1956
+ for (const code of httpCodes) if (code in responses) {
1957
+ const response = responses[code];
1525
1958
  const responseSchema = this.getResponseByRef(response);
1526
1959
  methodApis.push({
1527
1960
  method,
@@ -1553,246 +1986,244 @@ var VersionedProvider = class {
1553
1986
  }
1554
1987
  };
1555
1988
  //#endregion
1556
- //#region src/openapi/V2.ts
1557
- var V2 = class extends VersionedProvider {
1989
+ //#region src/openapi/V3_1.ts
1990
+ var V3_1 = class {
1558
1991
  doc;
1559
- version = "v2";
1560
1992
  constructor(doc) {
1561
- super();
1562
1993
  this.doc = doc;
1563
1994
  }
1564
- getSchemaContainer() {
1565
- return this.doc.definitions;
1566
- }
1567
- getParameterContainer() {
1568
- return this.doc.parameters;
1995
+ /**
1996
+ * Resolves a path $ref to the actual path object.
1997
+ */
1998
+ resolvePathRef($ref) {
1999
+ const refName = Base.ref2name($ref, this.doc);
2000
+ return this.doc.paths?.[refName];
1569
2001
  }
1570
- getResponseContainer() {
1571
- return this.doc.responses;
2002
+ /**
2003
+ * Is array schema.
2004
+ */
2005
+ isOpenAPIArraySchema(schema) {
2006
+ return typeof schema === "object" && schema.type === "array";
1572
2007
  }
1573
- getRequestBodyContainer() {}
1574
2008
  /**
1575
- * V2 parameter shape differs from V3: top-level `items`/`properties`/`enum`
1576
- * rather than nested under `schema`. Override accordingly.
2009
+ * OpenAPI schema to base schema.
1577
2010
  */
1578
- getParameterByRef(parameter, enums = [], upLevelSchemaKey = "") {
1579
- if (Base.isRef(parameter)) {
1580
- const refName = Base.ref2name(parameter.$ref, this.doc);
1581
- const resolved = this.doc.parameters?.[refName];
1582
- if (!resolved) throw new Error(`Parameter reference not found: ${parameter.$ref}`);
1583
- parameter = resolved;
2011
+ getSchemaByRef(schema, reserveRef = false, enums = [], upLevelSchemaKey = "") {
2012
+ let refName = "";
2013
+ if (Base.isRef(schema)) {
2014
+ refName = Base.upperCamelCase(Base.ref2name(schema.$ref));
2015
+ if (reserveRef) return { type: upLevelSchemaKey + refName };
2016
+ if (!this.doc.components) this.doc.components = { schemas: {} };
2017
+ const resolvedSchema = this.doc.components.schemas?.[Base.ref2name(schema.$ref, this.doc)];
2018
+ if (!resolvedSchema) throw new Error(`Schema reference not found: ${refName}`);
2019
+ schema = resolvedSchema;
1584
2020
  }
1585
- const p = parameter;
1586
- const { name, required, description, type, items, enum: enum_, properties, schema } = p;
1587
- if (enum_) {
1588
- const enumType = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
2021
+ return this.toBaseSchema(schema, enums, "", upLevelSchemaKey + refName);
2022
+ }
2023
+ /**
2024
+ * OpenAPI parameter to base parameter.
2025
+ */
2026
+ getParameterByRef(schema, enums = [], upLevelSchemaKey = "") {
2027
+ if (Base.isRef(schema)) schema = this.doc.components?.parameters?.[Base.ref2name(schema.$ref, this.doc)];
2028
+ const { name, required, deprecated, description, schema: parameterSchema } = schema;
2029
+ if (parameterSchema && !Base.isRef(parameterSchema) && parameterSchema.enum) {
2030
+ const type = Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(name));
1589
2031
  const enumSchema = {
1590
- name: enumType,
1591
- enum: [...new Set(enum_)]
2032
+ name: type,
2033
+ enum: [...new Set(parameterSchema.enum)]
1592
2034
  };
1593
2035
  const sameEnum = Base.findSameSchema(enumSchema, enums);
1594
- if (!sameEnum && Base.isValidEnumType({
1595
- type: enumType,
1596
- enum: enum_
1597
- })) enums.push(enumSchema);
2036
+ if (!sameEnum && Base.isValidEnumType(parameterSchema)) enums.push(enumSchema);
1598
2037
  return {
1599
2038
  name,
1600
2039
  required,
1601
2040
  description,
1602
- in: p.in,
1603
- schema: { type: sameEnum?.name ?? enumType }
2041
+ deprecated,
2042
+ in: schema.in,
2043
+ schema: { type: sameEnum?.name ?? type }
1604
2044
  };
1605
2045
  }
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
2046
  return {
1624
2047
  name,
1625
2048
  required,
1626
2049
  description,
1627
- in: p.in,
1628
- schema: {
1629
- type,
1630
- properties
1631
- }
2050
+ deprecated,
2051
+ in: schema.in,
2052
+ schema: schema.schema && this.getSchemaByRef(schema.schema, false, enums, upLevelSchemaKey + Base.capitalize(name))
1632
2053
  };
1633
2054
  }
1634
2055
  /**
1635
- * V2 response shape: a `schema` field directly, not `content`. V2 always
1636
- * emits JSON.
2056
+ * OpenAPI schema to base response
1637
2057
  */
1638
2058
  getResponseByRef(schema) {
1639
- if (Base.isRef(schema)) schema = this.doc.responses[Base.ref2name(schema.$ref, this.doc)];
1640
- const { schema: responseSchema } = schema;
1641
- return [{
1642
- type: "application/json",
1643
- schema: responseSchema ? this.getSchemaByRef(responseSchema, true) : void 0
1644
- }];
2059
+ if (Base.isRef(schema)) schema = this.doc.components?.responses?.[Base.ref2name(schema.$ref, this.doc)];
2060
+ const { content = {} } = schema;
2061
+ return Object.keys(content).map((c) => ({
2062
+ type: c,
2063
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true)
2064
+ }));
2065
+ }
2066
+ /**
2067
+ * OpenAPI schema to requestBody.
2068
+ */
2069
+ getRequestBodyByRef(schema, enums = []) {
2070
+ if (Base.isRef(schema)) schema = this.doc.components?.requestBodies?.[Base.ref2name(schema.$ref, this.doc)];
2071
+ const { content = {} } = schema;
2072
+ return Object.keys(content).map((c) => ({
2073
+ type: c,
2074
+ schema: content[c].schema && this.getSchemaByRef(content[c].schema, true, enums)
2075
+ }));
1645
2076
  }
1646
2077
  /**
1647
- * V2 has no `requestBody` concept; parameters with `in: body` or
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.
2078
+ * Transform all OpenAPI schema to Base Schema
1651
2079
  */
2080
+ toBaseSchema(schema, enums = [], schemaKey = "", upLevelSchemaKey = "") {
2081
+ if (!schema) return { type: "unknown" };
2082
+ if (Base.isRef(schema)) return this.getSchemaByRef(schema, true);
2083
+ if (this.isOpenAPIArraySchema(schema)) {
2084
+ const { type, description, items, required } = schema;
2085
+ return {
2086
+ type,
2087
+ required: !!required,
2088
+ description,
2089
+ items: this.toBaseSchema(items, enums, schemaKey, upLevelSchemaKey)
2090
+ };
2091
+ } else {
2092
+ const { required = [], allOf, anyOf, description, deprecated, enum: enum_, format, oneOf, properties = {} } = schema;
2093
+ let { type } = schema;
2094
+ if (enum_ && type !== "boolean") {
2095
+ const enumObject = {
2096
+ name: Base.upperCamelCase(Base.normalize(upLevelSchemaKey)) + Base.upperCamelCase(Base.normalize(schemaKey)),
2097
+ enum: [...new Set(enum_)]
2098
+ };
2099
+ const sameObject = Base.findSameSchema(enumObject, enums);
2100
+ if (!sameObject && Base.isValidEnumType(schema)) enums.push(enumObject);
2101
+ return {
2102
+ type: sameObject ? sameObject.name : Base.isBooleanEnum(schema) ? "boolean" : enumObject.name,
2103
+ required,
2104
+ description,
2105
+ deprecated
2106
+ };
2107
+ }
2108
+ if (type === void 0 && Object.keys(properties).length > 0) type = "object";
2109
+ return {
2110
+ type,
2111
+ required,
2112
+ description,
2113
+ deprecated,
2114
+ enum: enum_,
2115
+ format,
2116
+ allOf: allOf?.map((s) => Base.isRef(s) ? {
2117
+ ...s,
2118
+ ref: s.$ref,
2119
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2120
+ } : this.toBaseSchema(s, enums)),
2121
+ anyOf: anyOf?.map((s) => Base.isRef(s) ? {
2122
+ ...s,
2123
+ ref: s.$ref,
2124
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2125
+ } : this.toBaseSchema(s, enums)),
2126
+ oneOf: oneOf?.map((s) => Base.isRef(s) ? {
2127
+ ...s,
2128
+ ref: s.$ref,
2129
+ type: Base.capitalize(Base.ref2name(s.$ref, this.doc))
2130
+ } : this.toBaseSchema(s, enums)),
2131
+ properties: Object.keys(properties).reduce((acc, p) => {
2132
+ const propSchema = properties[p];
2133
+ return {
2134
+ ...acc,
2135
+ [p]: Base.isRef(propSchema) ? {
2136
+ type: Base.capitalize(Base.ref2name(propSchema.$ref, this.doc)),
2137
+ isRef: true
2138
+ } : this.toBaseSchema(propSchema, enums, p, upLevelSchemaKey)
2139
+ };
2140
+ }, {})
2141
+ };
2142
+ }
2143
+ }
1652
2144
  init() {
1653
- const { paths = {} } = this.doc;
2145
+ const { components = {}, paths = {} } = this.doc;
1654
2146
  const enums = [];
1655
- const schemaContainer = this.getSchemaContainer() ?? {};
1656
- const parameterContainer = this.getParameterContainer() ?? {};
1657
- const responseContainer = this.getResponseContainer() ?? {};
1658
- const schemas_ = Object.keys(schemaContainer).reduce((acc, key) => {
1659
- const schema = schemaContainer[key];
2147
+ const { requestBodies = {}, responses = {}, parameters = {}, schemas = {} } = components;
2148
+ const schemas_ = Object.keys(schemas).reduce((acc, key) => {
2149
+ const schema = schemas[key];
1660
2150
  return {
1661
2151
  ...acc,
1662
2152
  [key]: this.getSchemaByRef(schema, false, enums, key)
1663
2153
  };
1664
2154
  }, {});
1665
- const parameters_ = Object.keys(parameterContainer).reduce((acc, key) => {
1666
- const parameter = parameterContainer[key];
2155
+ const parameters_ = Object.keys(parameters).reduce((acc, key) => {
2156
+ const parameter = parameters[key];
1667
2157
  return {
1668
2158
  ...acc,
1669
2159
  [key]: this.getParameterByRef(parameter, enums, key)
1670
2160
  };
1671
2161
  }, {});
1672
- const responses_ = Object.keys(responseContainer).reduce((acc, key) => {
1673
- const response = responseContainer[key];
2162
+ const responses_ = Object.keys(responses).reduce((acc, key) => {
2163
+ const response = responses[key];
1674
2164
  return {
1675
2165
  ...acc,
1676
2166
  [key]: this.getResponseByRef(response)
1677
2167
  };
1678
2168
  }, {});
1679
- const apis = {};
1680
- for (const path of Object.keys(paths)) {
2169
+ const requestBodies_ = Object.keys(requestBodies).reduce((acc, key) => {
2170
+ const requestBody = requestBodies[key];
2171
+ return {
2172
+ ...acc,
2173
+ [key]: this.getRequestBodyByRef(requestBody, enums)
2174
+ };
2175
+ }, {});
2176
+ const apis = Object.keys(paths).reduce((acc, path) => {
1681
2177
  let pathObject = paths[path] ?? {};
1682
2178
  if (pathObject.$ref) {
1683
2179
  const resolved = this.resolvePathRef(pathObject.$ref);
1684
2180
  if (resolved) pathObject = resolved;
1685
2181
  }
1686
- const { parameters = [] } = pathObject;
2182
+ const { parameters = [], description, summary } = pathObject;
1687
2183
  const methodApis = [];
1688
2184
  Object.values(HttpMethods).forEach((method) => {
1689
2185
  const methodObject = pathObject[method];
1690
- if (!methodObject) return;
1691
- const { deprecated, operationId, summary: summary_, description: description_, responses } = methodObject;
1692
- const { parameters: parameters_ = [] } = methodObject;
1693
- const baseParameters = [...parameters, ...parameters_].map((p) => this.getParameterByRef(p, enums));
1694
- const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
1695
- const responsesClone = responses ? { ...responses } : {};
1696
- if (Object.keys(responsesClone).length === 0) responsesClone[200] = { description: "Successful response" };
1697
- const inBody = baseParameters.filter((p) => p.in === "body" || p.in === "formData");
1698
- const notInBody = baseParameters.filter((p) => p.in !== "body" && p.in !== "formData");
1699
- const httpCodes = Object.keys(responsesClone);
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";
1704
- methodApis.push({
1705
- method,
1706
- operationId,
1707
- summary: summary_,
1708
- deprecated,
1709
- description: description_,
1710
- parameters: uniqueParameterName.map((name) => notInBody.find((p) => p.name === name)).filter((p) => p !== void 0),
1711
- responses: responseSchema,
1712
- requestBody: inBody.length > 0 ? inBodyOnlyHasBody ? [{
1713
- type: "application/json",
1714
- schema: inBody[0].schema
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
1732
- });
1733
- break;
2186
+ if (methodObject) {
2187
+ const { deprecated, operationId, summary: summary_, description: description_, responses = {}, requestBody = { content: {} } } = methodObject;
2188
+ const { parameters: parameters_ = [] } = methodObject;
2189
+ const baseParameters = [...parameters, ...parameters_].map((parameter) => this.getParameterByRef(parameter, enums));
2190
+ const baseRequestBody = this.getRequestBodyByRef(requestBody, enums);
2191
+ const uniqueParameterName = [...new Set(baseParameters.map((p) => p.name))];
2192
+ if (Object.keys(responses).length === 0) Object.assign(responses, { 200: { description: "Successful response" } });
2193
+ const httpCodes = Object.keys(responses);
2194
+ for (const code of httpCodes) if (code in responses) {
2195
+ const response = responses[code];
2196
+ const responseSchema = this.getResponseByRef(response);
2197
+ methodApis.push({
2198
+ method,
2199
+ operationId,
2200
+ summary: summary_ ?? summary,
2201
+ description: description_ ?? description,
2202
+ deprecated,
2203
+ parameters: uniqueParameterName.map((name) => baseParameters.find((p) => p.name === name)).filter((p) => p !== void 0),
2204
+ responses: responseSchema,
2205
+ requestBody: baseRequestBody
2206
+ });
2207
+ break;
2208
+ }
1734
2209
  }
1735
2210
  });
1736
- apis[path] = methodApis;
1737
- }
2211
+ return {
2212
+ ...acc,
2213
+ [path]: methodApis
2214
+ };
2215
+ }, {});
1738
2216
  return {
1739
2217
  enums: Base.uniqueEnums(enums),
1740
2218
  schemas: schemas_,
1741
2219
  responses: responses_,
1742
2220
  parameters: parameters_,
1743
- requestBodies: {},
2221
+ requestBodies: requestBodies_,
1744
2222
  apis
1745
2223
  };
1746
2224
  }
1747
2225
  };
1748
2226
  //#endregion
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
2227
  //#region src/openapi/index.ts
1797
2228
  const logger$1 = (0, _moccona_logger.createScopedLogger)("OpenAPI");
1798
2229
  let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
@@ -1803,7 +2234,9 @@ let OpenAPIVersion = /* @__PURE__ */ function(OpenAPIVersion) {
1803
2234
  return OpenAPIVersion;
1804
2235
  }({});
1805
2236
  function getDocVersion(doc) {
1806
- switch ((doc.openapi || doc.swagger).slice(0, 3)) {
2237
+ const raw = doc.openapi || doc.swagger;
2238
+ if (typeof raw !== "string" || raw.length === 0) return "unknown";
2239
+ switch (raw.slice(0, 3)) {
1807
2240
  case "3.1": return "v3_1";
1808
2241
  case "3.0": return "v3";
1809
2242
  case "2.0": return "v2";
@@ -1834,7 +2267,21 @@ async function codeGen(initOptions) {
1834
2267
  if (verbose) logger$1.setLevel("debug");
1835
2268
  else logger$1.setLevel("info");
1836
2269
  logger$1.info(`Fetch document from ${initOptions.docURL}`);
1837
- const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, await Base.fetchDoc(initOptions.docURL, initOptions.requestOptions));
2270
+ const { transport, source } = Base.resolveSpecURL(initOptions.docURL);
2271
+ const { enums, schemas, parameters, responses, requestBodies, apis } = new OpenAPIProvider(initOptions, transport === "file" ? await (async () => {
2272
+ let raw;
2273
+ try {
2274
+ raw = await (0, node_fs_promises.readFile)(source, "utf8");
2275
+ } catch (error) {
2276
+ if (error?.code === "ENOENT") throw createErrors.specNotFound(source, error);
2277
+ throw new Error(`Failed to read OpenAPI spec from ${source}: ${error instanceof Error ? error.message : String(error)}`);
2278
+ }
2279
+ try {
2280
+ return JSON.parse(raw);
2281
+ } catch (error) {
2282
+ throw createErrors.specParseFailed(source, void 0, void 0, error);
2283
+ }
2284
+ })() : await Base.fetchDoc(source, initOptions.requestOptions));
1838
2285
  const adaptor = getAdaptor(initOptions.adaptor ?? "fetch");
1839
2286
  const code = await Generator.genCode({
1840
2287
  enums,
@@ -1856,61 +2303,95 @@ async function codeGen(initOptions) {
1856
2303
  };
1857
2304
  }
1858
2305
  //#endregion
1859
- //#region src/vite-plugin/index.ts
1860
- const PLUGIN_NAME = "api-code-gen";
1861
- const pluginLogger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
2306
+ //#region src/vite-plugin/cache.ts
1862
2307
  /**
1863
- * Find the nearest tsconfig.json or jsconfig.json by searching upward.
1864
- * Bounded by process.cwd() — the Vite project root — to avoid picking up
1865
- * unrelated configs outside the project.
2308
+ * Cache for a single vite-plugin codegen run. Lives only for the duration
2309
+ * of one plugin invocation — there is no module-level state.
2310
+ *
2311
+ * Cache files are stored at:
2312
+ *
2313
+ * <cacheDir>/<optionsHash>.json
2314
+ *
2315
+ * where `<cacheDir>` defaults to `node_modules/.cache/apicodegen` but can
2316
+ * be overridden via `cacheDir`.
1866
2317
  */
1867
- async function findNearestTsConfig(filePath) {
1868
- let dir = node_path.default.dirname(node_path.default.resolve(filePath));
1869
- const rootDir = process.cwd();
1870
- const fsRoot = node_path.default.parse(dir).root;
1871
- while (true) {
1872
- for (const name of ["tsconfig.json", "jsconfig.json"]) {
1873
- const configPath = node_path.default.join(dir, name);
1874
- if (await fs_extra.default.pathExists(configPath)) return configPath;
2318
+ var CodegenCache = class CodegenCache {
2319
+ cacheDir;
2320
+ constructor(cacheDir) {
2321
+ this.cacheDir = cacheDir;
2322
+ }
2323
+ /** Hash the options that affect generated output (excluding the spec). */
2324
+ static hashOptions(options) {
2325
+ const payload = Object.keys(options).sort().filter((k) => k !== "verbose" && k !== "typeCheck" && k !== "cache").map((k) => `${k}=${JSON.stringify(options[k])}`).join("|");
2326
+ return (0, node_crypto.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
2327
+ }
2328
+ /** Hash the raw spec content so unrelated edits are detected. */
2329
+ static hashContent(content) {
2330
+ return (0, node_crypto.createHash)("sha256").update(content).digest("hex").slice(0, 16);
2331
+ }
2332
+ /**
2333
+ * Look up a cached entry. Returns `null` on miss / corruption / disabled.
2334
+ *
2335
+ * @param optionsHash Options hash from `hashOptions`.
2336
+ * @param specSource Resolved spec path or URL. Local paths use mtime +
2337
+ * content hash; URLs always miss (no cache).
2338
+ */
2339
+ async lookup(optionsHash, specSource) {
2340
+ const cachePath = node_path.default.join(this.cacheDir, `${optionsHash}.json`);
2341
+ let raw;
2342
+ try {
2343
+ raw = await (0, node_fs_promises.readFile)(cachePath, "utf8");
2344
+ } catch {
2345
+ return null;
2346
+ }
2347
+ let entry;
2348
+ try {
2349
+ entry = JSON.parse(raw);
2350
+ } catch {
2351
+ return null;
2352
+ }
2353
+ if (entry.optionsHash !== optionsHash) return null;
2354
+ if (specSource.startsWith("http://") || specSource.startsWith("https://")) return null;
2355
+ let currentMtimeMs;
2356
+ try {
2357
+ currentMtimeMs = (await (0, node_fs_promises.stat)(specSource)).mtimeMs;
2358
+ } catch {
2359
+ return null;
2360
+ }
2361
+ if (currentMtimeMs !== entry.specMtimeMs) return null;
2362
+ if (entry.specContentHash) {
2363
+ let content;
2364
+ try {
2365
+ content = await (0, node_fs_promises.readFile)(specSource, "utf8");
2366
+ } catch {
2367
+ return null;
2368
+ }
2369
+ if (CodegenCache.hashContent(content) !== entry.specContentHash) return null;
1875
2370
  }
1876
- if (dir === rootDir || dir === fsRoot) break;
1877
- dir = node_path.default.dirname(dir);
2371
+ return entry;
1878
2372
  }
1879
- return null;
1880
- }
2373
+ /** Persist a successful codegen result. */
2374
+ async store(entry) {
2375
+ const cachePath = node_path.default.join(this.cacheDir, `${entry.optionsHash}.json`);
2376
+ const dir = node_path.default.dirname(cachePath);
2377
+ await import("fs-extra").then((fs) => fs.ensureDir(dir));
2378
+ await (0, node_fs_promises.writeFile)(cachePath, JSON.stringify(entry));
2379
+ }
2380
+ };
2381
+ //#endregion
2382
+ //#region src/vite-plugin/index.ts
2383
+ const PLUGIN_NAME = "api-code-gen";
2384
+ const logger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
1881
2385
  /**
1882
2386
  * Run TypeScript type checking on generated file
1883
2387
  */
1884
2388
  async function runTypeCheck(filePath) {
1885
2389
  const { execaCommand } = await import("execa");
1886
2390
  const errors = [];
1887
- const resolvedPath = node_path.default.resolve(filePath);
1888
- const tsconfigPath = await findNearestTsConfig(resolvedPath);
1889
- if (!tsconfigPath) {
1890
- try {
1891
- await execaCommand(`npx tsc ${resolvedPath} --noEmit`, { shell: true });
1892
- } catch (error) {
1893
- if (error instanceof Error) errors.push(error.message);
1894
- }
1895
- return errors;
1896
- }
1897
- const outputDir = node_path.default.dirname(resolvedPath);
1898
- const tempConfigName = `.${node_path.default.basename(resolvedPath).replace(/\.ts$/i, "")}.${Date.now()}.apicodegen.json`;
1899
- const tempConfigPath = node_path.default.join(outputDir, tempConfigName);
1900
- const tempConfig = {
1901
- extends: node_path.default.relative(outputDir, tsconfigPath),
1902
- compilerOptions: { noEmit: true },
1903
- include: [node_path.default.basename(resolvedPath)]
1904
- };
1905
2391
  try {
1906
- await fs_extra.default.writeJson(tempConfigPath, tempConfig);
1907
- await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
2392
+ await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
1908
2393
  } catch (error) {
1909
2394
  if (error instanceof Error) errors.push(error.message);
1910
- } finally {
1911
- try {
1912
- await fs_extra.default.remove(tempConfigPath);
1913
- } catch {}
1914
2395
  }
1915
2396
  return errors;
1916
2397
  }
@@ -1927,9 +2408,9 @@ async function validateSpecPath(specPath) {
1927
2408
  * Generate code for a single API configuration
1928
2409
  */
1929
2410
  async function generateForOption(option) {
1930
- const { name, typeCheck = true, verbose, ...restOptions } = option;
2411
+ const { name, typeCheck = true, verbose, cache = true, cacheDir, ...restOptions } = option;
1931
2412
  try {
1932
- logger.info(`Generating ${name}...`);
2413
+ console.log(`\x1b[36m├─\x1b[0m ${name}`);
1933
2414
  const config = await loadConfig({
1934
2415
  name,
1935
2416
  cliOptions: {
@@ -1943,25 +2424,69 @@ async function generateForOption(option) {
1943
2424
  await fs_extra.default.ensureDir(outputDir);
1944
2425
  }
1945
2426
  let docURL = config.spec;
1946
- if (!docURL.startsWith("http://") && !docURL.startsWith("https://")) if (docURL.startsWith("/") || docURL.match(/^[A-Za-z]:/)) docURL = `file://${docURL}`;
1947
- else docURL = node_path.default.resolve(process.cwd(), docURL);
1948
- const result = await codeGen({
1949
- ...toProviderOptions(config),
1950
- docURL
2427
+ 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);
2428
+ const resolvedCacheDir = cacheDir ?? node_path.default.join(process.cwd(), "node_modules", ".cache", "apicodegen");
2429
+ const codegenCache = cache ? new CodegenCache(resolvedCacheDir) : null;
2430
+ const optionsHash = CodegenCache.hashOptions({
2431
+ name,
2432
+ spec: docURL,
2433
+ output: config.output,
2434
+ adaptor: config.adaptor,
2435
+ baseURL: config.baseURL,
2436
+ importClientSource: config.importClientSource
1951
2437
  });
2438
+ let result = null;
2439
+ let cached = false;
2440
+ if (codegenCache) {
2441
+ const cachedEntry = await codegenCache.lookup(optionsHash, docURL);
2442
+ if (cachedEntry) {
2443
+ result = {
2444
+ code: cachedEntry.code,
2445
+ stats: cachedEntry.stats
2446
+ };
2447
+ cached = true;
2448
+ if (verbose) logger.debug(`Cache hit for ${name} (${optionsHash})`);
2449
+ }
2450
+ }
2451
+ if (!result) {
2452
+ result = await codeGen({
2453
+ ...toProviderOptions(config),
2454
+ docURL
2455
+ });
2456
+ if (codegenCache) try {
2457
+ const fsPromises = await import("node:fs/promises");
2458
+ let specMtimeMs;
2459
+ let specContentHash;
2460
+ if (!(docURL.startsWith("http://") || docURL.startsWith("https://"))) try {
2461
+ specMtimeMs = (await fsPromises.stat(docURL)).mtimeMs;
2462
+ const content = await fsPromises.readFile(docURL, "utf8");
2463
+ specContentHash = CodegenCache.hashContent(content);
2464
+ } catch {}
2465
+ await codegenCache.store({
2466
+ optionsHash,
2467
+ specMtimeMs,
2468
+ specContentHash,
2469
+ code: result.code,
2470
+ stats: result.stats
2471
+ });
2472
+ } catch (cacheError) {
2473
+ if (verbose) logger.warn(`Cache write failed for ${name}: ${cacheError.message}`);
2474
+ }
2475
+ }
1952
2476
  if (config.output) await fs_extra.default.writeFile(config.output, result.code);
1953
2477
  if (typeCheck && config.output) {
1954
2478
  const typeErrors = await runTypeCheck(config.output);
1955
2479
  if (typeErrors.length > 0) {
1956
- pluginLogger.warn(`Type check failed for ${config.output}`);
1957
- if (verbose) for (const error of typeErrors) pluginLogger.warn(` ${error}`);
2480
+ logger.warn(`Type check failed for ${config.output}`);
2481
+ if (verbose) for (const error of typeErrors) logger.warn(` ${error}`);
1958
2482
  }
1959
2483
  }
1960
2484
  return {
1961
2485
  success: true,
1962
2486
  name,
1963
2487
  output: config.output,
1964
- stats: result.stats
2488
+ stats: result.stats,
2489
+ cached
1965
2490
  };
1966
2491
  } catch (error) {
1967
2492
  return {
@@ -1995,47 +2520,47 @@ async function generateForOption(option) {
1995
2520
  */
1996
2521
  function apiCodeGenPlugin(options) {
1997
2522
  if (!Array.isArray(options) || options.length === 0) {
1998
- pluginLogger.warn("No API configurations provided to apiCodeGenPlugin");
2523
+ logger.warn("No API configurations provided to apiCodeGenPlugin");
1999
2524
  return { name: PLUGIN_NAME };
2000
2525
  }
2001
2526
  return {
2002
2527
  name: PLUGIN_NAME,
2003
2528
  async config(_config, env) {
2004
- logger.heading("API Code Gen", env?.command);
2529
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2530
+ console.log(`\x1b[1m\x1b[36mAPI Code Gen\x1b[0m`);
2531
+ console.log(`\x1b[90mMode:\x1b[0m ${env?.command || "unknown"}`);
2532
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2005
2533
  const results = await Promise.all(options.map(generateForOption));
2006
2534
  const successCount = results.filter((r) => r.success).length;
2007
2535
  const failCount = options.length - successCount;
2008
- logger.divider();
2536
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2009
2537
  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");
2538
+ const { name, output, stats, cached } = result;
2539
+ if (stats) {
2540
+ const cachedTag = cached ? " \x1B[90m[cached]\x1B[0m" : "";
2541
+ console.log(`\x1b[32m✓\x1b[0m ${name} → ${output} (${stats.endpoints} endpoints, ${stats.schemas} schemas) ${stats.duration}ms${cachedTag}`);
2542
+ } else console.log(`\x1b[32m✓\x1b[0m ${name} → ${output || "N/A"}`);
2013
2543
  } else {
2014
2544
  const { name, error } = result;
2015
2545
  if (isApicodegenError(error)) {
2016
- logger.item(name, "red");
2017
- logger.error(error, true);
2546
+ console.log(`\x1b[31m✗\x1b[0m ${name}`);
2547
+ console.log(`\x1b[90m${formatError(error, true)}\x1b[0m`);
2018
2548
  } else {
2019
2549
  const wrapped = wrapError(error, {
2020
- code: ErrorCodes.GENERATION_FAILED,
2550
+ code: "E_GENERATION_FAILED",
2021
2551
  message: `Failed to generate API "${name}"`
2022
2552
  });
2023
- logger.item(name, "red");
2024
- logger.error(wrapped, true);
2553
+ console.log(`\x1b[31m✗\x1b[0m ${name}`);
2554
+ console.log(`\x1b[90m${formatError(wrapped, true)}\x1b[0m`);
2025
2555
  }
2026
2556
  }
2027
- logger.divider();
2557
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2028
2558
  const totalDuration = results.reduce((sum, r) => sum + (r.stats?.duration || 0), 0);
2029
2559
  const totalEndpoints = results.reduce((sum, r) => sum + (r.stats?.endpoints || 0), 0);
2030
2560
  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();
2561
+ if (failCount === 0) console.log(`\x1b[32m✓\x1b[0m API Code Gen - Complete (\x1b[90m${successCount}/${options.length} succeeded\x1b[0m, ${totalEndpoints} endpoints, ${totalSchemas} schemas, ${totalDuration}ms\x1b[0m)`);
2562
+ 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)`);
2563
+ console.log(`\x1b[1m\x1b[36m${"─".repeat(50)}\x1b[0m`);
2039
2564
  return {};
2040
2565
  }
2041
2566
  };
@@ -2063,13 +2588,15 @@ exports.SchemaType = SchemaType;
2063
2588
  exports.SuccessHttpStatusCode = SuccessHttpStatusCode;
2064
2589
  exports.apiCodeGenPlugin = apiCodeGenPlugin;
2065
2590
  exports.codeGen = codeGen;
2591
+ exports.configToCLIOptions = configToCLIOptions;
2066
2592
  exports.createErrors = createErrors;
2067
2593
  exports.formatError = formatError;
2068
2594
  exports.isApicodegenError = isApicodegenError;
2069
2595
  exports.loadConfig = loadConfig;
2070
- exports.logger = logger;
2596
+ exports.mergeConfigs = mergeConfigs;
2071
2597
  exports.printError = printError;
2072
2598
  exports.toProviderOptions = toProviderOptions;
2599
+ exports.validateConfig = validateConfig;
2073
2600
  exports.wrapError = wrapError;
2074
2601
 
2075
2602
  //# sourceMappingURL=index.cjs.map