@moccona/apicodegen 0.1.1 → 1.0.0

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