@kubb/core 5.0.0-alpha.7 → 5.0.0-alpha.70

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.
Files changed (69) hide show
  1. package/README.md +3 -2
  2. package/dist/PluginDriver-BXibeQk-.cjs +1036 -0
  3. package/dist/PluginDriver-BXibeQk-.cjs.map +1 -0
  4. package/dist/PluginDriver-DV3p2Hky.js +945 -0
  5. package/dist/PluginDriver-DV3p2Hky.js.map +1 -0
  6. package/dist/index.cjs +730 -1773
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +289 -240
  9. package/dist/index.js +717 -1741
  10. package/dist/index.js.map +1 -1
  11. package/dist/mocks.cjs +139 -0
  12. package/dist/mocks.cjs.map +1 -0
  13. package/dist/mocks.d.ts +74 -0
  14. package/dist/mocks.js +134 -0
  15. package/dist/mocks.js.map +1 -0
  16. package/dist/types-DWtkW2RX.d.ts +1915 -0
  17. package/package.json +51 -57
  18. package/src/FileManager.ts +115 -0
  19. package/src/FileProcessor.ts +86 -0
  20. package/src/Kubb.ts +205 -130
  21. package/src/PluginDriver.ts +326 -565
  22. package/src/constants.ts +20 -47
  23. package/src/createAdapter.ts +25 -0
  24. package/src/createKubb.ts +546 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +58 -0
  27. package/src/defineGenerator.ts +88 -100
  28. package/src/defineLogger.ts +13 -3
  29. package/src/defineMiddleware.ts +64 -0
  30. package/src/defineParser.ts +45 -0
  31. package/src/definePlugin.ts +78 -7
  32. package/src/defineResolver.ts +521 -0
  33. package/src/devtools.ts +14 -14
  34. package/src/index.ts +13 -16
  35. package/src/mocks.ts +172 -0
  36. package/src/renderNode.ts +35 -0
  37. package/src/storages/fsStorage.ts +43 -13
  38. package/src/storages/memoryStorage.ts +6 -4
  39. package/src/types.ts +752 -226
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/isInputPath.ts +10 -0
  42. package/src/utils/packageJSON.ts +99 -0
  43. package/dist/PluginDriver-Dma9KhLK.d.ts +0 -1056
  44. package/dist/chunk-ByKO4r7w.cjs +0 -38
  45. package/dist/hooks.cjs +0 -102
  46. package/dist/hooks.cjs.map +0 -1
  47. package/dist/hooks.d.ts +0 -75
  48. package/dist/hooks.js +0 -97
  49. package/dist/hooks.js.map +0 -1
  50. package/src/PackageManager.ts +0 -180
  51. package/src/build.ts +0 -419
  52. package/src/config.ts +0 -56
  53. package/src/defineAdapter.ts +0 -22
  54. package/src/defineStorage.ts +0 -56
  55. package/src/errors.ts +0 -1
  56. package/src/hooks/index.ts +0 -4
  57. package/src/hooks/useKubb.ts +0 -138
  58. package/src/hooks/useMode.ts +0 -11
  59. package/src/hooks/usePlugin.ts +0 -11
  60. package/src/hooks/usePluginDriver.ts +0 -11
  61. package/src/utils/FunctionParams.ts +0 -155
  62. package/src/utils/TreeNode.ts +0 -215
  63. package/src/utils/executeStrategies.ts +0 -81
  64. package/src/utils/formatters.ts +0 -56
  65. package/src/utils/getBarrelFiles.ts +0 -141
  66. package/src/utils/getConfigs.ts +0 -30
  67. package/src/utils/getPlugins.ts +0 -23
  68. package/src/utils/linters.ts +0 -25
  69. package/src/utils/resolveOptions.ts +0 -93
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#emitter","EventEmitter","posix","#options","#transformParam","#eachParam","#head","#tail","#size","#plugins","#usedPluginNames","#parse","#studioIsOpen","openInStudioFn","#getSortedPlugins","#execute","#executeSync","performance","#emitProcessingEnd","fsPlugin","typescriptParser","#cache","#cwd","mod","os","pkg","#match","#items","#orderItems","#addParams","#cachedLeaves","path"],"sources":["../../../internals/utils/dist/index.js","../src/config.ts","../src/constants.ts","../src/devtools.ts","../../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js","../../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js","../src/utils/executeStrategies.ts","../src/PluginDriver.ts","../src/defineStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/build.ts","../src/defineAdapter.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/definePlugin.ts","../src/PackageManager.ts","../src/storages/memoryStorage.ts","../src/utils/FunctionParams.ts","../src/utils/formatters.ts","../src/utils/TreeNode.ts","../src/utils/getBarrelFiles.ts","../src/utils/getPlugins.ts","../src/utils/getConfigs.ts","../src/utils/linters.ts","../src/utils/resolveOptions.ts"],"sourcesContent":["import \"./chunk--u3MIqq1.js\";\nimport { EventEmitter } from \"node:events\";\nimport { parseArgs, styleText } from \"node:util\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { access, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, posix, resolve } from \"node:path\";\nimport { promises } from \"node:dns\";\nimport { spawn } from \"node:child_process\";\n//#region src/errors.ts\n/** Thrown when a plugin's configuration or input fails validation. */\nvar ValidationPluginError = class extends Error {};\n/**\n* Thrown when one or more errors occur during a Kubb build.\n* Carries the full list of underlying errors on `errors`.\n*/\nvar BuildError = class extends Error {\n\terrors;\n\tconstructor(message, options) {\n\t\tsuper(message, { cause: options.cause });\n\t\tthis.name = \"BuildError\";\n\t\tthis.errors = options.errors;\n\t}\n};\n/**\n* Coerces an unknown thrown value to an `Error` instance.\n* When the value is already an `Error` it is returned as-is;\n* otherwise a new `Error` is created whose message is `String(value)`.\n*/\nfunction toError(value) {\n\treturn value instanceof Error ? value : new Error(String(value));\n}\n/**\n* Safely extracts a human-readable message from any thrown value.\n*/\nfunction getErrorMessage(value) {\n\treturn value instanceof Error ? value.message : String(value);\n}\n/**\n* Extracts the `.cause` of an `Error` as an `Error | undefined`.\n* Returns `undefined` when the cause is absent or is not an `Error`.\n*/\nfunction toCause(error) {\n\treturn error.cause instanceof Error ? error.cause : void 0;\n}\n//#endregion\n//#region src/asyncEventEmitter.ts\n/**\n* A typed EventEmitter that awaits all async listeners before resolving.\n* Wraps Node's `EventEmitter` with full TypeScript event-map inference.\n*/\nvar AsyncEventEmitter = class {\n\t/**\n\t* `maxListener` controls the maximum number of listeners per event before Node emits a memory-leak warning.\n\t* @default 10\n\t*/\n\tconstructor(maxListener = 10) {\n\t\tthis.#emitter.setMaxListeners(maxListener);\n\t}\n\t#emitter = new EventEmitter();\n\t/**\n\t* Emits an event and awaits all registered listeners in parallel.\n\t* Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.\n\t*/\n\tasync emit(eventName, ...eventArgs) {\n\t\tconst listeners = this.#emitter.listeners(eventName);\n\t\tif (listeners.length === 0) return;\n\t\tawait Promise.all(listeners.map(async (listener) => {\n\t\t\ttry {\n\t\t\t\treturn await listener(...eventArgs);\n\t\t\t} catch (err) {\n\t\t\t\tlet serializedArgs;\n\t\t\t\ttry {\n\t\t\t\t\tserializedArgs = JSON.stringify(eventArgs);\n\t\t\t\t} catch {\n\t\t\t\t\tserializedArgs = String(eventArgs);\n\t\t\t\t}\n\t\t\t\tthrow new Error(`Error in async listener for \"${eventName}\" with eventArgs ${serializedArgs}`, { cause: toError(err) });\n\t\t\t}\n\t\t}));\n\t}\n\t/** Registers a persistent listener for the given event. */\n\ton(eventName, handler) {\n\t\tthis.#emitter.on(eventName, handler);\n\t}\n\t/** Registers a one-shot listener that removes itself after the first invocation. */\n\tonOnce(eventName, handler) {\n\t\tconst wrapper = (...args) => {\n\t\t\tthis.off(eventName, wrapper);\n\t\t\treturn handler(...args);\n\t\t};\n\t\tthis.on(eventName, wrapper);\n\t}\n\t/** Removes a previously registered listener. */\n\toff(eventName, handler) {\n\t\tthis.#emitter.off(eventName, handler);\n\t}\n\t/** Removes all listeners from every event channel. */\n\tremoveAll() {\n\t\tthis.#emitter.removeAllListeners();\n\t}\n};\n//#endregion\n//#region src/casing.ts\n/**\n* Shared implementation for camelCase and PascalCase conversion.\n* Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n* and capitalizes each word according to `pascal`.\n*\n* When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n*/\nfunction toCamelOrPascal(text, pascal) {\n\treturn text.trim().replace(/([a-z\\d])([A-Z])/g, \"$1 $2\").replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\").replace(/(\\d)([a-z])/g, \"$1 $2\").split(/[\\s\\-_./\\\\:]+/).filter(Boolean).map((word, i) => {\n\t\tif (word.length > 1 && word === word.toUpperCase()) return word;\n\t\tif (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);\n\t\treturn word.charAt(0).toUpperCase() + word.slice(1);\n\t}).join(\"\").replace(/[^a-zA-Z0-9]/g, \"\");\n}\n/**\n* Splits `text` on `.` and applies `transformPart` to each segment.\n* The last segment receives `isLast = true`, all earlier segments receive `false`.\n* Segments are joined with `/` to form a file path.\n*/\nfunction applyToFileParts(text, transformPart) {\n\tconst parts = text.split(\".\");\n\treturn parts.map((part, i) => transformPart(part, i === parts.length - 1)).join(\"/\");\n}\n/**\n* Converts `text` to camelCase.\n* When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n*\n* @example\n* camelCase('hello-world') // 'helloWorld'\n* camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n*/\nfunction camelCase(text, { isFile, prefix = \"\", suffix = \"\" } = {}) {\n\tif (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {\n\t\tprefix,\n\t\tsuffix\n\t} : {}));\n\treturn toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);\n}\n/**\n* Converts `text` to PascalCase.\n* When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n*\n* @example\n* pascalCase('hello-world') // 'HelloWorld'\n* pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n*/\nfunction pascalCase(text, { isFile, prefix = \"\", suffix = \"\" } = {}) {\n\tif (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {\n\t\tprefix,\n\t\tsuffix\n\t}) : camelCase(part));\n\treturn toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);\n}\n/**\n* Converts `text` to snake_case.\n*\n* @example\n* snakeCase('helloWorld') // 'hello_world'\n* snakeCase('Hello-World') // 'hello_world'\n*/\nfunction snakeCase(text, { prefix = \"\", suffix = \"\" } = {}) {\n\treturn `${prefix} ${text} ${suffix}`.trim().replace(/([a-z])([A-Z])/g, \"$1_$2\").replace(/[\\s\\-.]+/g, \"_\").replace(/[^a-zA-Z0-9_]/g, \"\").toLowerCase().split(\"_\").filter(Boolean).join(\"_\");\n}\n/**\n* Converts `text` to SCREAMING_SNAKE_CASE.\n*\n* @example\n* screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n*/\nfunction screamingSnakeCase(text, { prefix = \"\", suffix = \"\" } = {}) {\n\treturn snakeCase(text, {\n\t\tprefix,\n\t\tsuffix\n\t}).toUpperCase();\n}\n//#endregion\n//#region src/cli/define.ts\n/** Returns a `CLIAdapter` with type inference. Pass a different adapter to `createCLI` to swap the CLI engine. */\nfunction defineCLIAdapter(adapter) {\n\treturn adapter;\n}\n/**\n* Returns a `CommandDefinition` with typed `values` in `run()`.\n* The callback receives `values` typed from the declared options — no casts needed.\n*/\nfunction defineCommand(def) {\n\tconst { run, ...rest } = def;\n\tif (!run) return rest;\n\treturn {\n\t\t...rest,\n\t\trun: (args) => run({\n\t\t\tvalues: args.values,\n\t\t\tpositionals: args.positionals\n\t\t})\n\t};\n}\n//#endregion\n//#region src/cli/schema.ts\n/**\n* Serializes `CommandDefinition[]` to a plain, JSON-serializable structure.\n* Use to expose CLI capabilities to AI agents or MCP tools.\n*/\nfunction getCommandSchema(defs) {\n\treturn defs.map(serializeCommand);\n}\nfunction serializeCommand(def) {\n\treturn {\n\t\tname: def.name,\n\t\tdescription: def.description,\n\t\targuments: def.arguments,\n\t\toptions: serializeOptions(def.options ?? {}),\n\t\tsubCommands: def.subCommands ? def.subCommands.map(serializeCommand) : []\n\t};\n}\nfunction serializeOptions(options) {\n\treturn Object.entries(options).map(([name, opt]) => {\n\t\treturn {\n\t\t\tname,\n\t\t\tflags: `${opt.short ? `-${opt.short}, ` : \"\"}--${name}${opt.type === \"string\" ? ` <${opt.hint ?? name}>` : \"\"}`,\n\t\t\ttype: opt.type,\n\t\t\tdescription: opt.description,\n\t\t\t...opt.default !== void 0 ? { default: opt.default } : {},\n\t\t\t...opt.hint ? { hint: opt.hint } : {},\n\t\t\t...opt.enum ? { enum: opt.enum } : {},\n\t\t\t...opt.required ? { required: opt.required } : {}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/cli/help.ts\n/** Prints formatted help output for a command using its `CommandDefinition`. */\nfunction renderHelp(def, parentName) {\n\tconst schema = getCommandSchema([def])[0];\n\tconst programName = parentName ? `${parentName} ${schema.name}` : schema.name;\n\tconst argsPart = schema.arguments?.length ? ` ${schema.arguments.join(\" \")}` : \"\";\n\tconst subCmdPart = schema.subCommands.length ? \" <command>\" : \"\";\n\tconsole.log(`\\n${styleText(\"bold\", \"Usage:\")} ${programName}${argsPart}${subCmdPart} [options]\\n`);\n\tif (schema.description) console.log(` ${schema.description}\\n`);\n\tif (schema.subCommands.length) {\n\t\tconsole.log(styleText(\"bold\", \"Commands:\"));\n\t\tfor (const sub of schema.subCommands) console.log(` ${styleText(\"cyan\", sub.name.padEnd(16))}${sub.description}`);\n\t\tconsole.log();\n\t}\n\tconst options = [...schema.options, {\n\t\tname: \"help\",\n\t\tflags: \"-h, --help\",\n\t\ttype: \"boolean\",\n\t\tdescription: \"Show help\"\n\t}];\n\tconsole.log(styleText(\"bold\", \"Options:\"));\n\tfor (const opt of options) {\n\t\tconst flags = styleText(\"cyan\", opt.flags.padEnd(30));\n\t\tconst defaultPart = opt.default !== void 0 ? styleText(\"dim\", ` (default: ${opt.default})`) : \"\";\n\t\tconsole.log(` ${flags}${opt.description}${defaultPart}`);\n\t}\n\tconsole.log();\n}\n//#endregion\n//#region src/cli/adapters/nodeAdapter.ts\nfunction buildParseOptions(def) {\n\tconst result = { help: {\n\t\ttype: \"boolean\",\n\t\tshort: \"h\"\n\t} };\n\tfor (const [name, opt] of Object.entries(def.options ?? {})) result[name] = {\n\t\ttype: opt.type,\n\t\t...opt.short ? { short: opt.short } : {},\n\t\t...opt.default !== void 0 ? { default: opt.default } : {}\n\t};\n\treturn result;\n}\nasync function runCommand(def, argv, parentName) {\n\tconst parseOptions = buildParseOptions(def);\n\tlet parsed;\n\ttry {\n\t\tconst result = parseArgs({\n\t\t\targs: argv,\n\t\t\toptions: parseOptions,\n\t\t\tallowPositionals: true,\n\t\t\tstrict: false\n\t\t});\n\t\tparsed = {\n\t\t\tvalues: result.values,\n\t\t\tpositionals: result.positionals\n\t\t};\n\t} catch {\n\t\trenderHelp(def, parentName);\n\t\tprocess.exit(1);\n\t}\n\tif (parsed.values[\"help\"]) {\n\t\trenderHelp(def, parentName);\n\t\tprocess.exit(0);\n\t}\n\tfor (const [name, opt] of Object.entries(def.options ?? {})) if (opt.required && parsed.values[name] === void 0) {\n\t\tconsole.error(styleText(\"red\", `Error: --${name} is required`));\n\t\trenderHelp(def, parentName);\n\t\tprocess.exit(1);\n\t}\n\tif (!def.run) {\n\t\trenderHelp(def, parentName);\n\t\tprocess.exit(0);\n\t}\n\ttry {\n\t\tawait def.run(parsed);\n\t} catch (err) {\n\t\tconsole.error(styleText(\"red\", `Error: ${err instanceof Error ? err.message : String(err)}`));\n\t\trenderHelp(def, parentName);\n\t\tprocess.exit(1);\n\t}\n}\nfunction printRootHelp(programName, version, defs) {\n\tconsole.log(`\\n${styleText(\"bold\", \"Usage:\")} ${programName} <command> [options]\\n`);\n\tconsole.log(` Kubb generation — v${version}\\n`);\n\tconsole.log(styleText(\"bold\", \"Commands:\"));\n\tfor (const def of defs) console.log(` ${styleText(\"cyan\", def.name.padEnd(16))}${def.description}`);\n\tconsole.log();\n\tconsole.log(styleText(\"bold\", \"Options:\"));\n\tconsole.log(` ${styleText(\"cyan\", \"-v, --version\".padEnd(30))}Show version number`);\n\tconsole.log(` ${styleText(\"cyan\", \"-h, --help\".padEnd(30))}Show help`);\n\tconsole.log();\n\tconsole.log(`Run ${styleText(\"cyan\", `${programName} <command> --help`)} for command-specific help.\\n`);\n}\n/** CLI adapter using `node:util parseArgs`. No external dependencies. */\nconst nodeAdapter = defineCLIAdapter({\n\trenderHelp(def, parentName) {\n\t\trenderHelp(def, parentName);\n\t},\n\tasync run(defs, argv, opts) {\n\t\tconst { programName, defaultCommandName, version } = opts;\n\t\tconst args = argv.length >= 2 && argv[0]?.includes(\"node\") ? argv.slice(2) : argv;\n\t\tif (args[0] === \"--version\" || args[0] === \"-v\") {\n\t\t\tconsole.log(version);\n\t\t\tprocess.exit(0);\n\t\t}\n\t\tif (args[0] === \"--help\" || args[0] === \"-h\") {\n\t\t\tprintRootHelp(programName, version, defs);\n\t\t\tprocess.exit(0);\n\t\t}\n\t\tif (args.length === 0) {\n\t\t\tconst defaultDef = defs.find((d) => d.name === defaultCommandName);\n\t\t\tif (defaultDef?.run) await runCommand(defaultDef, [], programName);\n\t\t\telse printRootHelp(programName, version, defs);\n\t\t\treturn;\n\t\t}\n\t\tconst [first, ...rest] = args;\n\t\tconst isKnownSubcommand = defs.some((d) => d.name === first);\n\t\tlet def;\n\t\tlet commandArgv;\n\t\tlet parentName;\n\t\tif (isKnownSubcommand) {\n\t\t\tdef = defs.find((d) => d.name === first);\n\t\t\tcommandArgv = rest;\n\t\t\tparentName = programName;\n\t\t} else {\n\t\t\tdef = defs.find((d) => d.name === defaultCommandName);\n\t\t\tcommandArgv = args;\n\t\t\tparentName = programName;\n\t\t}\n\t\tif (!def) {\n\t\t\tconsole.error(`Unknown command: ${first}`);\n\t\t\tprintRootHelp(programName, version, defs);\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (def.subCommands?.length) {\n\t\t\tconst [subName, ...subRest] = commandArgv;\n\t\t\tconst subDef = def.subCommands.find((s) => s.name === subName);\n\t\t\tif (subName === \"--help\" || subName === \"-h\") {\n\t\t\t\trenderHelp(def, parentName);\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\tif (!subDef) {\n\t\t\t\trenderHelp(def, parentName);\n\t\t\t\tprocess.exit(subName ? 1 : 0);\n\t\t\t}\n\t\t\tawait runCommand(subDef, subRest, `${parentName} ${def.name}`);\n\t\t\treturn;\n\t\t}\n\t\tawait runCommand(def, commandArgv, parentName);\n\t}\n});\n//#endregion\n//#region src/cli/parse.ts\n/**\n* Create a CLI runner bound to a specific adapter.\n* Defaults to the built-in `nodeAdapter` (Node.js `node:util parseArgs`).\n*/\nfunction createCLI(options) {\n\tconst adapter = options?.adapter ?? nodeAdapter;\n\treturn { run(commands, argv, opts) {\n\t\treturn adapter.run(commands, argv, opts);\n\t} };\n}\n//#endregion\n//#region src/time.ts\n/**\n* Calculates elapsed time in milliseconds from a high-resolution start time.\n* Rounds to 2 decimal places to provide sub-millisecond precision without noise.\n*/\nfunction getElapsedMs(hrStart) {\n\tconst [seconds, nanoseconds] = process.hrtime(hrStart);\n\tconst ms = seconds * 1e3 + nanoseconds / 1e6;\n\treturn Math.round(ms * 100) / 100;\n}\n/**\n* Converts a millisecond duration into a human-readable string.\n* Adjusts units (ms, s, m s) based on the magnitude of the duration.\n*/\nfunction formatMs(ms) {\n\tif (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;\n\tif (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;\n\treturn `${Math.round(ms)}ms`;\n}\n/**\n* Convenience helper: formats the elapsed time since `hrStart` in one step.\n*/\nfunction formatHrtime(hrStart) {\n\treturn formatMs(getElapsedMs(hrStart));\n}\n//#endregion\n//#region src/colors.ts\n/**\n* Parses a CSS hex color string (`#RGB`) into its RGB channels.\n* Falls back to `255` for any channel that cannot be parsed.\n*/\nfunction parseHex(color) {\n\tconst int = Number.parseInt(color.replace(\"#\", \"\"), 16);\n\treturn Number.isNaN(int) ? {\n\t\tr: 255,\n\t\tg: 255,\n\t\tb: 255\n\t} : {\n\t\tr: int >> 16 & 255,\n\t\tg: int >> 8 & 255,\n\t\tb: int & 255\n\t};\n}\n/**\n* Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence\n* for the given hex color.\n*/\nfunction hex(color) {\n\tconst { r, g, b } = parseHex(color);\n\treturn (text) => `\\x1b[38;2;${r};${g};${b}m${text}\\x1b[0m`;\n}\nfunction gradient(colorStops, text) {\n\tconst chars = text.split(\"\");\n\treturn chars.map((char, i) => {\n\t\tconst t = chars.length <= 1 ? 0 : i / (chars.length - 1);\n\t\tconst seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);\n\t\tconst lt = t * (colorStops.length - 1) - seg;\n\t\tconst from = parseHex(colorStops[seg]);\n\t\tconst to = parseHex(colorStops[seg + 1]);\n\t\treturn `\\x1b[38;2;${Math.round(from.r + (to.r - from.r) * lt)};${Math.round(from.g + (to.g - from.g) * lt)};${Math.round(from.b + (to.b - from.b) * lt)}m${char}\\x1b[0m`;\n\t}).join(\"\");\n}\n/** ANSI color functions for each part of the Kubb mascot illustration. */\nconst palette = {\n\tlid: hex(\"#F55A17\"),\n\twoodTop: hex(\"#F5A217\"),\n\twoodMid: hex(\"#F58517\"),\n\twoodBase: hex(\"#B45309\"),\n\teye: hex(\"#FFFFFF\"),\n\thighlight: hex(\"#adadc6\"),\n\tblush: hex(\"#FDA4AF\")\n};\n/**\n* Generates the Kubb mascot welcome banner.\n*/\nfunction getIntro({ title, description, version, areEyesOpen }) {\n\tconst kubbVersion = gradient([\n\t\t\"#F58517\",\n\t\t\"#F5A217\",\n\t\t\"#F55A17\"\n\t], `KUBB v${version}`);\n\tconst eyeTop = areEyesOpen ? palette.eye(\"█▀█\") : palette.eye(\"───\");\n\tconst eyeBottom = areEyesOpen ? palette.eye(\"▀▀▀\") : palette.eye(\"───\");\n\treturn `\n ${palette.lid(\"▄▄▄▄▄▄▄▄▄▄▄▄▄\")}\n ${palette.woodTop(\"█ \")}${palette.highlight(\"▄▄\")}${palette.woodTop(\" \")}${palette.highlight(\"▄▄\")}${palette.woodTop(\" █\")} ${kubbVersion}\n ${palette.woodMid(\"█ \")}${eyeTop}${palette.woodMid(\" \")}${eyeTop}${palette.woodMid(\" █\")} ${styleText(\"gray\", title)}\n ${palette.woodMid(\"█ \")}${eyeBottom}${palette.woodMid(\" \")}${palette.blush(\"◡\")}${palette.woodMid(\" \")}${eyeBottom}${palette.woodMid(\" █\")} ${styleText(\"yellow\", \"➜\")} ${styleText(\"white\", description)}\n ${palette.woodBase(\"▀▀▀▀▀▀▀▀▀▀▀▀▀\")}\n`;\n}\n/** ANSI color names available for terminal output. */\nconst randomColors = [\n\t\"black\",\n\t\"red\",\n\t\"green\",\n\t\"yellow\",\n\t\"blue\",\n\t\"white\",\n\t\"magenta\",\n\t\"cyan\",\n\t\"gray\"\n];\n/**\n* Returns the text wrapped in a deterministic ANSI color derived from the text's SHA-256 hash.\n*/\nfunction randomCliColor(text) {\n\tif (!text) return \"\";\n\treturn styleText(randomColors[createHash(\"sha256\").update(text).digest().readUInt32BE(0) % randomColors.length] ?? \"white\", text);\n}\n/**\n* Formats a millisecond duration with an ANSI color based on thresholds:\n* green ≤ 500 ms · yellow ≤ 1 000 ms · red > 1 000 ms\n*/\nfunction formatMsWithColor(ms) {\n\tconst formatted = formatMs(ms);\n\tif (ms <= 500) return styleText(\"green\", formatted);\n\tif (ms <= 1e3) return styleText(\"yellow\", formatted);\n\treturn styleText(\"red\", formatted);\n}\n//#endregion\n//#region src/env.ts\n/**\n* Returns `true` when running inside a GitHub Actions workflow.\n*/\nfunction isGitHubActions() {\n\treturn !!process.env.GITHUB_ACTIONS;\n}\n/**\n* Returns `true` when the process is running in a CI environment.\n* Covers GitHub Actions, GitLab CI, CircleCI, Travis CI, Jenkins, Bitbucket,\n* TeamCity, Buildkite, and Azure Pipelines.\n*/\nfunction isCIEnvironment() {\n\treturn !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.BITBUCKET_BUILD_NUMBER || process.env.JENKINS_URL || process.env.CIRCLECI || process.env.TRAVIS || process.env.TEAMCITY_VERSION || process.env.BUILDKITE || process.env.TF_BUILD);\n}\n/**\n* Returns `true` when the process has an interactive TTY and is not running in CI.\n*/\nfunction canUseTTY() {\n\treturn !!process.stdout.isTTY && !isCIEnvironment();\n}\n//#endregion\n//#region src/fs.ts\n/**\n* Converts all backslashes to forward slashes.\n* Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n*/\nfunction toSlash(p) {\n\tif (p.startsWith(\"\\\\\\\\?\\\\\")) return p;\n\treturn p.replaceAll(\"\\\\\", \"/\");\n}\n/**\n* Returns the relative path from `rootDir` to `filePath`, always using\n* forward slashes and prefixed with `./` when not already traversing upward.\n*/\nfunction getRelativePath(rootDir, filePath) {\n\tif (!rootDir || !filePath) throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || \"\"} ${filePath || \"\"}`);\n\tconst relativePath = posix.relative(toSlash(rootDir), toSlash(filePath));\n\treturn relativePath.startsWith(\"../\") ? relativePath : `./${relativePath}`;\n}\n/**\n* Resolves to `true` when the file or directory at `path` exists.\n* Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n*/\nasync function exists(path) {\n\tif (typeof Bun !== \"undefined\") return Bun.file(path).exists();\n\treturn access(path).then(() => true, () => false);\n}\n/**\n* Reads the file at `path` as a UTF-8 string.\n* Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n*/\nasync function read(path) {\n\tif (typeof Bun !== \"undefined\") return Bun.file(path).text();\n\treturn readFile(path, { encoding: \"utf8\" });\n}\n/** Synchronous counterpart of `read`. */\nfunction readSync(path) {\n\treturn readFileSync(path, { encoding: \"utf8\" });\n}\n/**\n* Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n* Skips the write and returns `undefined` when the trimmed content is empty or\n* identical to what is already on disk.\n* Creates any missing parent directories automatically.\n* When `sanity` is `true`, re-reads the file after writing and throws if the\n* content does not match.\n*/\nasync function write(path, data, options = {}) {\n\tconst trimmed = data.trim();\n\tif (trimmed === \"\") return void 0;\n\tconst resolved = resolve(path);\n\tif (typeof Bun !== \"undefined\") {\n\t\tconst file = Bun.file(resolved);\n\t\tif ((await file.exists() ? await file.text() : null) === trimmed) return void 0;\n\t\tawait Bun.write(resolved, trimmed);\n\t\treturn trimmed;\n\t}\n\ttry {\n\t\tif (await readFile(resolved, { encoding: \"utf-8\" }) === trimmed) return void 0;\n\t} catch {}\n\tawait mkdir(dirname(resolved), { recursive: true });\n\tawait writeFile(resolved, trimmed, { encoding: \"utf-8\" });\n\tif (options.sanity) {\n\t\tconst savedData = await readFile(resolved, { encoding: \"utf-8\" });\n\t\tif (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`);\n\t\treturn savedData;\n\t}\n\treturn trimmed;\n}\n/** Recursively removes `path`. Silently succeeds when `path` does not exist. */\nasync function clean(path) {\n\treturn rm(path, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n}\n//#endregion\n//#region src/jsdoc.ts\n/**\n* Builds a JSDoc comment block from an array of lines.\n* Returns `fallback` when `comments` is empty so callers always get a usable string.\n*/\nfunction buildJSDoc(comments, options = {}) {\n\tconst { indent = \" * \", suffix = \"\\n \", fallback = \" \" } = options;\n\tif (comments.length === 0) return fallback;\n\treturn `/**\\n${comments.map((c) => `${indent}${c}`).join(\"\\n\")}\\n */${suffix}`;\n}\n//#endregion\n//#region src/names.ts\n/**\n* Returns a unique name by appending an incrementing numeric suffix when the name has already been used.\n* Mutates `data` in-place as a usage counter so subsequent calls remain consistent.\n*\n* @example\n* const seen: Record<string, number> = {}\n* getUniqueName('Foo', seen) // 'Foo'\n* getUniqueName('Foo', seen) // 'Foo2'\n* getUniqueName('Foo', seen) // 'Foo3'\n*/\nfunction getUniqueName(originalName, data) {\n\tlet used = data[originalName] || 0;\n\tif (used) {\n\t\tdata[originalName] = ++used;\n\t\toriginalName += used;\n\t}\n\tdata[originalName] = 1;\n\treturn originalName;\n}\n/**\n* Registers `originalName` in `data` without altering the returned name.\n* Use this when you need to track usage frequency but always emit the original identifier.\n*/\nfunction setUniqueName(originalName, data) {\n\tlet used = data[originalName] || 0;\n\tif (used) {\n\t\tdata[originalName] = ++used;\n\t\treturn originalName;\n\t}\n\tdata[originalName] = 1;\n\treturn originalName;\n}\n//#endregion\n//#region src/network.ts\n/** Well-known stable domains used as DNS probes to check internet connectivity. */\nconst TEST_DOMAINS = [\n\t\"dns.google.com\",\n\t\"cloudflare.com\",\n\t\"one.one.one.one\"\n];\n/**\n* Returns `true` when the system has internet connectivity.\n* Uses DNS resolution against well-known stable domains as a lightweight probe.\n*/\nasync function isOnline() {\n\tfor (const domain of TEST_DOMAINS) try {\n\t\tawait promises.resolve(domain);\n\t\treturn true;\n\t} catch {}\n\treturn false;\n}\n/**\n* Executes `fn` only when the system is online. Returns `null` when offline or on error.\n*/\nasync function executeIfOnline(fn) {\n\tif (!await isOnline()) return null;\n\ttry {\n\t\treturn await fn();\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/string.ts\n/**\n* Strips a single matching pair of `\"...\"`, `'...'`, or `` `...` `` from both ends of `text`.\n* Returns the string unchanged when no balanced quote pair is found.\n*\n* @example\n* trimQuotes('\"hello\"') // 'hello'\n* trimQuotes('hello') // 'hello'\n*/\nfunction trimQuotes(text) {\n\tif (text.length >= 2) {\n\t\tconst first = text[0];\n\t\tconst last = text[text.length - 1];\n\t\tif (first === \"\\\"\" && last === \"\\\"\" || first === \"'\" && last === \"'\" || first === \"`\" && last === \"`\") return text.slice(1, -1);\n\t}\n\treturn text;\n}\n/**\n* Escapes characters that are not allowed inside JS string literals.\n* Handles quotes, backslashes, and Unicode line terminators (U+2028 / U+2029).\n*\n* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\n*/\nfunction jsStringEscape(input) {\n\treturn `${input}`.replace(/[\"'\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n\t\tswitch (character) {\n\t\t\tcase \"\\\"\":\n\t\t\tcase \"'\":\n\t\t\tcase \"\\\\\": return `\\\\${character}`;\n\t\t\tcase \"\\n\": return \"\\\\n\";\n\t\t\tcase \"\\r\": return \"\\\\r\";\n\t\t\tcase \"\\u2028\": return \"\\\\u2028\";\n\t\t\tcase \"\\u2029\": return \"\\\\u2029\";\n\t\t\tdefault: return \"\";\n\t\t}\n\t});\n}\n/**\n* Returns a masked version of a string, showing only the first and last few characters.\n* Useful for logging sensitive values (tokens, keys) without exposing the full value.\n*\n* @example\n* maskString('KUBB_STUDIO-abc123-xyz789') // 'KUBB_STUDIO-…789'\n*/\nfunction maskString(value, start = 8, end = 4) {\n\tif (value.length <= start + end) return value;\n\treturn `${value.slice(0, start)}…${value.slice(-end)}`;\n}\n//#endregion\n//#region src/object.ts\n/**\n* Serializes a primitive value to a JSON string literal, stripping any surrounding quote characters first.\n*\n* @example\n* stringify('hello') // '\"hello\"'\n* stringify('\"hello\"') // '\"hello\"'\n*/\nfunction stringify(value) {\n\tif (value === void 0 || value === null) return \"\\\"\\\"\";\n\treturn JSON.stringify(trimQuotes(value.toString()));\n}\n/**\n* Converts a plain object into a multiline key-value string suitable for embedding in generated code.\n* Nested objects are recursively stringified with indentation.\n*\n* @example\n* stringifyObject({ foo: 'bar', nested: { a: 1 } })\n* // 'foo: bar,\\nnested: {\\n a: 1\\n }'\n*/\nfunction stringifyObject(value) {\n\treturn Object.entries(value).map(([key, val]) => {\n\t\tif (val !== null && typeof val === \"object\") return `${key}: {\\n ${stringifyObject(val)}\\n }`;\n\t\treturn `${key}: ${val}`;\n\t}).filter(Boolean).join(\",\\n\");\n}\n/**\n* Serializes plugin options for safe JSON transport.\n* Strips functions, symbols, and `undefined` values recursively.\n*/\nfunction serializePluginOptions(options) {\n\tif (options === null || options === void 0) return {};\n\tif (typeof options !== \"object\") return options;\n\tif (Array.isArray(options)) return options.map(serializePluginOptions);\n\tconst serialized = {};\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tif (typeof value === \"function\" || typeof value === \"symbol\" || value === void 0) continue;\n\t\tserialized[key] = value !== null && typeof value === \"object\" ? serializePluginOptions(value) : value;\n\t}\n\treturn serialized;\n}\n/**\n* Converts a dot-notation path or string array into an optional-chaining accessor expression.\n*\n* @example\n* getNestedAccessor('pagination.next.id', 'lastPage')\n* // → \"lastPage?.['pagination']?.['next']?.['id']\"\n*/\nfunction getNestedAccessor(param, accessor) {\n\tconst parts = Array.isArray(param) ? param : param.split(\".\");\n\tif (parts.length === 0 || parts.length === 1 && parts[0] === \"\") return void 0;\n\treturn `${accessor}?.['${`${parts.join(\"']?.['\")}']`}`;\n}\n//#endregion\n//#region src/packageManager.ts\nconst packageManagers = {\n\tpnpm: {\n\t\tname: \"pnpm\",\n\t\tlockFile: \"pnpm-lock.yaml\",\n\t\tinstallCommand: [\"add\", \"-D\"]\n\t},\n\tyarn: {\n\t\tname: \"yarn\",\n\t\tlockFile: \"yarn.lock\",\n\t\tinstallCommand: [\"add\", \"-D\"]\n\t},\n\tbun: {\n\t\tname: \"bun\",\n\t\tlockFile: \"bun.lockb\",\n\t\tinstallCommand: [\"add\", \"-d\"]\n\t},\n\tnpm: {\n\t\tname: \"npm\",\n\t\tlockFile: \"package-lock.json\",\n\t\tinstallCommand: [\"install\", \"--save-dev\"]\n\t}\n};\n/**\n* Detects the active package manager for the given directory.\n* Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n* Falls back to npm when no signal is found.\n*/\nfunction detectPackageManager(cwd = process.cwd()) {\n\tconst packageJsonPath = join(cwd, \"package.json\");\n\tif (existsSync(packageJsonPath)) try {\n\t\tconst pmField = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")).packageManager;\n\t\tif (typeof pmField === \"string\") {\n\t\t\tconst name = pmField.split(\"@\")[0];\n\t\t\tif (name && name in packageManagers) return packageManagers[name];\n\t\t}\n\t} catch {}\n\tfor (const pm of Object.values(packageManagers)) if (existsSync(join(cwd, pm.lockFile))) return pm;\n\treturn packageManagers.npm;\n}\n//#endregion\n//#region src/promise.ts\n/** Returns `true` when `result` is a thenable `Promise`. */\nfunction isPromise(result) {\n\treturn result !== null && result !== void 0 && typeof result[\"then\"] === \"function\";\n}\n/** Type guard for a rejected `Promise.allSettled` result with a typed `reason`. */\nfunction isPromiseRejectedResult(result) {\n\treturn result.status === \"rejected\";\n}\n//#endregion\n//#region src/regexp.ts\n/**\n* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.\n* Inline flags expressed as `^(?im)` prefixes are extracted and applied to the resulting expression.\n* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.\n*\n* @example\n* toRegExpString('^(?im)foo') // → 'new RegExp(\"foo\", \"im\")'\n* toRegExpString('^(?im)foo', null) // → '/foo/im'\n*/\nfunction toRegExpString(text, func = \"RegExp\") {\n\tconst raw = trimQuotes(text);\n\tconst match = raw.match(/^\\^(\\(\\?([igmsuy]+)\\))/i);\n\tconst replacementTarget = match?.[1] ?? \"\";\n\tconst matchedFlags = match?.[2];\n\tconst cleaned = raw.replace(/^\\\\?\\//, \"\").replace(/\\\\?\\/$/, \"\").replace(replacementTarget, \"\");\n\tconst { source, flags } = new RegExp(cleaned, matchedFlags);\n\tif (func === null) return `/${source}/${flags}`;\n\treturn `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : \"\"})`;\n}\n//#endregion\n//#region src/reserved.ts\n/**\n* JavaScript and Java reserved words.\n* @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n*/\nconst reservedWords = [\n\t\"abstract\",\n\t\"arguments\",\n\t\"boolean\",\n\t\"break\",\n\t\"byte\",\n\t\"case\",\n\t\"catch\",\n\t\"char\",\n\t\"class\",\n\t\"const\",\n\t\"continue\",\n\t\"debugger\",\n\t\"default\",\n\t\"delete\",\n\t\"do\",\n\t\"double\",\n\t\"else\",\n\t\"enum\",\n\t\"eval\",\n\t\"export\",\n\t\"extends\",\n\t\"false\",\n\t\"final\",\n\t\"finally\",\n\t\"float\",\n\t\"for\",\n\t\"function\",\n\t\"goto\",\n\t\"if\",\n\t\"implements\",\n\t\"import\",\n\t\"in\",\n\t\"instanceof\",\n\t\"int\",\n\t\"interface\",\n\t\"let\",\n\t\"long\",\n\t\"native\",\n\t\"new\",\n\t\"null\",\n\t\"package\",\n\t\"private\",\n\t\"protected\",\n\t\"public\",\n\t\"return\",\n\t\"short\",\n\t\"static\",\n\t\"super\",\n\t\"switch\",\n\t\"synchronized\",\n\t\"this\",\n\t\"throw\",\n\t\"throws\",\n\t\"transient\",\n\t\"true\",\n\t\"try\",\n\t\"typeof\",\n\t\"var\",\n\t\"void\",\n\t\"volatile\",\n\t\"while\",\n\t\"with\",\n\t\"yield\",\n\t\"Array\",\n\t\"Date\",\n\t\"hasOwnProperty\",\n\t\"Infinity\",\n\t\"isFinite\",\n\t\"isNaN\",\n\t\"isPrototypeOf\",\n\t\"length\",\n\t\"Math\",\n\t\"name\",\n\t\"NaN\",\n\t\"Number\",\n\t\"Object\",\n\t\"prototype\",\n\t\"String\",\n\t\"toString\",\n\t\"undefined\",\n\t\"valueOf\"\n];\n/**\n* Prefixes a word with `_` when it is a reserved JavaScript/Java identifier\n* or starts with a digit.\n*/\nfunction transformReservedWord(word) {\n\tconst firstChar = word.charCodeAt(0);\n\tif (word && (reservedWords.includes(word) || firstChar >= 48 && firstChar <= 57)) return `_${word}`;\n\treturn word;\n}\n/**\n* Returns `true` when `name` is a syntactically valid JavaScript variable name.\n*/\nfunction isValidVarName(name) {\n\ttry {\n\t\tnew Function(`var ${name}`);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn true;\n}\n//#endregion\n//#region src/shell.ts\n/**\n* Tokenizes a shell command string, respecting single and double quotes.\n*\n* @example\n* tokenize('git commit -m \"initial commit\"')\n* // → ['git', 'commit', '-m', 'initial commit']\n*/\nfunction tokenize(command) {\n\treturn (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, \"\"));\n}\n/**\n* Spawns `cmd` with `args` and returns a promise that settles when the child process finishes.\n*\n* Foreground mode (default) inherits the parent's stdio and rejects on non-zero exit or signal.\n* Detached mode spawns the child in its own process group, unref's it, and resolves immediately —\n* the parent can exit without waiting for the child.\n*/\nfunction spawnAsync(cmd, args, options = {}) {\n\tconst { cwd = process.cwd(), env, detached = false } = options;\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(cmd, args, {\n\t\t\tstdio: detached ? \"ignore\" : \"inherit\",\n\t\t\tcwd,\n\t\t\tenv,\n\t\t\tdetached\n\t\t});\n\t\tif (detached) {\n\t\t\tchild.unref();\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tchild.on(\"close\", (code, signal) => {\n\t\t\tif (code === 0) resolve();\n\t\t\telse if (signal !== null) reject(/* @__PURE__ */ new Error(`\"${cmd} ${args.join(\" \")}\" was terminated by signal ${signal}`));\n\t\t\telse reject(/* @__PURE__ */ new Error(`\"${cmd} ${args.join(\" \")}\" exited with code ${code}`));\n\t\t});\n\t\tchild.on(\"error\", reject);\n\t});\n}\n//#endregion\n//#region src/token.ts\n/** Generates a cryptographically random 32-byte token encoded as a hex string. */\nfunction generateToken() {\n\treturn randomBytes(32).toString(\"hex\");\n}\n/** Returns the SHA-256 hex digest of `input`. Useful for deterministically hashing a token before storage. */\nfunction hashToken(input) {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\n//#endregion\n//#region src/urlPath.ts\n/**\n* Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n*\n* @example\n* const p = new URLPath('/pet/{petId}')\n* p.URL // '/pet/:petId'\n* p.template // '`/pet/${petId}`'\n*/\nvar URLPath = class {\n\t/** The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`. */\n\tpath;\n\t#options;\n\tconstructor(path, options = {}) {\n\t\tthis.path = path;\n\t\tthis.#options = options;\n\t}\n\t/** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n\tget URL() {\n\t\treturn this.toURLPath();\n\t}\n\t/** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`). */\n\tget isURL() {\n\t\ttry {\n\t\t\treturn !!new URL(this.path).href;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\t/**\n\t* Converts the OpenAPI path to a TypeScript template literal string.\n\t*\n\t* @example\n\t* new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n\t* new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n\t*/\n\tget template() {\n\t\treturn this.toTemplateString();\n\t}\n\t/** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set. */\n\tget object() {\n\t\treturn this.toObject();\n\t}\n\t/** Returns a map of path parameter names, or `undefined` when the path has no parameters. */\n\tget params() {\n\t\treturn this.getParams();\n\t}\n\t#transformParam(raw) {\n\t\tconst param = isValidVarName(raw) ? raw : camelCase(raw);\n\t\treturn this.#options.casing === \"camelcase\" ? camelCase(param) : param;\n\t}\n\t/** Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name. */\n\t#eachParam(fn) {\n\t\tfor (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n\t\t\tconst raw = match[1];\n\t\t\tfn(raw, this.#transformParam(raw));\n\t\t}\n\t}\n\ttoObject({ type = \"path\", replacer, stringify } = {}) {\n\t\tconst object = {\n\t\t\turl: type === \"path\" ? this.toURLPath() : this.toTemplateString({ replacer }),\n\t\t\tparams: this.getParams()\n\t\t};\n\t\tif (stringify) {\n\t\t\tif (type === \"template\") return JSON.stringify(object).replaceAll(\"'\", \"\").replaceAll(`\"`, \"\");\n\t\t\tif (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", \"\").replaceAll(`\"`, \"\")} }`;\n\t\t\treturn `{ url: '${object.url}' }`;\n\t\t}\n\t\treturn object;\n\t}\n\t/**\n\t* Converts the OpenAPI path to a TypeScript template literal string.\n\t* An optional `replacer` can transform each extracted parameter name before interpolation.\n\t*\n\t* @example\n\t* new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n\t*/\n\ttoTemplateString({ prefix = \"\", replacer } = {}) {\n\t\treturn `\\`${prefix}${this.path.split(/\\{([^}]+)\\}/).map((part, i) => {\n\t\t\tif (i % 2 === 0) return part;\n\t\t\tconst param = this.#transformParam(part);\n\t\t\treturn `\\${${replacer ? replacer(param) : param}}`;\n\t\t}).join(\"\")}\\``;\n\t}\n\t/**\n\t* Extracts all `{param}` segments from the path and returns them as a key-value map.\n\t* An optional `replacer` transforms each parameter name in both key and value positions.\n\t* Returns `undefined` when no path parameters are found.\n\t*/\n\tgetParams(replacer) {\n\t\tconst params = {};\n\t\tthis.#eachParam((_raw, param) => {\n\t\t\tconst key = replacer ? replacer(param) : param;\n\t\t\tparams[key] = key;\n\t\t});\n\t\treturn Object.keys(params).length > 0 ? params : void 0;\n\t}\n\t/** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`. */\n\ttoURLPath() {\n\t\treturn this.path.replace(/\\{([^}]+)\\}/g, \":$1\");\n\t}\n};\n//#endregion\nexport { AsyncEventEmitter, BuildError, URLPath, ValidationPluginError, buildJSDoc, camelCase, canUseTTY, clean, createCLI, defineCommand, detectPackageManager, executeIfOnline, exists, formatHrtime, formatMs, formatMsWithColor, generateToken, getElapsedMs, getErrorMessage, getIntro, getNestedAccessor, getRelativePath, getUniqueName, hashToken, isCIEnvironment, isGitHubActions, isPromise, isPromiseRejectedResult, isValidVarName, jsStringEscape, maskString, packageManagers, pascalCase, randomCliColor, read, readSync, screamingSnakeCase, serializePluginOptions, setUniqueName, snakeCase, spawnAsync, stringify, stringifyObject, toCause, toError, toRegExpString, tokenize, transformReservedWord, trimQuotes, write };\n\n//# sourceMappingURL=index.js.map","import type { PossiblePromise } from '@internals/utils'\nimport type { InputPath, UserConfig } from './types.ts'\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n /** Path to `kubb.config.js` */\n config?: string\n\n /** Enable watch mode for input files */\n watch?: boolean\n\n /**\n * Logging verbosity for CLI usage.\n *\n * - `silent`: hide non-essential logs\n * - `info`: show general logs (non-plugin-related)\n * - `debug`: include detailed plugin lifecycle logs\n * @default 'silent'\n */\n logLevel?: 'silent' | 'info' | 'debug'\n\n /** Run Kubb with Bun */\n bun?: boolean\n}\n\n/** All accepted forms of a Kubb configuration. */\nexport type ConfigInput = PossiblePromise<UserConfig | UserConfig[]> | ((cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>)\n\n/**\n * Helper for defining a Kubb configuration.\n *\n * Accepts either:\n * - A config object or array of configs\n * - A function returning the config(s), optionally async,\n * receiving the CLI options as argument\n *\n * @example\n * export default defineConfig(({ logLevel }) => ({\n * root: 'src',\n * plugins: [myPlugin()],\n * }))\n */\nexport function defineConfig(config: (cli: CLIOptions) => PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: PossiblePromise<UserConfig | UserConfig[]>): typeof config\nexport function defineConfig(config: ConfigInput): ConfigInput {\n return config\n}\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: UserConfig | undefined): config is UserConfig<InputPath> {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n","import type { KubbFile } from '@kubb/fabric-core/types'\n\nexport const DEFAULT_STUDIO_URL = 'https://studio.kubb.dev' as const\n\nexport const CORE_PLUGIN_NAME = 'core' as const\n\nexport const DEFAULT_MAX_LISTENERS = 100\n\nexport const DEFAULT_CONCURRENCY = 15\n\nexport const BARREL_FILENAME = 'index.ts' as const\n\nexport const DEFAULT_BANNER = 'simple' as const\n\nexport const DEFAULT_EXTENSION: Record<KubbFile.Extname, KubbFile.Extname | ''> = { '.ts': '.ts' }\n\nexport const PATH_SEPARATORS = ['/', '\\\\'] as const\n\nexport const logLevel = {\n silent: Number.NEGATIVE_INFINITY,\n error: 0,\n warn: 1,\n info: 3,\n verbose: 4,\n debug: 5,\n} as const\n\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n args: (outputPath: string) => ['--fix', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const\n\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const\n","import type { RootNode } from '@kubb/ast/types'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { x } from 'tinyexec'\nimport type { DevtoolsOptions } from './types.ts'\n\n/**\n * Encodes a `RootNode` as a compressed, URL-safe string.\n *\n * The JSON representation is deflate-compressed with {@link deflateSync} before\n * base64url encoding, which typically reduces payload size by 70–80 % and\n * keeps URLs well within browser and server path-length limits.\n *\n * Use {@link decodeAst} to reverse.\n */\nexport function encodeAst(root: RootNode): string {\n const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(root)))\n return Buffer.from(compressed).toString('base64url')\n}\n\n/**\n * Decodes a `RootNode` from a string produced by {@link encodeAst}.\n *\n * Works in both Node.js and the browser — no streaming APIs required.\n */\nexport function decodeAst(encoded: string): RootNode {\n const bytes = Buffer.from(encoded, 'base64url')\n return JSON.parse(new TextDecoder().decode(inflateSync(bytes))) as RootNode\n}\n\n/**\n * Constructs the Kubb Studio URL for the given `RootNode`.\n * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).\n * The `root` is encoded and attached as the `?root=` query parameter so Studio\n * can decode and render it without a round-trip to any server.\n */\nexport function getStudioUrl(root: RootNode, studioUrl: string, options: DevtoolsOptions = {}): string {\n const baseUrl = studioUrl.replace(/\\/$/, '')\n const path = options.ast ? '/ast' : ''\n\n return `${baseUrl}${path}?root=${encodeAst(root)}`\n}\n\n/**\n * Opens the Kubb Studio URL for the given `RootNode` in the default browser —\n *\n * Falls back to printing the URL if the browser cannot be launched.\n */\nexport async function openInStudio(root: RootNode, studioUrl: string, options: DevtoolsOptions = {}): Promise<void> {\n const url = getStudioUrl(root, studioUrl, options)\n\n const cmd = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'\n const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]\n\n try {\n await x(cmd, args)\n } catch {\n console.log(`\\n ${url}\\n`)\n }\n}\n","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tlet rejectOnClear = false;\n\n\tif (typeof concurrency === 'object') {\n\t\t({concurrency, rejectOnClear = false} = concurrency);\n\t}\n\n\tvalidateConcurrency(concurrency);\n\n\tif (typeof rejectOnClear !== 'boolean') {\n\t\tthrow new TypeError('Expected `rejectOnClear` to be a boolean');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\t// Process the next queued function if we're under the concurrency limit\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tactiveCount++;\n\t\t\tqueue.dequeue().run();\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\t// Execute the function and capture the result promise\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\t// Resolve immediately with the promise (don't wait for completion)\n\t\tresolve(result);\n\n\t\t// Wait for the function to complete (success or failure)\n\t\t// We catch errors here to prevent unhandled rejections,\n\t\t// but the original promise rejection is preserved for the caller\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\t// Decrement active count and process next queued function\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, reject, arguments_) => {\n\t\tconst queueItem = {reject};\n\n\t\t// Queue the internal resolve function instead of the run function\n\t\t// to preserve the asynchronous execution context.\n\t\tnew Promise(internalResolve => { // eslint-disable-line promise/param-names\n\t\t\tqueueItem.run = internalResolve;\n\t\t\tqueue.enqueue(queueItem);\n\t\t}).then(run.bind(undefined, function_, resolve, arguments_)); // eslint-disable-line promise/prefer-await-to-then\n\n\t\t// Start processing immediately if we haven't reached the concurrency limit\n\t\tif (activeCount < concurrency) {\n\t\t\tresumeNext();\n\t\t}\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise((resolve, reject) => {\n\t\tenqueue(function_, resolve, reject, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tif (!rejectOnClear) {\n\t\t\t\t\tqueue.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst abortError = AbortSignal.abort().reason;\n\n\t\t\t\twhile (queue.size > 0) {\n\t\t\t\t\tqueue.dequeue().reject(abortError);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmap: {\n\t\t\tasync value(iterable, function_) {\n\t\t\t\tconst promises = Array.from(iterable, (value, index) => this(function_, value, index));\n\t\t\t\treturn Promise.all(promises);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, options) {\n\tconst limit = pLimit(options);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","import pLimit from 'p-limit'\n\ntype PromiseFunc<T = unknown, T2 = never> = (state?: T) => T2 extends never ? Promise<T> : Promise<T> | T2\n\ntype ValueOfPromiseFuncArray<TInput extends Array<unknown>> = TInput extends Array<PromiseFunc<infer X, infer Y>> ? X | Y : never\n\ntype SeqOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<Array<Awaited<ValueOfPromiseFuncArray<TInput>>>>\n\n/**\n * Chains promises\n */\nexport function hookSeq<TInput extends Array<PromiseFunc<TValue, null>>, TValue, TOutput = SeqOutput<TInput, TValue>>(promises: TInput): TOutput {\n return promises.filter(Boolean).reduce(\n (promise, func) => {\n if (typeof func !== 'function') {\n throw new Error('HookSeq needs a function that returns a promise `() => Promise<unknown>`')\n }\n\n return promise.then((state) => {\n const calledFunc = func(state as TValue)\n\n if (calledFunc) {\n return calledFunc.then(Array.prototype.concat.bind(state) as (result: TValue) => TValue[])\n }\n\n return state\n })\n },\n Promise.resolve([] as Array<TValue>),\n ) as TOutput\n}\n\ntype HookFirstOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown> = ValueOfPromiseFuncArray<TInput>\n\n/**\n * Chains promises, first non-null result stops and returns\n */\nexport function hookFirst<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookFirstOutput<TInput, TValue>>(\n promises: TInput,\n nullCheck: (state: unknown) => boolean = (state) => state !== null,\n): TOutput {\n let promise: Promise<unknown> = Promise.resolve(null) as Promise<unknown>\n\n for (const func of promises.filter(Boolean)) {\n promise = promise.then((state) => {\n if (nullCheck(state)) {\n return state\n }\n\n return func(state as TValue)\n })\n }\n\n return promise as TOutput\n}\n\ntype HookParallelOutput<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = Promise<PromiseSettledResult<Awaited<ValueOfPromiseFuncArray<TInput>>>[]>\n\n/**\n * Runs an array of promise functions with optional concurrency limit.\n */\nexport function hookParallel<TInput extends Array<PromiseFunc<TValue, null>>, TValue = unknown, TOutput = HookParallelOutput<TInput, TValue>>(\n promises: TInput,\n concurrency: number = Number.POSITIVE_INFINITY,\n): TOutput {\n const limit = pLimit(concurrency)\n\n const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()))\n\n return Promise.allSettled(tasks) as TOutput\n}\n\nexport type Strategy = 'seq' | 'first' | 'parallel'\n\nexport type StrategySwitch<TStrategy extends Strategy, TInput extends Array<PromiseFunc<TValue, null>>, TValue> = TStrategy extends 'first'\n ? HookFirstOutput<TInput, TValue>\n : TStrategy extends 'seq'\n ? SeqOutput<TInput, TValue>\n : TStrategy extends 'parallel'\n ? HookParallelOutput<TInput, TValue>\n : never\n","import { basename, extname, resolve } from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { isPromiseRejectedResult, setUniqueName, transformReservedWord } from '@internals/utils'\nimport type { RootNode } from '@kubb/ast/types'\nimport type { Fabric as FabricType, KubbFile } from '@kubb/fabric-core/types'\nimport { CORE_PLUGIN_NAME, DEFAULT_STUDIO_URL } from './constants.ts'\nimport { openInStudio as openInStudioFn } from './devtools.ts'\nimport { ValidationPluginError } from './errors.ts'\nimport type {\n Adapter,\n Config,\n DevtoolsOptions,\n KubbEvents,\n Plugin,\n PluginContext,\n PluginFactoryOptions,\n PluginLifecycle,\n PluginLifecycleHooks,\n PluginParameter,\n PluginWithLifeCycle,\n ResolveNameParams,\n ResolvePathParams,\n UserPlugin,\n} from './types.ts'\nimport { hookFirst, hookParallel, hookSeq } from './utils/executeStrategies.ts'\n\ntype RequiredPluginLifecycle = Required<PluginLifecycle>\n\nexport type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq'\n\ntype ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H]\n\ntype SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {\n result: Result\n plugin: Plugin\n}\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\ntype Options = {\n fabric: FabricType\n events: AsyncEventEmitter<KubbEvents>\n /**\n * @default Number.POSITIVE_INFINITY\n */\n concurrency?: number\n}\n\nexport type GetFileOptions<TOptions = object> = {\n name: string\n mode?: KubbFile.Mode\n extname: KubbFile.Extname\n pluginName: string\n options?: TOptions\n}\n\nexport function getMode(fileOrFolder: string | undefined | null): KubbFile.Mode {\n if (!fileOrFolder) {\n return 'split'\n }\n return extname(fileOrFolder) ? 'single' : 'split'\n}\n\nconst hookFirstNullCheck = (state: unknown) => !!(state as SafeParseResult<'resolveName'> | null)?.result\n\nexport class PluginDriver {\n readonly config: Config\n readonly options: Options\n\n /**\n * The universal `@kubb/ast` `RootNode` produced by the adapter, set by\n * the build pipeline after the adapter's `parse()` resolves.\n */\n rootNode: RootNode | undefined = undefined\n adapter: Adapter | undefined = undefined\n #studioIsOpen = false\n\n readonly #plugins = new Set<Plugin>()\n readonly #usedPluginNames: Record<string, number> = {}\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n ;[...(config.plugins || [])].forEach((plugin) => {\n const parsedPlugin = this.#parse(plugin as UserPlugin)\n\n this.#plugins.add(parsedPlugin)\n })\n }\n\n get events() {\n return this.options.events\n }\n\n getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown> {\n const plugins = [...this.#plugins]\n const driver = this\n\n const baseContext = {\n fabric: this.options.fabric,\n config: this.config,\n plugin,\n events: this.options.events,\n driver: this,\n mode: getMode(resolve(this.config.root, this.config.output.path)),\n addFile: async (...files: Array<KubbFile.File>) => {\n await this.options.fabric.addFile(...files)\n },\n upsertFile: async (...files: Array<KubbFile.File>) => {\n await this.options.fabric.upsertFile(...files)\n },\n get rootNode(): RootNode | undefined {\n return driver.rootNode\n },\n get adapter(): Adapter | undefined {\n return driver.adapter\n },\n openInStudio(options?: DevtoolsOptions) {\n if (!driver.config.devtools || driver.#studioIsOpen) {\n return\n }\n\n if (typeof driver.config.devtools !== 'object') {\n throw new Error('Devtools must be an object')\n }\n\n if (!driver.rootNode || !driver.adapter) {\n throw new Error('adapter is not defined, make sure you have set the parser in kubb.config.ts')\n }\n\n driver.#studioIsOpen = true\n\n const studioUrl = driver.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL\n\n return openInStudioFn(driver.rootNode, studioUrl, options)\n },\n } as unknown as PluginContext<TOptions>\n\n const mergedExtras: Record<string, unknown> = {}\n for (const p of plugins) {\n if (typeof p.inject === 'function') {\n const result = (p.inject as (this: PluginContext, context: PluginContext) => unknown).call(\n baseContext as unknown as PluginContext,\n baseContext as unknown as PluginContext,\n )\n if (result !== null && typeof result === 'object') {\n Object.assign(mergedExtras, result)\n }\n }\n }\n\n return {\n ...baseContext,\n ...mergedExtras,\n }\n }\n\n get plugins(): Array<Plugin> {\n return this.#getSortedPlugins()\n }\n\n getFile<TOptions = object>({ name, mode, extname, pluginName, options }: GetFileOptions<TOptions>): KubbFile.File<{ pluginName: string }> {\n const resolvedName = mode ? (mode === 'single' ? '' : this.resolveName({ name, pluginName, type: 'file' })) : name\n\n const path = this.resolvePath({\n baseName: `${resolvedName}${extname}` as const,\n mode,\n pluginName,\n options,\n })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${resolvedName}\" and pluginName \"${pluginName}\"`)\n }\n\n return {\n path,\n baseName: basename(path) as KubbFile.File['baseName'],\n meta: {\n pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n }\n }\n\n resolvePath = <TOptions = object>(params: ResolvePathParams<TOptions>): KubbFile.Path => {\n const root = resolve(this.config.root, this.config.output.path)\n const defaultPath = resolve(root, params.baseName)\n\n if (params.pluginName) {\n const paths = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return paths?.at(0) || defaultPath\n }\n\n const firstResult = this.hookFirstSync({\n hookName: 'resolvePath',\n parameters: [params.baseName, params.mode, params.options as object],\n })\n\n return firstResult?.result || defaultPath\n }\n //TODO refactor by using the order of plugins and the cache of the fileManager instead of guessing and recreating the name/path\n resolveName = (params: ResolveNameParams): string => {\n if (params.pluginName) {\n const names = this.hookForPluginSync({\n pluginName: params.pluginName,\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })\n\n const uniqueNames = new Set(names)\n\n return transformReservedWord([...uniqueNames].at(0) || params.name)\n }\n\n const name = this.hookFirstSync({\n hookName: 'resolveName',\n parameters: [params.name.trim(), params.type],\n })?.result\n\n return transformReservedWord(name ?? params.name)\n }\n\n /**\n * Run a specific hookName for plugin x.\n */\n async hookForPlugin<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Promise<Array<ReturnType<ParseResult<H>> | null>> {\n const plugins = this.getPluginsByName(hookName, pluginName)\n\n this.events.emit('plugins:hook:progress:start', {\n hookName,\n plugins,\n })\n\n const items: Array<ReturnType<ParseResult<H>>> = []\n\n for (const plugin of plugins) {\n const result = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n if (result !== undefined && result !== null) {\n items.push(result)\n }\n }\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return items\n }\n /**\n * Run a specific hookName for plugin x.\n */\n\n hookForPluginSync<H extends PluginLifecycleHooks>({\n pluginName,\n hookName,\n parameters,\n }: {\n pluginName: string\n hookName: H\n parameters: PluginParameter<H>\n }): Array<ReturnType<ParseResult<H>>> | null {\n const plugins = this.getPluginsByName(hookName, pluginName)\n\n const result = plugins\n .map((plugin) => {\n return this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n })\n .filter((x): x is NonNullable<typeof x> => x !== null)\n\n return result\n }\n\n /**\n * Returns the first non-null result.\n */\n async hookFirst<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): Promise<SafeParseResult<H>> {\n const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {\n return skipped ? !skipped.has(plugin) : true\n })\n\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return async () => {\n const value = await this.#execute<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n })\n\n return Promise.resolve({\n plugin,\n result: value,\n } as SafeParseResult<H>)\n }\n })\n\n const result = await hookFirst(promises, hookFirstNullCheck)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return result\n }\n\n /**\n * Returns the first non-null result.\n */\n hookFirstSync<H extends PluginLifecycleHooks>({\n hookName,\n parameters,\n skipped,\n }: {\n hookName: H\n parameters: PluginParameter<H>\n skipped?: ReadonlySet<Plugin> | null\n }): SafeParseResult<H> | null {\n let parseResult: SafeParseResult<H> | null = null\n const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {\n return skipped ? !skipped.has(plugin) : true\n })\n\n for (const plugin of plugins) {\n parseResult = {\n result: this.#executeSync<H>({\n strategy: 'hookFirst',\n hookName,\n parameters,\n plugin,\n }),\n plugin,\n } as SafeParseResult<H>\n\n if (parseResult?.result != null) {\n break\n }\n }\n\n return parseResult\n }\n\n /**\n * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.\n */\n async hookParallel<H extends PluginLifecycleHooks, TOutput = void>({\n hookName,\n parameters,\n }: {\n hookName: H\n parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined\n }): Promise<Awaited<TOutput>[]> {\n const plugins = this.#getSortedPlugins(hookName)\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const pluginStartTimes = new Map<Plugin, number>()\n\n const promises = plugins.map((plugin) => {\n return () => {\n pluginStartTimes.set(plugin, performance.now())\n return this.#execute({\n strategy: 'hookParallel',\n hookName,\n parameters,\n plugin,\n }) as Promise<TOutput>\n }\n })\n\n const results = await hookParallel(promises, this.options.concurrency)\n\n results.forEach((result, index) => {\n if (isPromiseRejectedResult<Error>(result)) {\n const plugin = this.#getSortedPlugins(hookName)[index]\n\n if (plugin) {\n const startTime = pluginStartTimes.get(plugin) ?? performance.now()\n this.events.emit('error', result.reason, {\n plugin,\n hookName,\n strategy: 'hookParallel',\n duration: Math.round(performance.now() - startTime),\n parameters,\n })\n }\n }\n })\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n\n return results.reduce((acc, result) => {\n if (result.status === 'fulfilled') {\n acc.push(result.value)\n }\n return acc\n }, [] as Awaited<TOutput>[])\n }\n\n /**\n * Chains plugins\n */\n async hookSeq<H extends PluginLifecycleHooks>({ hookName, parameters }: { hookName: H; parameters?: PluginParameter<H> }): Promise<void> {\n const plugins = this.#getSortedPlugins(hookName)\n this.events.emit('plugins:hook:progress:start', { hookName, plugins })\n\n const promises = plugins.map((plugin) => {\n return () =>\n this.#execute({\n strategy: 'hookSeq',\n hookName,\n parameters,\n plugin,\n })\n })\n\n await hookSeq(promises)\n\n this.events.emit('plugins:hook:progress:end', { hookName })\n }\n\n #getSortedPlugins(hookName?: keyof PluginLifecycle): Array<Plugin> {\n const plugins = [...this.#plugins]\n\n if (hookName) {\n return plugins.filter((plugin) => hookName in plugin)\n }\n // TODO add test case for sorting with pre/post\n\n return plugins\n .map((plugin) => {\n if (plugin.pre) {\n let missingPlugins = plugin.pre.filter((pluginName) => !plugins.find((pluginToFind) => pluginToFind.name === pluginName))\n\n // when adapter is set, we can ignore the depends on plugin-oas, in v5 this will not be needed anymore\n if (missingPlugins.includes('plugin-oas') && this.adapter) {\n missingPlugins = missingPlugins.filter((pluginName) => pluginName !== 'plugin-oas')\n }\n\n if (missingPlugins.length > 0) {\n throw new ValidationPluginError(`The plugin '${plugin.name}' has a pre set that references missing plugins for '${missingPlugins.join(', ')}'`)\n }\n }\n\n return plugin\n })\n .sort((a, b) => {\n if (b.pre?.includes(a.name)) {\n return 1\n }\n if (b.post?.includes(a.name)) {\n return -1\n }\n return 0\n })\n }\n\n getPluginByName(pluginName: string): Plugin | undefined {\n const plugins = [...this.#plugins]\n\n return plugins.find((item) => item.name === pluginName)\n }\n\n getPluginsByName(hookName: keyof PluginWithLifeCycle, pluginName: string): Plugin[] {\n const plugins = [...this.plugins]\n\n const pluginByPluginName = plugins.filter((plugin) => hookName in plugin).filter((item) => item.name === pluginName)\n\n if (!pluginByPluginName?.length) {\n // fallback on the core plugin when there is no match\n\n const corePlugin = plugins.find((plugin) => plugin.name === CORE_PLUGIN_NAME && hookName in plugin)\n\n return corePlugin ? [corePlugin] : []\n }\n\n return pluginByPluginName\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n #emitProcessingEnd<H extends PluginLifecycleHooks>({\n startTime,\n output,\n strategy,\n hookName,\n plugin,\n parameters,\n }: {\n startTime: number\n output: unknown\n strategy: Strategy\n hookName: H\n plugin: PluginWithLifeCycle\n parameters: unknown[] | undefined\n }): void {\n this.events.emit('plugins:hook:processing:end', {\n duration: Math.round(performance.now() - startTime),\n parameters,\n output,\n strategy,\n hookName,\n plugin,\n })\n }\n\n // Implementation signature\n #execute<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: unknown[] | undefined\n plugin: PluginWithLifeCycle\n }): Promise<ReturnType<ParseResult<H>> | null> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n const task = (async () => {\n try {\n const output =\n typeof hook === 'function' ? await Promise.resolve((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters ?? [])) : hook\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output as ReturnType<ParseResult<H>>\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n })()\n\n return task\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual plugin\n */\n #executeSync<H extends PluginLifecycleHooks>({\n strategy,\n hookName,\n parameters,\n plugin,\n }: {\n strategy: Strategy\n hookName: H\n parameters: PluginParameter<H>\n plugin: PluginWithLifeCycle\n }): ReturnType<ParseResult<H>> | null {\n const hook = plugin[hookName]\n\n if (!hook) {\n return null\n }\n\n this.events.emit('plugins:hook:processing:start', {\n strategy,\n hookName,\n parameters,\n plugin,\n })\n\n const startTime = performance.now()\n\n try {\n const output =\n typeof hook === 'function'\n ? ((hook as (...args: unknown[]) => unknown).apply(this.getContext(plugin), parameters) as ReturnType<ParseResult<H>>)\n : (hook as ReturnType<ParseResult<H>>)\n\n this.#emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters })\n\n return output\n } catch (error) {\n this.events.emit('error', error as Error, {\n plugin,\n hookName,\n strategy,\n duration: Math.round(performance.now() - startTime),\n })\n\n return null\n }\n }\n\n #parse(plugin: UserPlugin): Plugin {\n const usedPluginNames = this.#usedPluginNames\n\n setUniqueName(plugin.name, usedPluginNames)\n\n const usageCount = usedPluginNames[plugin.name]\n if (usageCount && usageCount > 1) {\n throw new ValidationPluginError(\n `Duplicate plugin \"${plugin.name}\" detected. Each plugin can only be used once. Use a different configuration instead of adding multiple instances of the same plugin.`,\n )\n }\n\n return {\n install() {},\n ...plugin,\n } as unknown as Plugin\n }\n}\n","/**\n * Storage interface for persisting Kubb output.\n *\n * Keys are root-relative forward-slash paths (e.g. `src/gen/api/getPets.ts`).\n * Implement this interface to route generated files to any backend — filesystem,\n * S3, Redis, in-memory, etc.\n *\n * Use `defineStorage` to create a typed storage driver.\n */\nexport interface DefineStorage {\n /** Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`). */\n readonly name: string\n /** Returns `true` when an entry for `key` exists in storage. */\n hasItem(key: string): Promise<boolean>\n /** Returns the stored string value, or `null` when `key` does not exist. */\n getItem(key: string): Promise<string | null>\n /** Persists `value` under `key`, creating any required structure. */\n setItem(key: string, value: string): Promise<void>\n /** Removes the entry for `key`. No-ops when the key does not exist. */\n removeItem(key: string): Promise<void>\n /** Returns all keys, optionally filtered to those starting with `base`. */\n getKeys(base?: string): Promise<Array<string>>\n /** Removes all entries, optionally scoped to those starting with `base`. */\n clear(base?: string): Promise<void>\n /** Optional teardown hook called after the build completes. */\n dispose?(): Promise<void>\n}\n\n/**\n * Wraps a storage builder so the `options` argument is optional, following the\n * same factory pattern as `definePlugin`, `defineLogger`, and `defineAdapter`.\n *\n * The builder receives the resolved options object and must return a\n * `DefineStorage`-compatible object that includes a `name` string.\n *\n * @example\n * ```ts\n * import { defineStorage } from '@kubb/core'\n *\n * export const memoryStorage = defineStorage((_options) => {\n * const store = new Map<string, string>()\n * return {\n * name: 'memory',\n * async hasItem(key) { return store.has(key) },\n * async getItem(key) { return store.get(key) ?? null },\n * async setItem(key, value) { store.set(key, value) },\n * async removeItem(key) { store.delete(key) },\n * async getKeys() { return [...store.keys()] },\n * async clear() { store.clear() },\n * }\n * })\n * ```\n */\nexport function defineStorage<TOptions = Record<string, never>>(build: (options: TOptions) => DefineStorage): (options?: TOptions) => DefineStorage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import type { Dirent } from 'node:fs'\nimport { access, readdir, readFile, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { clean, write } from '@internals/utils'\nimport { defineStorage } from '../defineStorage.ts'\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in `output`.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Internally uses the `write` utility from `@internals/utils`, which:\n * - trims leading/trailing whitespace before writing\n * - skips the write when file content is already identical (deduplication)\n * - creates missing parent directories automatically\n * - supports Bun's native file API when running under Bun\n *\n * @example\n * ```ts\n * import { defineConfig, fsStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: fsStorage() },\n * })\n * ```\n */\nexport const fsStorage = defineStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch {\n return null\n }\n },\n async setItem(key: string, value: string) {\n await write(resolve(key), value, { sanity: false })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const keys: Array<string> = []\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, { withFileTypes: true })) as Array<Dirent>\n } catch {\n return\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n await walk(join(dir, entry.name), rel)\n } else {\n keys.push(rel)\n }\n }\n }\n\n await walk(resolve(base ?? process.cwd()), '')\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n}))\n","","import { version as nodeVersion } from 'node:process'\nimport { version as KubbVersion } from '../../package.json'\n\n/**\n * Get diagnostic information for debugging\n */\nexport function getDiagnosticInfo() {\n return {\n nodeVersion,\n KubbVersion,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n } as const\n}\n","import { dirname, relative, resolve } from 'node:path'\nimport { AsyncEventEmitter, exists, formatMs, getElapsedMs, getRelativePath, URLPath } from '@internals/utils'\nimport type { Fabric as FabricType, KubbFile } from '@kubb/fabric-core/types'\nimport { createFabric } from '@kubb/react-fabric'\nimport { typescriptParser } from '@kubb/react-fabric/parsers'\nimport { fsPlugin } from '@kubb/react-fabric/plugins'\nimport { isInputPath } from './config.ts'\nimport { BARREL_FILENAME, DEFAULT_BANNER, DEFAULT_CONCURRENCY, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport { BuildError } from './errors.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, DefineStorage, KubbEvents, Output, Plugin, UserConfig } from './types.ts'\nimport { getDiagnosticInfo } from './utils/diagnostics.ts'\nimport type { FileMetaBase } from './utils/getBarrelFiles.ts'\n\ntype BuildOptions = {\n config: UserConfig\n events?: AsyncEventEmitter<KubbEvents>\n}\n\ntype BuildOutput = {\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n fabric: FabricType\n files: Array<KubbFile.ResolvedFile>\n driver: PluginDriver\n pluginTimings: Map<string, number>\n error?: Error\n sources: Map<KubbFile.Path, string>\n}\n\ntype SetupResult = {\n events: AsyncEventEmitter<KubbEvents>\n fabric: FabricType\n driver: PluginDriver\n sources: Map<KubbFile.Path, string>\n}\n\nexport async function setup(options: BuildOptions): Promise<SetupResult> {\n const { config: userConfig, events = new AsyncEventEmitter<KubbEvents>() } = options\n\n const sources: Map<KubbFile.Path, string> = new Map<KubbFile.Path, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await events.emit('warn', 'This feature is still under development — use with caution')\n }\n\n await events.emit('debug', {\n date: new Date(),\n logs: [\n 'Configuration:',\n ` • Name: ${userConfig.name || 'unnamed'}`,\n ` • Root: ${userConfig.root || process.cwd()}`,\n ` • Output: ${userConfig.output?.path || 'not specified'}`,\n ` • Plugins: ${userConfig.plugins?.length || 0}`,\n 'Output Settings:',\n ` • Storage: ${userConfig.output?.storage ? `custom(${userConfig.output.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,\n ` • Formatter: ${userConfig.output?.format || 'none'}`,\n ` • Linter: ${userConfig.output?.lint || 'none'}`,\n 'Environment:',\n Object.entries(diagnosticInfo)\n .map(([key, value]) => ` • ${key}: ${value}`)\n .join('\\n'),\n ],\n })\n\n try {\n if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {\n await exists(userConfig.input.path)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ Input file validated: ${userConfig.input.path}`],\n })\n }\n } catch (caughtError) {\n if (isInputPath(userConfig)) {\n const error = caughtError as Error\n\n throw new Error(\n `Cannot read file/URL defined in \\`input.path\\` or set with \\`kubb generate PATH\\` in the CLI of your Kubb config ${userConfig.input.path}`,\n {\n cause: error,\n },\n )\n }\n }\n\n const definedConfig: Config = {\n root: userConfig.root || process.cwd(),\n ...userConfig,\n output: {\n write: true,\n barrelType: 'named',\n extension: DEFAULT_EXTENSION,\n defaultBanner: DEFAULT_BANNER,\n ...userConfig.output,\n },\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins as Config['plugins'],\n }\n\n // write: false is the explicit dry-run opt-out; otherwise use the provided\n // storage or fall back to fsStorage (backwards-compatible default).\n // Keys are root-relative (e.g. `src/gen/api/getPets.ts`) so fsStorage()\n // needs no configuration — it resolves them against process.cwd().\n const storage: DefineStorage | null = definedConfig.output.write === false ? null : (definedConfig.output.storage ?? fsStorage())\n\n if (definedConfig.output.clean) {\n await events.emit('debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${definedConfig.output.path}`],\n })\n await storage?.clear(resolve(definedConfig.root, definedConfig.output.path))\n }\n\n const fabric = createFabric()\n fabric.use(fsPlugin)\n fabric.use(typescriptParser)\n\n fabric.context.on('files:processing:start', (files) => {\n events.emit('files:processing:start', files)\n events.emit('debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n })\n\n fabric.context.on('file:processing:update', async (params) => {\n const { file, source } = params\n await events.emit('file:processing:update', {\n ...params,\n config: definedConfig,\n source,\n })\n\n if (source) {\n // Key is root-relative so it's meaningful for any backend (fs, S3, Redis…)\n const key = relative(resolve(definedConfig.root), file.path)\n await storage?.setItem(key, source)\n sources.set(file.path, source)\n }\n })\n\n fabric.context.on('files:processing:end', async (files) => {\n await events.emit('files:processing:end', files)\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${files.length} files`],\n })\n })\n\n await events.emit('debug', {\n date: new Date(),\n logs: [\n '✓ Fabric initialized',\n ` • Storage: ${storage ? storage.name : 'disabled (dry-run)'}`,\n ` • Barrel type: ${definedConfig.output.barrelType || 'none'}`,\n ],\n })\n\n const pluginDriver = new PluginDriver(definedConfig, {\n fabric,\n events,\n concurrency: DEFAULT_CONCURRENCY,\n })\n\n // Run the adapter (if provided) to produce the universal RootNode\n if (definedConfig.adapter) {\n const source = inputToAdapterSource(definedConfig)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`Running adapter: ${definedConfig.adapter.name}`],\n })\n\n pluginDriver.adapter = definedConfig.adapter\n pluginDriver.rootNode = await definedConfig.adapter.parse(source)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${definedConfig.adapter.name}' resolved RootNode`,\n ` • Schemas: ${pluginDriver.rootNode.schemas.length}`,\n ` • Operations: ${pluginDriver.rootNode.operations.length}`,\n ],\n })\n }\n\n return {\n events,\n fabric,\n driver: pluginDriver,\n sources,\n }\n}\n\nexport async function build(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(options, overrides)\n\n if (error) {\n throw error\n }\n\n if (failedPlugins.size > 0) {\n const errors = [...failedPlugins].map(({ error }) => error)\n\n throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })\n }\n\n return {\n failedPlugins,\n fabric,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\nexport async function safeBuild(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, driver, events, sources } = overrides ? overrides : await setup(options)\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n // in ms\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\n for (const plugin of driver.plugins) {\n const context = driver.getContext(plugin)\n const hrStart = process.hrtime()\n\n const installer = plugin.install.bind(context)\n\n try {\n const timestamp = new Date()\n\n await events.emit('plugin:start', plugin)\n\n await events.emit('debug', {\n date: timestamp,\n logs: ['Installing plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n await installer(context)\n\n const duration = getElapsedMs(hrStart)\n pluginTimings.set(plugin.name, duration)\n\n await events.emit('plugin:end', plugin, { duration, success: true })\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ Plugin installed successfully (${formatMs(duration)})`],\n })\n } catch (caughtError) {\n const error = caughtError as Error\n const errorTimestamp = new Date()\n const duration = getElapsedMs(hrStart)\n\n await events.emit('plugin:end', plugin, {\n duration,\n success: false,\n error,\n })\n\n await events.emit('debug', {\n date: errorTimestamp,\n logs: [\n '✗ Plugin installation failed',\n ` • Plugin Name: ${plugin.name}`,\n ` • Error: ${error.constructor.name} - ${error.message}`,\n ' • Stack Trace:',\n error.stack || 'No stack trace available',\n ],\n })\n\n failedPlugins.add({ plugin, error })\n }\n }\n\n if (config.output.barrelType) {\n const root = resolve(config.root)\n const rootPath = resolve(root, config.output.path, BARREL_FILENAME)\n const rootDir = dirname(rootPath)\n\n await events.emit('debug', {\n date: new Date(),\n logs: ['Generating barrel file', ` • Type: ${config.output.barrelType}`, ` • Path: ${rootPath}`],\n })\n\n const barrelFiles = fabric.files.filter((file) => {\n return file.sources.some((source) => source.isIndexable)\n })\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`Found ${barrelFiles.length} indexable files for barrel export`],\n })\n\n const existingBarrel = fabric.files.find((f) => f.path === rootPath)\n const existingExports = new Set(\n existingBarrel?.exports?.flatMap((e) => (Array.isArray(e.name) ? e.name : [e.name])).filter((n): n is string => Boolean(n)) ?? [],\n )\n\n const rootFile: KubbFile.File = {\n path: rootPath,\n baseName: BARREL_FILENAME,\n exports: buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }),\n sources: [],\n imports: [],\n meta: {},\n }\n\n await fabric.upsertFile(rootFile)\n\n await events.emit('debug', {\n date: new Date(),\n logs: [`✓ Generated barrel file (${rootFile.exports?.length || 0} exports)`],\n })\n }\n\n const files = [...fabric.files]\n\n await fabric.write({ extension: config.output.extension })\n\n return {\n failedPlugins,\n fabric,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n fabric,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n }\n}\n\ntype BuildBarrelExportsParams = {\n barrelFiles: KubbFile.ResolvedFile[]\n rootDir: string\n existingExports: Set<string>\n config: Config\n driver: PluginDriver\n}\n\nfunction buildBarrelExports({ barrelFiles, rootDir, existingExports, config, driver }: BuildBarrelExportsParams): KubbFile.Export[] {\n const pluginNameMap = new Map<string, Plugin>()\n for (const plugin of driver.plugins) {\n pluginNameMap.set(plugin.name, plugin)\n }\n\n return barrelFiles.flatMap((file) => {\n const containsOnlyTypes = file.sources?.every((source) => source.isTypeOnly)\n\n return (file.sources ?? []).flatMap((source) => {\n if (!file.path || !source.isIndexable) {\n return []\n }\n\n const meta = file.meta as FileMetaBase | undefined\n const plugin = meta?.pluginName ? pluginNameMap.get(meta.pluginName) : undefined\n const pluginOptions = plugin?.options as { output?: Output<unknown> } | undefined\n\n if (!pluginOptions || pluginOptions.output?.barrelType === false) {\n return []\n }\n\n const exportName = config.output.barrelType === 'all' ? undefined : source.name ? [source.name] : undefined\n if (exportName?.some((n) => existingExports.has(n))) {\n return []\n }\n\n return [\n {\n name: exportName,\n path: getRelativePath(rootDir, file.path),\n isTypeOnly: config.output.barrelType === 'all' ? containsOnlyTypes : source.isTypeOnly,\n } satisfies KubbFile.Export,\n ]\n })\n })\n}\n\n/**\n * Maps the resolved `Config['input']` shape into an `AdapterSource` that\n * the adapter's `parse()` can consume.\n */\nfunction inputToAdapterSource(config: Config): AdapterSource {\n if (Array.isArray(config.input)) {\n return {\n type: 'paths',\n paths: config.input.map((i) => resolve(config.root, i.path)),\n }\n }\n\n if ('data' in config.input) {\n return { type: 'data', data: config.input.data }\n }\n\n const resolved = resolve(config.root, config.input.path)\n return { type: 'path', path: resolved }\n}\n","import type { Adapter, AdapterFactoryOptions } from './types.ts'\n\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Wraps an adapter builder to make the options parameter optional.\n *\n * @example\n * ```ts\n * export const adapterOas = defineAdapter<OasAdapter>((options) => {\n * const { validate = true, dateType = 'string' } = options\n * return {\n * name: adapterOasName,\n * options: { validate, dateType, ... },\n * parse(source) { ... },\n * }\n * })\n * ```\n */\nexport function defineAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import type { OperationNode, SchemaNode } from '@kubb/ast/types'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport type { FabricReactNode } from '@kubb/react-fabric/types'\nimport type { Adapter, Config, Plugin, PluginFactoryOptions } from './types.ts'\n\nexport type Version = '1' | '2'\n\n// V2 props — fully typed with @kubb/ast (already a @kubb/core dependency)\nexport type OperationsV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n options: Plugin<TPlugin>['options']\n nodes: Array<OperationNode>\n}\n\nexport type OperationV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n options: Plugin<TPlugin>['options']\n node: OperationNode\n}\n\nexport type SchemaV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n options: Plugin<TPlugin>['options']\n node: SchemaNode\n}\n\ntype UserCoreGeneratorV2<TPlugin extends PluginFactoryOptions> = {\n name: string\n type: 'core'\n version?: '2'\n operations?(props: OperationsV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n operation?(props: OperationV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n schema?(props: SchemaV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n}\n\ntype UserReactGeneratorV2<TPlugin extends PluginFactoryOptions> = {\n name: string\n type: 'react'\n version?: '2'\n Operations?(props: OperationsV2Props<TPlugin>): FabricReactNode\n Operation?(props: OperationV2Props<TPlugin>): FabricReactNode\n Schema?(props: SchemaV2Props<TPlugin>): FabricReactNode\n}\n\nexport type CoreGeneratorV2<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n name: string\n type: 'core'\n version: '2'\n operations(props: OperationsV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n operation(props: OperationV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n schema(props: SchemaV2Props<TPlugin>): Promise<Array<KubbFile.File>>\n}\n\nexport type ReactGeneratorV2<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n name: string\n type: 'react'\n version: '2'\n Operations(props: OperationsV2Props<TPlugin>): FabricReactNode\n Operation(props: OperationV2Props<TPlugin>): FabricReactNode\n Schema(props: SchemaV2Props<TPlugin>): FabricReactNode\n}\n\nexport type Generator<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = UserCoreGeneratorV2<TPlugin> | UserReactGeneratorV2<TPlugin>\n\nexport function defineGenerator<TPlugin extends PluginFactoryOptions = PluginFactoryOptions>(\n generator: UserReactGeneratorV2<TPlugin>,\n): ReactGeneratorV2<TPlugin>\n\nexport function defineGenerator<TPlugin extends PluginFactoryOptions = PluginFactoryOptions>(generator: UserCoreGeneratorV2<TPlugin>): CoreGeneratorV2<TPlugin>\n\nexport function defineGenerator<TPlugin extends PluginFactoryOptions = PluginFactoryOptions>(\n generator: UserCoreGeneratorV2<TPlugin> | UserReactGeneratorV2<TPlugin>,\n): unknown {\n if (generator.type === 'react') {\n return {\n version: '2',\n Operations() {\n return null\n },\n Operation() {\n return null\n },\n Schema() {\n return null\n },\n ...generator,\n }\n }\n\n return {\n version: '2',\n async operations() {\n return []\n },\n async operation() {\n return []\n },\n async schema() {\n return []\n },\n ...generator,\n }\n}\n","import type { Logger, LoggerOptions, UserLogger } from './types.ts'\n\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions>(logger: UserLogger<Options>): Logger<Options> {\n return {\n ...logger,\n }\n}\n","import type { PluginFactoryOptions, UserPluginWithLifeCycle } from './types.ts'\n\ntype PluginBuilder<T extends PluginFactoryOptions = PluginFactoryOptions> = (options: T['options']) => UserPluginWithLifeCycle<T>\n\n/**\n * Wraps a plugin builder to make the options parameter optional.\n */\nexport function definePlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(\n build: PluginBuilder<T>,\n): (options?: T['options']) => UserPluginWithLifeCycle<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import mod from 'node:module'\nimport os from 'node:os'\nimport { pathToFileURL } from 'node:url'\nimport { read, readSync } from '@internals/utils'\nimport * as pkg from 'empathic/package'\nimport { coerce, satisfies } from 'semver'\nimport { PATH_SEPARATORS } from './constants.ts'\n\ntype PackageJSON = {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}\n\ntype DependencyName = string\n\ntype DependencyVersion = string\n\nexport class PackageManager {\n static #cache: Record<DependencyName, DependencyVersion> = {}\n\n #cwd?: string\n\n constructor(workspace?: string) {\n if (workspace) {\n this.#cwd = workspace\n }\n }\n\n set workspace(workspace: string) {\n this.#cwd = workspace\n }\n\n get workspace(): string | undefined {\n return this.#cwd\n }\n\n normalizeDirectory(directory: string): string {\n const lastChar = directory[directory.length - 1]\n if (lastChar && !(PATH_SEPARATORS as readonly string[]).includes(lastChar)) {\n return `${directory}/`\n }\n\n return directory\n }\n\n getLocation(path: string): string {\n let location = path\n\n if (this.#cwd) {\n const require = mod.createRequire(this.normalizeDirectory(this.#cwd))\n location = require.resolve(path)\n }\n\n return location\n }\n\n async import(path: string): Promise<unknown> {\n let location = this.getLocation(path)\n\n if (os.platform() === 'win32') {\n location = pathToFileURL(location).href\n }\n\n const module = await import(location)\n\n return module?.default ?? module\n }\n\n async getPackageJSON(): Promise<PackageJSON | undefined> {\n const pkgPath = pkg.up({\n cwd: this.#cwd,\n })\n if (!pkgPath) {\n return undefined\n }\n\n const json = await read(pkgPath)\n\n return JSON.parse(json) as PackageJSON\n }\n\n getPackageJSONSync(): PackageJSON | undefined {\n const pkgPath = pkg.up({\n cwd: this.#cwd,\n })\n if (!pkgPath) {\n return undefined\n }\n\n const json = readSync(pkgPath)\n\n return JSON.parse(json) as PackageJSON\n }\n\n static setVersion(dependency: DependencyName, version: DependencyVersion): void {\n PackageManager.#cache[dependency] = version\n }\n\n #match(packageJSON: PackageJSON, dependency: DependencyName | RegExp): string | undefined {\n const dependencies = {\n ...(packageJSON.dependencies || {}),\n ...(packageJSON.devDependencies || {}),\n }\n\n if (typeof dependency === 'string' && dependencies[dependency]) {\n return dependencies[dependency]\n }\n\n const matchedDependency = Object.keys(dependencies).find((dep) => dep.match(dependency))\n\n return matchedDependency ? dependencies[matchedDependency] : undefined\n }\n\n async getVersion(dependency: DependencyName | RegExp): Promise<DependencyVersion | undefined> {\n if (typeof dependency === 'string' && PackageManager.#cache[dependency]) {\n return PackageManager.#cache[dependency]\n }\n\n const packageJSON = await this.getPackageJSON()\n\n if (!packageJSON) {\n return undefined\n }\n\n return this.#match(packageJSON, dependency)\n }\n\n getVersionSync(dependency: DependencyName | RegExp): DependencyVersion | undefined {\n if (typeof dependency === 'string' && PackageManager.#cache[dependency]) {\n return PackageManager.#cache[dependency]\n }\n\n const packageJSON = this.getPackageJSONSync()\n\n if (!packageJSON) {\n return undefined\n }\n\n return this.#match(packageJSON, dependency)\n }\n\n async isValid(dependency: DependencyName | RegExp, version: DependencyVersion): Promise<boolean> {\n const packageVersion = await this.getVersion(dependency)\n\n if (!packageVersion) {\n return false\n }\n\n if (packageVersion === version) {\n return true\n }\n\n const semVer = coerce(packageVersion)\n\n if (!semVer) {\n return false\n }\n\n return satisfies(semVer, version)\n }\n isValidSync(dependency: DependencyName | RegExp, version: DependencyVersion): boolean {\n const packageVersion = this.getVersionSync(dependency)\n\n if (!packageVersion) {\n return false\n }\n\n if (packageVersion === version) {\n return true\n }\n\n const semVer = coerce(packageVersion)\n\n if (!semVer) {\n return false\n }\n\n return satisfies(semVer, version)\n }\n}\n","import { defineStorage } from '../defineStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { defineConfig, memoryStorage } from '@kubb/core'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen', storage: memoryStorage() },\n * })\n * ```\n */\nexport const memoryStorage = defineStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n","import { camelCase } from '@internals/utils'\n// TODO replace with @internals/utils\nimport { sortBy } from 'remeda'\n\ntype FunctionParamsASTWithoutType = {\n name?: string\n type?: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n\ntype FunctionParamsASTWithType = {\n name?: never\n type: string\n /**\n * @default true\n */\n required?: boolean\n /**\n * @default true\n */\n enabled?: boolean\n default?: string\n}\n/**\n * @deprecated\n */\nexport type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType\n\n/**\n * @deprecated\n */\nexport class FunctionParams {\n #items: Array<FunctionParamsAST | FunctionParamsAST[]> = []\n\n get items(): FunctionParamsAST[] {\n return this.#items.flat()\n }\n\n add(item: FunctionParamsAST | Array<FunctionParamsAST | FunctionParamsAST[] | undefined> | undefined): FunctionParams {\n if (!item) {\n return this\n }\n\n if (Array.isArray(item)) {\n item\n .filter((x): x is FunctionParamsAST | FunctionParamsAST[] => x !== undefined)\n .forEach((it) => {\n this.#items.push(it)\n })\n return this\n }\n this.#items.push(item)\n\n return this\n }\n static #orderItems(items: Array<FunctionParamsAST | FunctionParamsAST[]>) {\n return sortBy(\n items.filter(Boolean),\n [(item) => Array.isArray(item), 'desc'], // arrays (rest params) first\n [(item) => !Array.isArray(item) && (item as FunctionParamsAST).default !== undefined, 'asc'], // no-default before has-default\n [(item) => Array.isArray(item) || ((item as FunctionParamsAST).required ?? true), 'desc'], // required before optional\n )\n }\n\n static #addParams(acc: string[], item: FunctionParamsAST) {\n const { enabled = true, name, type, required = true, ...rest } = item\n\n if (!enabled) {\n return acc\n }\n\n if (!name) {\n // when name is not se we uses TypeScript generics\n acc.push(`${type}${rest.default ? ` = ${rest.default}` : ''}`)\n\n return acc\n }\n // TODO check why we still need the camelcase here\n const parameterName = name.startsWith('{') ? name : camelCase(name)\n\n if (type) {\n if (required) {\n acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ''}`)\n } else {\n acc.push(`${parameterName}?: ${type}`)\n }\n } else {\n acc.push(`${parameterName}`)\n }\n\n return acc\n }\n\n static toObject(items: FunctionParamsAST[]): FunctionParamsAST {\n let type: string[] = []\n let name: string[] = []\n\n const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true\n const required = items.every((item) => item.required) ?? true\n\n items.forEach((item) => {\n name = FunctionParams.#addParams(name, { ...item, type: undefined })\n if (items.some((item) => item.type)) {\n type = FunctionParams.#addParams(type, item)\n }\n })\n\n return {\n name: `{ ${name.join(', ')} }`,\n type: type.length ? `{ ${type.join('; ')} }` : undefined,\n enabled,\n required,\n }\n }\n\n toObject(): FunctionParamsAST {\n const items = FunctionParams.#orderItems(this.#items).flat()\n\n return FunctionParams.toObject(items)\n }\n\n static toString(items: (FunctionParamsAST | FunctionParamsAST[])[]): string {\n const sortedData = FunctionParams.#orderItems(items)\n\n return sortedData\n .reduce((acc, item) => {\n if (Array.isArray(item)) {\n if (item.length <= 0) {\n return acc\n }\n const subItems = FunctionParams.#orderItems(item) as FunctionParamsAST[]\n const objectItem = FunctionParams.toObject(subItems)\n\n return FunctionParams.#addParams(acc, objectItem)\n }\n\n return FunctionParams.#addParams(acc, item)\n }, [] as string[])\n .join(', ')\n }\n\n toString(): string {\n const items = FunctionParams.#orderItems(this.#items)\n\n return FunctionParams.toString(items)\n }\n}\n","import { x } from 'tinyexec'\nimport type { formatters } from '../constants.ts'\n\ntype Formatter = keyof typeof formatters\n\n/**\n * Check if a formatter command is available in the system.\n *\n * @param formatter - The formatter to check ('biome', 'prettier', or 'oxfmt')\n * @returns Promise that resolves to true if the formatter is available, false otherwise\n *\n * @remarks\n * This function checks availability by running `<formatter> --version` command.\n * All supported formatters (biome, prettier, oxfmt) implement the --version flag.\n */\nasync function isFormatterAvailable(formatter: Formatter): Promise<boolean> {\n try {\n // Try to get the version of the formatter to check if it's installed\n await x(formatter, ['--version'], { nodeOptions: { stdio: 'ignore' } })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Detect which formatter is available in the system.\n *\n * @returns Promise that resolves to the first available formatter or undefined if none are found\n *\n * @remarks\n * Checks in order of preference: biome, oxfmt, prettier.\n * Uses the `--version` flag to detect if each formatter command is available.\n * This is a reliable method as all supported formatters implement this flag.\n *\n * @example\n * ```typescript\n * const formatter = await detectFormatter()\n * if (formatter) {\n * console.log(`Using ${formatter} for formatting`)\n * } else {\n * console.log('No formatter found')\n * }\n * ```\n */\nexport async function detectFormatter(): Promise<Formatter | undefined> {\n const formatterNames: Formatter[] = ['biome', 'oxfmt', 'prettier']\n\n for (const formatter of formatterNames) {\n if (await isFormatterAvailable(formatter)) {\n return formatter\n }\n }\n\n return undefined\n}\n","import path from 'node:path'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport { getMode } from '../PluginDriver.ts'\n\ntype BarrelData = {\n file?: KubbFile.File\n /**\n * @deprecated use file instead\n */\n type: KubbFile.Mode\n path: string\n name: string\n}\n\nexport class TreeNode {\n data: BarrelData\n parent?: TreeNode\n children: Array<TreeNode> = []\n #cachedLeaves?: Array<TreeNode> = undefined\n\n constructor(data: BarrelData, parent?: TreeNode) {\n this.data = data\n this.parent = parent\n }\n\n addChild(data: BarrelData): TreeNode {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n get root(): TreeNode {\n if (!this.parent) {\n return this\n }\n return this.parent.root\n }\n\n get leaves(): Array<TreeNode> {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n if (this.#cachedLeaves) {\n return this.#cachedLeaves\n }\n\n const leaves: TreeNode[] = []\n for (const child of this.children) {\n leaves.push(...child.leaves)\n }\n\n this.#cachedLeaves = leaves\n\n return leaves\n }\n\n forEach(callback: (treeNode: TreeNode) => void): this {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n callback(this)\n\n for (const child of this.children) {\n child.forEach(callback)\n }\n\n return this\n }\n\n findDeep(predicate?: (value: TreeNode, index: number, obj: TreeNode[]) => boolean): TreeNode | undefined {\n if (typeof predicate !== 'function') {\n throw new TypeError('find() predicate must be a function')\n }\n\n return this.leaves.find(predicate)\n }\n\n forEachDeep(callback: (treeNode: TreeNode) => void): void {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n this.leaves.forEach(callback)\n }\n\n filterDeep(callback: (treeNode: TreeNode) => boolean): Array<TreeNode> {\n if (typeof callback !== 'function') {\n throw new TypeError('filter() callback must be a function')\n }\n\n return this.leaves.filter(callback)\n }\n\n mapDeep<T>(callback: (treeNode: TreeNode) => T): Array<T> {\n if (typeof callback !== 'function') {\n throw new TypeError('map() callback must be a function')\n }\n\n return this.leaves.map(callback)\n }\n\n public static build(files: KubbFile.File[], root?: string): TreeNode | null {\n try {\n const filteredTree = buildDirectoryTree(files, root)\n\n if (!filteredTree) {\n return null\n }\n\n const treeNode = new TreeNode({\n name: filteredTree.name,\n path: filteredTree.path,\n file: filteredTree.file,\n type: getMode(filteredTree.path),\n })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({\n name: item.name,\n path: item.path,\n file: item.file,\n type: getMode(item.path),\n })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => {\n recurse(treeNode, child)\n })\n\n return treeNode\n } catch (error) {\n throw new Error('Something went wrong with creating barrel files with the TreeNode class', { cause: error })\n }\n }\n}\n\ntype DirectoryTree = {\n name: string\n path: string\n file?: KubbFile.File\n children: Array<DirectoryTree>\n}\n\nconst normalizePath = (p: string): string => p.replaceAll('\\\\', '/')\n\nfunction buildDirectoryTree(files: Array<KubbFile.File>, rootFolder = ''): DirectoryTree | null {\n const normalizedRootFolder = normalizePath(rootFolder)\n const rootPrefix = normalizedRootFolder.endsWith('/') ? normalizedRootFolder : `${normalizedRootFolder}/`\n\n const filteredFiles = files.filter((file) => {\n const normalizedFilePath = normalizePath(file.path)\n return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith('.json') : !normalizedFilePath.endsWith('.json')\n })\n\n if (filteredFiles.length === 0) {\n return null // No files match the root folder\n }\n\n const root: DirectoryTree = {\n name: rootFolder || '',\n path: rootFolder || '',\n children: [],\n }\n\n filteredFiles.forEach((file) => {\n const relativePath = file.path.slice(rootFolder.length)\n const parts = relativePath.split('/').filter(Boolean)\n let currentLevel: DirectoryTree[] = root.children\n let currentPath = normalizePath(rootFolder)\n\n parts.forEach((part, index) => {\n currentPath = path.posix.join(currentPath, part)\n\n let existingNode = currentLevel.find((node) => node.name === part)\n\n if (!existingNode) {\n if (index === parts.length - 1) {\n // If its the last part, its a file\n existingNode = {\n name: part,\n file,\n path: currentPath,\n } as DirectoryTree\n } else {\n // Otherwise, its a folder\n existingNode = {\n name: part,\n path: currentPath,\n children: [],\n } as DirectoryTree\n }\n currentLevel.push(existingNode)\n }\n\n // Move to the next level if its a folder\n if (!existingNode.file) {\n currentLevel = existingNode.children\n }\n })\n })\n\n return root\n}\n","/** biome-ignore-all lint/suspicious/useIterableCallbackReturn: not needed */\nimport { join } from 'node:path'\nimport { getRelativePath } from '@internals/utils'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport type { BarrelType } from '../types.ts'\nimport { TreeNode } from './TreeNode.ts'\n\nexport type FileMetaBase = {\n pluginName?: string\n}\n\ntype AddIndexesProps = {\n type: BarrelType | false | undefined\n /**\n * Root based on root and output.path specified in the config\n */\n root: string\n /**\n * Output for plugin\n */\n output: {\n path: string\n }\n group?: {\n output: string\n exportAs: string\n }\n\n meta?: FileMetaBase\n}\n\nfunction getBarrelFilesByRoot(root: string | undefined, files: Array<KubbFile.ResolvedFile>): Array<KubbFile.File> {\n const cachedFiles = new Map<KubbFile.Path, KubbFile.File>()\n\n TreeNode.build(files, root)?.forEach((treeNode) => {\n if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {\n return\n }\n\n const barrelFilePath = join(treeNode.parent?.data.path, 'index.ts') as KubbFile.Path\n const barrelFile: KubbFile.File = {\n path: barrelFilePath,\n baseName: 'index.ts',\n exports: [],\n imports: [],\n sources: [],\n }\n const previousBarrelFile = cachedFiles.get(barrelFile.path)\n const leaves = treeNode.leaves\n\n leaves.forEach((item) => {\n if (!item.data.name) {\n return\n }\n\n const sources = item.data.file?.sources || []\n\n sources.forEach((source) => {\n if (!item.data.file?.path || !source.isIndexable || !source.name) {\n return\n }\n const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some(\n (item) => item.name === source.name && item.isTypeOnly === source.isTypeOnly,\n )\n\n if (alreadyContainInPreviousBarrelFile) {\n return\n }\n\n barrelFile.exports!.push({\n name: [source.name],\n path: getRelativePath(treeNode.parent?.data.path, item.data.path),\n isTypeOnly: source.isTypeOnly,\n })\n\n barrelFile.sources.push({\n name: source.name,\n isTypeOnly: source.isTypeOnly,\n //TODO use parser to generate import\n value: '',\n isExportable: false,\n isIndexable: false,\n })\n })\n })\n\n if (previousBarrelFile) {\n previousBarrelFile.sources.push(...barrelFile.sources)\n previousBarrelFile.exports?.push(...(barrelFile.exports || []))\n } else {\n cachedFiles.set(barrelFile.path, barrelFile)\n }\n })\n\n return [...cachedFiles.values()]\n}\n\nfunction trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n // Only strip when the dot is found and no path separator follows it\n // (guards against stripping dots that are part of a directory name like /project.v2/gen)\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\nexport async function getBarrelFiles(files: Array<KubbFile.ResolvedFile>, { type, meta = {}, root, output }: AddIndexesProps): Promise<Array<KubbFile.File>> {\n if (!type || type === 'propagate') {\n return []\n }\n\n const pathToBuildFrom = join(root, output.path)\n\n if (trimExtName(pathToBuildFrom).endsWith('index')) {\n return []\n }\n\n const barrelFiles = getBarrelFilesByRoot(pathToBuildFrom, files)\n\n if (type === 'all') {\n return barrelFiles.map((file) => {\n return {\n ...file,\n exports: file.exports?.map((exportItem) => {\n return {\n ...exportItem,\n name: undefined,\n }\n }),\n }\n })\n }\n\n return barrelFiles.map((indexFile) => {\n return {\n ...indexFile,\n meta,\n }\n })\n}\n","import type { UnknownUserPlugin, UserConfig } from '../types.ts'\n\ntype PluginsArray = Array<Omit<UnknownUserPlugin, 'inject'>>\n\nfunction isJSONPlugins(plugins: UserConfig['plugins']): boolean {\n return Array.isArray(plugins) && plugins.some((plugin) => Array.isArray(plugin) && typeof (plugin as unknown[])[0] === 'string')\n}\n\nfunction isObjectPlugins(plugins: UserConfig['plugins']): boolean {\n return plugins instanceof Object && !Array.isArray(plugins)\n}\n\nexport function getPlugins(plugins: UserConfig['plugins']): Promise<PluginsArray | undefined> {\n if (isObjectPlugins(plugins)) {\n throw new Error('Object plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json')\n }\n\n if (isJSONPlugins(plugins)) {\n throw new Error('JSON plugins are not supported anymore, best to use http://kubb.dev/getting-started/configure#json')\n }\n\n return Promise.resolve(plugins)\n}\n","import type { CLIOptions, ConfigInput } from '../config.ts'\nimport type { Config, UserConfig } from '../types.ts'\nimport { getPlugins } from './getPlugins.ts'\n\n/**\n * Converting UserConfig to Config Array without a change in the object beside the JSON convert.\n */\nexport async function getConfigs(config: ConfigInput | UserConfig, args: CLIOptions): Promise<Array<Config>> {\n const resolvedConfig: Promise<UserConfig | Array<UserConfig>> =\n typeof config === 'function' ? Promise.resolve(config(args as CLIOptions)) : Promise.resolve(config)\n\n let userConfigs = await resolvedConfig\n\n if (!Array.isArray(userConfigs)) {\n userConfigs = [userConfigs]\n }\n\n const results: Array<Config> = []\n\n for (const item of userConfigs) {\n const plugins = item.plugins ? await getPlugins(item.plugins) : undefined\n\n results.push({\n ...item,\n plugins,\n } as Config)\n }\n\n return results\n}\n","import { x } from 'tinyexec'\nimport type { linters } from '../constants.ts'\n\ntype Linter = keyof typeof linters\n\nasync function isLinterAvailable(linter: Linter): Promise<boolean> {\n try {\n await x(linter, ['--version'], { nodeOptions: { stdio: 'ignore' } })\n return true\n } catch {\n return false\n }\n}\n\nexport async function detectLinter(): Promise<Linter | undefined> {\n const linterNames: Linter[] = ['biome', 'oxlint', 'eslint']\n\n for (const linter of linterNames) {\n if (await isLinterAvailable(linter)) {\n return linter\n }\n }\n\n return undefined\n}\n","import { isOperationNode, isSchemaNode } from '@kubb/ast'\nimport type { Node, OperationNode, SchemaNode } from '@kubb/ast/types'\n\ntype FilterItem = {\n type: string\n pattern: string | RegExp\n}\n\ntype OverrideItem<TOptions> = FilterItem & {\n options: Omit<Partial<TOptions>, 'override'>\n}\n\ntype ResolveOptionsContext<TOptions> = {\n options: TOptions\n exclude?: Array<FilterItem>\n include?: Array<FilterItem>\n override?: Array<OverrideItem<TOptions>>\n}\n\nfunction matchesOperationPattern(node: OperationNode, type: string, pattern: string | RegExp): boolean {\n switch (type) {\n case 'tag':\n return node.tags.some((tag) => !!tag.match(pattern))\n case 'operationId':\n return !!node.operationId.match(pattern)\n case 'path':\n return !!node.path.match(pattern)\n case 'method':\n return !!(node.method.toLowerCase() as string).match(pattern)\n default:\n return false\n }\n}\n\nfunction matchesSchemaPattern(node: SchemaNode, type: string, pattern: string | RegExp): boolean | null {\n switch (type) {\n case 'schemaName':\n return node.name ? !!node.name.match(pattern) : false\n default:\n return null\n }\n}\n\n/**\n * Resolves the effective plugin options for a given AST node by applying\n * `exclude`, `include`, and `override` rules from the plugin configuration.\n *\n * Returns `null` when the node is excluded or not matched by `include`.\n * Returns the merged options (base options merged with any matching `override`) otherwise.\n *\n * Supported filter types for `OperationNode`: `tag`, `operationId`, `path`, `method`.\n * Supported filter types for `SchemaNode`: `schemaName`.\n *\n * @example\n * const resolved = resolveOptions(operationNode, { options, exclude, include, override })\n * if (!resolved) return // excluded\n */\nexport function resolveOptions<TOptions>(node: Node, { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>): TOptions | null {\n if (isOperationNode(node)) {\n const isExcluded = exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))\n if (isExcluded) {\n return null\n }\n\n if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) {\n return null\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options\n\n return { ...options, ...overrideOptions }\n }\n\n if (isSchemaNode(node)) {\n if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) {\n return null\n }\n\n if (include) {\n const results = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern))\n const applicable = results.filter((r) => r !== null)\n if (applicable.length > 0 && !applicable.includes(true)) {\n return null\n }\n }\n\n const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options\n\n return { ...options, ...overrideOptions }\n }\n\n return options\n}\n"],"x_google_ignoreList":[4,5],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAI,wBAAwB,cAAc,MAAM;;;;;AAKhD,IAAI,aAAa,cAAc,MAAM;CACpC;CACA,YAAY,SAAS,SAAS;AAC7B,QAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AACxC,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;;;;;;;;AAQxB,SAAS,QAAQ,OAAO;AACvB,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;AAqBjE,IAAI,oBAAoB,MAAM;;;;;CAK7B,YAAY,cAAc,IAAI;AAC7B,QAAA,QAAc,gBAAgB,YAAY;;CAE3C,WAAW,IAAIC,YAAAA,cAAc;;;;;CAK7B,MAAM,KAAK,WAAW,GAAG,WAAW;EACnC,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AACpD,MAAI,UAAU,WAAW,EAAG;AAC5B,QAAM,QAAQ,IAAI,UAAU,IAAI,OAAO,aAAa;AACnD,OAAI;AACH,WAAO,MAAM,SAAS,GAAG,UAAU;YAC3B,KAAK;IACb,IAAI;AACJ,QAAI;AACH,sBAAiB,KAAK,UAAU,UAAU;YACnC;AACP,sBAAiB,OAAO,UAAU;;AAEnC,UAAM,IAAI,MAAM,gCAAgC,UAAU,mBAAmB,kBAAkB,EAAE,OAAO,QAAQ,IAAI,EAAE,CAAC;;IAEvH,CAAC;;;CAGJ,GAAG,WAAW,SAAS;AACtB,QAAA,QAAc,GAAG,WAAW,QAAQ;;;CAGrC,OAAO,WAAW,SAAS;EAC1B,M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SAAS;GAEX,MAAM,aADU,QAAQ,KAAK,EAAE,MAAM,cAAc,qBAAqB,MAAM,MAAM,QAAQ,CAAC,CAClE,QAAQ,MAAM,MAAM,KAAK;AACpD,OAAI,WAAW,SAAS,KAAK,CAAC,WAAW,SAAS,KAAK,CACrD,QAAO;;EAIX,MAAM,kBAAkB,SAAS,MAAM,EAAE,MAAM,cAAc,qBAAqB,MAAM,MAAM,QAAQ,KAAK,KAAK,EAAE;AAElH,SAAO;GAAE,GAAG;GAAS,GAAG;GAAiB;;AAG3C,QAAO"}
1
+ {"version":3,"file":"index.cjs","names":["#emitter","NodeEventEmitter","#options","camelCase","#transformParam","#eachParam","#head","#tail","#size","#limit","DEFAULT_EXTENSION","DEFAULT_BANNER","DEFAULT_STUDIO_URL","PluginDriver","applyHookResult"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/createAdapter.ts","../../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js","../../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js","../src/FileProcessor.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/utils/isInputPath.ts","../src/createKubb.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineMiddleware.ts","../src/defineParser.ts","../src/definePlugin.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["/**\n * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","import { EventEmitter as NodeEventEmitter } from 'node:events'\nimport { toError } from './errors.ts'\n\n/**\n * A function that can be registered as an event listener, synchronous or async.\n */\ntype AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>\n\n/**\n * Typed `EventEmitter` that awaits all async listeners before resolving.\n * Wraps Node's `EventEmitter` with full TypeScript event-map inference.\n *\n * @example\n * ```ts\n * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()\n * emitter.on('build', async (name) => { console.log(name) })\n * await emitter.emit('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {\n /**\n * Maximum number of listeners per event before Node emits a memory-leak warning.\n * @default 10\n */\n constructor(maxListener = 10) {\n this.#emitter.setMaxListeners(maxListener)\n }\n\n #emitter = new NodeEventEmitter()\n\n /**\n * Emits `eventName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.\n *\n * @example\n * ```ts\n * await emitter.emit('build', 'petstore')\n * ```\n */\n async emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void> {\n const listeners = this.#emitter.listeners(eventName) as Array<AsyncListener<TEvents[TEventName]>>\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n try {\n await listener(...eventArgs)\n } catch (err) {\n let serializedArgs: string\n try {\n serializedArgs = JSON.stringify(eventArgs)\n } catch {\n serializedArgs = String(eventArgs)\n }\n throw new Error(`Error in async listener for \"${eventName}\" with eventArgs ${serializedArgs}`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', async (name) => { console.log(name) })\n * ```\n */\n on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.on(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Registers a one-shot listener that removes itself after the first invocation.\n *\n * @example\n * ```ts\n * emitter.onOnce('build', async (name) => { console.log(name) })\n * ```\n */\n onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n const wrapper: AsyncListener<TEvents[TEventName]> = (...args) => {\n this.off(eventName, wrapper)\n return handler(...args)\n }\n this.on(eventName, wrapper)\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * emitter.off('build', handler)\n * ```\n */\n off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.off(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Returns the number of listeners registered for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', handler)\n * emitter.listenerCount('build') // 1\n * ```\n */\n listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number {\n return this.#emitter.listenerCount(eventName)\n }\n\n /**\n * Removes all listeners from every event channel.\n *\n * @example\n * ```ts\n * emitter.removeAll()\n * ```\n */\n removeAll(): void {\n this.#emitter.removeAllListeners()\n }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n\n/**\n * Formats the elapsed time since `hrStart` as a human-readable string.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * formatHrtime(start) // '1.50s'\n * ```\n */\nexport function formatHrtime(hrStart: [number, number]): string {\n return formatMs(getElapsedMs(hrStart))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({\n prefix = '',\n replacer,\n }: {\n prefix?: string\n replacer?: (pathParam: string) => string\n } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import type { Adapter, AdapterFactoryOptions } from './types.ts'\n\n/**\n * Builder type for an {@link Adapter} — takes options and returns the adapter instance.\n */\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Creates an adapter factory. Call the returned function with optional options to get the adapter instance.\n *\n * @example\n * export const myAdapter = createAdapter<MyAdapter>((options) => {\n * return {\n * name: 'my-adapter',\n * options,\n * async parse(source) { ... },\n * }\n * })\n *\n * // instantiate\n * const adapter = myAdapter({ validate: true })\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tlet rejectOnClear = false;\n\n\tif (typeof concurrency === 'object') {\n\t\t({concurrency, rejectOnClear = false} = concurrency);\n\t}\n\n\tvalidateConcurrency(concurrency);\n\n\tif (typeof rejectOnClear !== 'boolean') {\n\t\tthrow new TypeError('Expected `rejectOnClear` to be a boolean');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\t// Process the next queued function if we're under the concurrency limit\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tactiveCount++;\n\t\t\tqueue.dequeue().run();\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\t// Execute the function and capture the result promise\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\t// Resolve immediately with the promise (don't wait for completion)\n\t\tresolve(result);\n\n\t\t// Wait for the function to complete (success or failure)\n\t\t// We catch errors here to prevent unhandled rejections,\n\t\t// but the original promise rejection is preserved for the caller\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\t// Decrement active count and process next queued function\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, reject, arguments_) => {\n\t\tconst queueItem = {reject};\n\n\t\t// Queue the internal resolve function instead of the run function\n\t\t// to preserve the asynchronous execution context.\n\t\tnew Promise(internalResolve => { // eslint-disable-line promise/param-names\n\t\t\tqueueItem.run = internalResolve;\n\t\t\tqueue.enqueue(queueItem);\n\t\t}).then(run.bind(undefined, function_, resolve, arguments_)); // eslint-disable-line promise/prefer-await-to-then\n\n\t\t// Start processing immediately if we haven't reached the concurrency limit\n\t\tif (activeCount < concurrency) {\n\t\t\tresumeNext();\n\t\t}\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise((resolve, reject) => {\n\t\tenqueue(function_, resolve, reject, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tif (!rejectOnClear) {\n\t\t\t\t\tqueue.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst abortError = AbortSignal.abort().reason;\n\n\t\t\t\twhile (queue.size > 0) {\n\t\t\t\t\tqueue.dequeue().reject(abortError);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmap: {\n\t\t\tasync value(iterable, function_) {\n\t\t\t\tconst promises = Array.from(iterable, (value, index) => this(function_, value, index));\n\t\t\t\treturn Promise.all(promises);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, options) {\n\tconst limit = pLimit(options);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","import type { CodeNode, FileNode } from '@kubb/ast'\nimport { extractStringsFromNodes } from '@kubb/ast'\nimport pLimit from 'p-limit'\nimport { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'\nimport type { Parser } from './defineParser.ts'\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n}\n\ntype RunOptions = ParseOptions & {\n /**\n * @default 'sequential'\n */\n mode?: 'sequential' | 'parallel'\n onStart?: (files: Array<FileNode>) => Promise<void> | void\n onEnd?: (files: Array<FileNode>) => Promise<void> | void\n onUpdate?: (params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }) => Promise<void> | void\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Converts a single file to a string using the registered parsers.\n * Falls back to joining source values when no matching parser is found.\n *\n * @internal\n */\nexport class FileProcessor {\n readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)\n\n async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {\n const parseExtName = extension?.[file.extname] || undefined\n\n if (!parsers || !file.extname) {\n return joinSources(file)\n }\n\n const parser = parsers.get(file.extname)\n\n if (!parser) {\n return joinSources(file)\n }\n\n return parser.parse(file, { extname: parseExtName })\n }\n\n async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension, onStart, onEnd, onUpdate }: RunOptions = {}): Promise<Array<FileNode>> {\n await onStart?.(files)\n\n const total = files.length\n let processed = 0\n\n const processOne = async (file: FileNode) => {\n const source = await this.parse(file, { extension, parsers })\n const currentProcessed = ++processed\n const percentage = (currentProcessed / total) * 100\n\n await onUpdate?.({\n file,\n source,\n processed: currentProcessed,\n percentage,\n total,\n })\n }\n\n if (mode === 'sequential') {\n for (const file of files) {\n await processOne(file)\n }\n } else {\n await Promise.all(files.map((file) => this.#limit(() => processOne(file))))\n }\n\n await onEnd?.(files)\n\n return files\n }\n}\n","export type Storage = {\n /**\n * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists in storage.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Returns the stored string value, or `null` when `key` does not exist.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Persists `value` under `key`, creating any required structure.\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Removes the entry for `key`. No-ops when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns all keys, optionally filtered to those starting with `base`.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes all entries, optionally scoped to those starting with `base`.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Creates a storage factory. Call the returned function with optional options to get the storage instance.\n *\n * @example\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n * return {\n * name: 'memory',\n * async hasItem(key) { return store.has(key) },\n * async getItem(key) { return store.get(key) ?? null },\n * async setItem(key, value) { store.set(key, value) },\n * async removeItem(key) { store.delete(key) },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) { if (!base) store.clear() },\n * }\n * })\n */\nexport function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import type { Dirent } from 'node:fs'\nimport { access, readdir, readFile, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { clean, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\n\n/**\n * Detects the filesystem error used to indicate that a path does not exist.\n */\nfunction isMissingPathError(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT'\n}\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in the root config.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Internally uses the `write` utility from `@internals/utils`, which:\n * - trims leading/trailing whitespace before writing\n * - skips the write when file content is already identical (deduplication)\n * - creates missing parent directories automatically\n * - supports Bun's native file API when running under Bun\n *\n * @example\n * ```ts\n * import { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (error) {\n if (isMissingPathError(error)) {\n return false\n }\n\n throw new Error(`Failed to access storage item \"${key}\"`, {\n cause: error as Error,\n })\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (error) {\n if (isMissingPathError(error)) {\n return null\n }\n\n throw new Error(`Failed to read storage item \"${key}\"`, {\n cause: error as Error,\n })\n }\n },\n async setItem(key: string, value: string) {\n await write(resolve(key), value, { sanity: false })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const keys: Array<string> = []\n const resolvedBase = resolve(base ?? process.cwd())\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, {\n withFileTypes: true,\n })) as Array<Dirent>\n } catch (error) {\n if (isMissingPathError(error)) {\n return\n }\n\n throw new Error(`Failed to list storage keys under \"${resolvedBase}\"`, {\n cause: error as Error,\n })\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n await walk(join(dir, entry.name), rel)\n } else {\n keys.push(rel)\n }\n }\n }\n\n await walk(resolvedBase, '')\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n}))\n","","import { version as nodeVersion } from 'node:process'\nimport { version as KubbVersion } from '../../package.json'\n\n/**\n * Returns a snapshot of the current runtime environment.\n *\n * Useful for attaching context to debug logs and error reports so that\n * issues can be reproduced without manual information gathering.\n */\nexport function getDiagnosticInfo() {\n return {\n nodeVersion,\n KubbVersion,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n } as const\n}\n","import type { Config, InputPath, UserConfig } from '../types'\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: UserConfig | undefined): config is UserConfig<InputPath>\nexport function isInputPath(config: Config | undefined): config is Config<InputPath>\nexport function isInputPath(config: Config | UserConfig | undefined): config is Config<InputPath> | UserConfig<InputPath> {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n","import { resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, URLPath } from '@internals/utils'\nimport type { FileNode, OperationNode } from '@kubb/ast'\nimport { transform, walk } from '@kubb/ast'\nimport { DEFAULT_BANNER, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Generator } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { Plugin } from './definePlugin.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport type { Kubb } from './Kubb.ts'\nimport { PluginDriver } from './PluginDriver.ts'\nimport { applyHookResult } from './renderNode.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, GeneratorContext, KubbHooks, Middleware, NormalizedPlugin, Storage, UserConfig } from './types.ts'\nimport { getDiagnosticInfo } from './utils/diagnostics.ts'\nimport { isInputPath } from './utils/isInputPath.ts'\n\ntype SetupOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n files: Array<FileNode>\n driver: PluginDriver\n /**\n * Elapsed time in milliseconds for each plugin, keyed by plugin name.\n */\n pluginTimings: Map<string, number>\n error?: Error\n /**\n * Raw generated source, keyed by absolute file path.\n */\n sources: Map<string, string>\n}\n\ntype SetupResult = {\n hooks: AsyncEventEmitter<KubbHooks>\n driver: PluginDriver\n sources: Map<string, string>\n config: Config\n storage: Storage | null\n}\n\nasync function setup(userConfig: UserConfig, options: SetupOptions = {}): Promise<SetupResult> {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n\n const sources: Map<string, string> = new Map<string, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n if (Array.isArray(userConfig.input)) {\n await hooks.emit('kubb:warn', { message: 'This feature is still under development — use with caution' })\n }\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n 'Configuration:',\n ` • Name: ${userConfig.name || 'unnamed'}`,\n ` • Root: ${userConfig.root || process.cwd()}`,\n ` • Output: ${userConfig.output?.path || 'not specified'}`,\n ` • Plugins: ${userConfig.plugins?.length || 0}`,\n 'Output Settings:',\n ` • Storage: ${userConfig.storage ? `custom(${userConfig.storage.name})` : userConfig.output?.write === false ? 'disabled' : 'filesystem (default)'}`,\n ` • Formatter: ${userConfig.output?.format || 'none'}`,\n ` • Linter: ${userConfig.output?.lint || 'none'}`,\n 'Environment:',\n Object.entries(diagnosticInfo)\n .map(([key, value]) => ` • ${key}: ${value}`)\n .join('\\n'),\n ],\n })\n\n try {\n if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {\n await exists(userConfig.input.path)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Input file validated: ${userConfig.input.path}`],\n })\n }\n } catch (caughtError) {\n if (isInputPath(userConfig)) {\n const error = caughtError as Error\n\n throw new Error(\n `Cannot read file/URL defined in \\`input.path\\` or set with \\`kubb generate PATH\\` in the CLI of your Kubb config ${userConfig.input.path}`,\n {\n cause: error,\n },\n )\n }\n }\n\n if (!userConfig.adapter) {\n throw new Error('Adapter should be defined')\n }\n\n const config: Config = {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n adapter: userConfig.adapter,\n output: {\n write: true,\n extension: DEFAULT_EXTENSION,\n defaultBanner: DEFAULT_BANNER,\n ...userConfig.output,\n },\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: userConfig.plugins as unknown as Config['plugins'],\n }\n\n const storage: Storage | null = config.output.write === false ? null : (config.storage ?? fsStorage())\n\n if (config.output.clean) {\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],\n })\n await storage?.clear(resolve(config.root, config.output.path))\n }\n\n const driver = new PluginDriver(config, {\n hooks,\n })\n\n // Register middleware hooks after all plugin hooks are registered.\n // Because AsyncEventEmitter calls listeners in registration order,\n // middleware hooks for any event fire after all plugin hooks for that event.\n function registerMiddlewareHook<K extends keyof KubbHooks & string>(event: K, middlewareHooks: Middleware['hooks']) {\n const handler = middlewareHooks[event]\n if (handler) {\n hooks.on(event, handler)\n }\n }\n\n for (const middleware of config.middleware ?? []) {\n for (const event of Object.keys(middleware.hooks) as Array<keyof KubbHooks & string>) {\n registerMiddlewareHook(event, middleware.hooks)\n }\n }\n\n const adapter = config.adapter\n if (!adapter) {\n throw new Error('No adapter configured. Please provide an adapter in your kubb.config.ts.')\n }\n const source = inputToAdapterSource(config)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Running adapter: ${adapter.name}`],\n })\n\n driver.adapter = adapter\n driver.inputNode = await adapter.parse(source)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${adapter.name}' resolved InputNode`,\n ` • Schemas: ${driver.inputNode.schemas.length}`,\n ` • Operations: ${driver.inputNode.operations.length}`,\n ],\n })\n\n return {\n config,\n hooks,\n driver,\n sources,\n storage,\n }\n}\n\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n */\nasync function runPluginAstHooks(plugin: NormalizedPlugin, context: GeneratorContext): Promise<void> {\n const { adapter, inputNode, resolver, driver } = context\n const { exclude, include, override } = plugin.options\n\n if (!adapter || !inputNode) {\n throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. pluginOas()) before this plugin in your Kubb config.`)\n }\n\n function resolveRenderer(gen: Generator): RendererFactory | undefined {\n return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)\n }\n\n const generators = plugin.generators ?? []\n const collectedOperations: Array<OperationNode> = []\n\n const generatorContext = {\n ...context,\n resolver: driver.getResolver(plugin.name),\n }\n\n await walk(inputNode, {\n depth: 'shallow',\n async schema(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, {\n options: plugin.options,\n exclude,\n include,\n override,\n })\n if (options === null) return\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)\n },\n async operation(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, {\n options: plugin.options,\n exclude,\n include,\n override,\n })\n if (options !== null) {\n collectedOperations.push(transformedNode)\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)\n }\n },\n })\n\n if (collectedOperations.length > 0) {\n const ctx = { ...generatorContext, options: plugin.options }\n\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations(collectedOperations, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)\n }\n}\n\nasync function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {\n const { driver, hooks, sources, storage } = setupResult\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\n await driver.emitSetupHooks()\n\n if (driver.adapter && driver.inputNode) {\n await hooks.emit('kubb:build:start', {\n config,\n adapter: driver.adapter,\n inputNode: driver.inputNode,\n getPlugin: driver.getPlugin.bind(driver),\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n }\n\n for (const plugin of driver.plugins.values()) {\n const context = driver.getContext(plugin)\n const hrStart = process.hrtime()\n\n try {\n const timestamp = new Date()\n\n await hooks.emit('kubb:plugin:start', { plugin })\n\n await hooks.emit('kubb:debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {\n await runPluginAstHooks(plugin, context)\n }\n\n const duration = getElapsedMs(hrStart)\n pluginTimings.set(plugin.name, duration)\n\n await hooks.emit('kubb:plugin:end', {\n plugin,\n duration,\n success: true,\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Plugin started successfully (${formatMs(duration)})`],\n })\n } catch (caughtError) {\n const error = caughtError as Error\n const errorTimestamp = new Date()\n const duration = getElapsedMs(hrStart)\n\n await hooks.emit('kubb:plugin:end', {\n plugin,\n duration,\n success: false,\n error,\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n await hooks.emit('kubb:debug', {\n date: errorTimestamp,\n logs: [\n '✗ Plugin start failed',\n ` • Plugin Name: ${plugin.name}`,\n ` • Error: ${error.constructor.name} - ${error.message}`,\n ' • Stack Trace:',\n error.stack || 'No stack trace available',\n ],\n })\n\n failedPlugins.add({ plugin, error })\n }\n }\n\n await hooks.emit('kubb:plugins:end', {\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n const files = driver.fileManager.files\n\n const parsersMap = new Map<FileNode['extname'], Parser>()\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const extname of parser.extNames) {\n parsersMap.set(extname, parser)\n }\n }\n }\n\n const fileProcessor = new FileProcessor()\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n\n await fileProcessor.run(files, {\n parsers: parsersMap,\n extension: config.output.extension,\n onStart: async (processingFiles) => {\n await hooks.emit('kubb:files:processing:start', { files: processingFiles })\n },\n onUpdate: async ({ file, source, processed, total, percentage }) => {\n await hooks.emit('kubb:file:processing:update', {\n file,\n source,\n processed,\n total,\n percentage,\n config,\n })\n if (source) {\n await storage?.setItem(file.path, source)\n sources.set(file.path, source)\n }\n },\n onEnd: async (processedFiles) => {\n await hooks.emit('kubb:files:processing:end', { files: processedFiles })\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${processedFiles.length} files`],\n })\n },\n })\n\n await hooks.emit('kubb:build:end', {\n files,\n config,\n outputDir: resolve(config.root, config.output.path),\n })\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n } finally {\n driver.dispose()\n }\n}\n\nasync function build(setupResult: SetupResult): Promise<BuildOutput> {\n const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)\n\n if (error) {\n throw error\n }\n\n if (failedPlugins.size > 0) {\n const errors = [...failedPlugins].map(({ error }) => error)\n\n throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })\n }\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n if (Array.isArray(config.input)) {\n return {\n type: 'paths',\n paths: config.input.map((i) => (new URLPath(i.path).isURL ? i.path : resolve(config.root, i.path))),\n }\n }\n\n if ('data' in config.input) {\n return { type: 'data', data: config.input.data }\n }\n\n if (new URLPath(config.input.path).isURL) {\n return { type: 'path', path: config.input.path }\n }\n\n const resolved = resolve(config.root, config.input.path)\n return { type: 'path', path: resolved }\n}\n\ntype CreateKubbOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Creates a Kubb instance bound to a single config entry.\n *\n * Accepts a user-facing config shape and resolves it to a full {@link Config} during\n * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)\n * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before\n * calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n *\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n *\n * const { files, failedPlugins } = await kubb.safeBuild()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n let setupResult: SetupResult | undefined\n\n const instance: Kubb = {\n get hooks() {\n return hooks\n },\n get sources() {\n return setupResult?.sources ?? new Map()\n },\n get driver() {\n return setupResult?.driver\n },\n get config() {\n return setupResult?.config\n },\n async setup() {\n setupResult = await setup(userConfig, { hooks })\n },\n async build() {\n if (!setupResult) {\n await instance.setup()\n }\n return build(setupResult!)\n },\n async safeBuild() {\n if (!setupResult) {\n await instance.setup()\n }\n return safeBuild(setupResult!)\n },\n }\n\n return instance\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * The generic `TElement` is the type of the element the renderer accepts —\n * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for\n * your own renderer. Defaults to `unknown` so that generators which do not\n * care about the element type continue to work without specifying it.\n *\n * This allows core to drive rendering without a hard dependency on\n * `@kubb/renderer-jsx` or any specific renderer implementation.\n */\nexport type Renderer<TElement = unknown> = {\n render(element: TElement): Promise<void>\n unmount(error?: Error | number | null): void\n readonly files: Array<FileNode>\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Creates a renderer factory for use in generator definitions.\n *\n * Wrap your renderer factory function with this helper to register it as the\n * renderer for a generator. Core will call this factory once per render cycle\n * to obtain a fresh renderer instance.\n *\n * @example\n * ```ts\n * // packages/renderer-jsx/src/index.ts\n * export const jsxRenderer = createRenderer(() => {\n * const runtime = new Runtime()\n * return {\n * async render(element) { await runtime.render(element) },\n * get files() { return runtime.nodes },\n * unmount(error) { runtime.unmount(error) },\n * }\n * })\n *\n * // packages/plugin-zod/src/generators/zodGenerator.tsx\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const zodGenerator = defineGenerator<PluginZod>({\n * name: 'zod',\n * renderer: jsxRenderer,\n * schema(node, options) { return <File ...>...</File> },\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { FileNode, OperationNode, SchemaNode } from '@kubb/ast'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { GeneratorContext, PluginFactoryOptions } from './types.ts'\n\nexport type { GeneratorContext } from './types.ts'\n\n/**\n * A generator is a named object with optional `schema`, `operation`, and `operations`\n * methods. Each method receives the AST node as the first argument and a typed\n * `ctx` object as the second, giving access to `ctx.config`, `ctx.resolver`,\n * `ctx.adapter`, `ctx.options`, `ctx.upsertFile`, etc.\n *\n * Generators that return renderer elements (e.g. JSX) must declare a `renderer`\n * factory so that core knows how to process the output without coupling core\n * to any specific renderer package.\n *\n * Return a renderer element, an array of `FileNode`, or `void` to handle file\n * writing manually via `ctx.upsertFile`.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * operation(node, ctx) {\n * const { options } = ctx\n * return <File ...><OperationType node={node} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin\n * declares a `renderer` (overrides the plugin-level fallback).\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * `applyHookResult` handles renderer elements and `File[]` uniformly using\n * the generator's declared `renderer` factory.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { Logger, LoggerOptions, UserLogger } from './types.ts'\n\n/**\n * Wraps a logger definition into a typed {@link Logger}.\n *\n * @example\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context, options) {\n * context.on('kubb:info', (message) => console.log('ℹ', message))\n * context.on('kubb:error', (error) => console.error('✗', error.message))\n * },\n * })\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions>(logger: UserLogger<Options>): Logger<Options> {\n return logger\n}\n","import type { KubbHooks } from './Kubb.ts'\n\n/**\n * A middleware instance produced by calling a factory created with `defineMiddleware`.\n * It declares event handlers under a `hooks` object which are registered on the\n * shared emitter after all plugin hooks, so middleware handlers for any event\n * always fire last.\n */\nexport type Middleware = {\n /**\n * Unique identifier for this middleware.\n */\n name: string\n /**\n * Lifecycle event handlers for this middleware.\n * Any event from the global `KubbHooks` map can be subscribed to here.\n * Handlers are registered after all plugin handlers, so they always fire last.\n */\n hooks: {\n [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>\n }\n}\n\n/**\n * Creates a middleware factory using the hook-style (`hooks:`) API.\n *\n * Mirrors `definePlugin`: the factory is called with optional options and returns a\n * fresh `Middleware` instance. Placing per-build state (e.g. accumulators) inside the\n * factory closure ensures each `createKubb` invocation gets its own isolated instance.\n *\n * @example\n * ```ts\n * // Stateless middleware\n * export const logMiddleware = defineMiddleware(() => ({\n * name: 'log-middleware',\n * hooks: {\n * 'kubb:build:end'({ files }) {\n * console.log(`Build complete with ${files.length} files`)\n * },\n * },\n * }))\n *\n * // Middleware with options and per-build state\n * export const myMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {\n * const seen = new Set<string>()\n * return {\n * name: 'my-middleware',\n * hooks: {\n * 'kubb:plugin:end'({ plugin }) {\n * seen.add(`${options.prefix}${plugin.name}`)\n * },\n * },\n * }\n * })\n *\n * // Usage in kubb.config.ts:\n * export default defineConfig({\n * middleware: [logMiddleware(), myMiddleware({ prefix: 'pfx:' })],\n * })\n * ```\n */\nexport function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware {\n return (options) => factory(options ?? ({} as TOptions))\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\nexport type Parser<TMeta extends object = any> = {\n name: string\n /**\n * File extensions this parser handles.\n * Use `undefined` to create a catch-all fallback parser.\n *\n * @example Handled extensions\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Convert a resolved file to a string.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string\n}\n\n/**\n * Defines a parser with type safety.\n *\n * Use this function to create parsers that transform generated files to strings\n * based on their extension.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * const { extractStringsFromNodes } = await import('@kubb/ast')\n * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {\n return parser\n}\n","import type { KubbHooks } from './Kubb.ts'\nimport type { KubbPluginSetupContext, PluginFactoryOptions } from './types.ts'\n\n/**\n * A plugin object produced by `definePlugin`.\n * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property\n * (matching Astro's integration naming convention).\n *\n * @template TFactory - The plugin's `PluginFactoryOptions` type.\n */\nexport type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {\n /**\n * Unique name for the plugin, following the same naming convention as `createPlugin`.\n */\n name: string\n /**\n * Plugins that must be registered before this plugin executes.\n * An error is thrown at startup when any listed dependency is missing.\n */\n dependencies?: Array<string>\n /**\n * Controls the execution order of this plugin relative to others.\n *\n * - `'pre'` — runs before all normal plugins.\n * - `'post'` — runs after all normal plugins.\n * - `undefined` (default) — runs in declaration order among normal plugins.\n *\n * Dependency constraints always take precedence over `enforce`.\n */\n enforce?: 'pre' | 'post'\n /**\n * The options passed by the user when calling the plugin factory.\n */\n options?: TFactory['options']\n /**\n * Lifecycle event handlers for this plugin.\n * Any event from the global `KubbHooks` map can be subscribed to here.\n */\n hooks: {\n [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void>\n } & {\n 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>\n }\n}\n\n/**\n * Returns `true` when `plugin` is a hook-style plugin created with `definePlugin`.\n *\n * Used by `PluginDriver` to distinguish hook-style plugins from legacy `createPlugin` plugins\n * so it can normalize them and register their handlers on the `AsyncEventEmitter`.\n */\nexport function isPlugin(plugin: unknown): plugin is Plugin {\n return typeof plugin === 'object' && plugin !== null && 'hooks' in plugin\n}\n\n/**\n * Creates a plugin factory using the hook-style (`hooks:`) API.\n *\n * The returned factory is called with optional options and produces a `Plugin`\n * that coexists with plugins created via the legacy `createPlugin` API in the same\n * `kubb.config.ts`.\n *\n * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling\n * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.\n *\n * @example\n * ```ts\n * // With PluginFactoryOptions (recommended for real plugins)\n * export const pluginTs = definePlugin<PluginTs>((options) => ({\n * name: 'plugin-ts',\n * hooks: {\n * 'kubb:plugin:setup'(ctx) {\n * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>\n * },\n * },\n * }))\n * ```\n */\nexport function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(\n factory: (options: TFactory['options']) => Plugin<TFactory>,\n): (options?: TFactory['options']) => Plugin<TFactory> {\n return (options) => factory(options ?? ({} as TFactory['options']))\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"x_google_ignoreList":[7,8],"mappings":";;;;;;;;;;;;;;;;;;AASA,IAAa,aAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,SAAiB,SAAkD;AAC7E,QAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;AACxC,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;;;;;;;;;;;;;;AAe1B,SAAgB,QAAQ,OAAuB;AAC7C,QAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;;;;;;;;;;ACZlE,IAAa,oBAAb,MAAoF;;;;;CAKlF,YAAY,cAAc,IAAI;AAC5B,QAAA,QAAc,gBAAgB,YAAY;;CAG5C,WAAW,IAAIC,YAAAA,cAAkB;;;;;;;;;;CAWjC,MAAM,KAAgD,WAAuB,GAAG,WAA+C;EAC7H,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AAEpD,MAAI,UAAU,WAAW,EACvB;AAGF,OAAK,MAAM,YAAY,UACrB,KAAI;AACF,SAAM,SAAS,GAAG,UAAU;WACrB,KAAK;GACZ,IAAI;AACJ,OAAI;AACF,qBAAiB,KAAK,UAAU,UAAU;WACpC;AACN,qBAAiB,OAAO,UAAU;;AAEpC,SAAM,IAAI,MAAM,gCAAgC,UAAU,mBAAmB,kBAAkB,EAAE,OAAO,QAAQ,IAAI,EAAE,CAAC;;;;;;;;;;;CAa7H,GAA8C,WAAuB,SAAmD;AACtH,QAAA,QAAc,GAAG,WAAW,QAAoC;;;;;;;;;;CAWlE,OAAkD,WAAuB,SAAmD;EAC1H,MAAM,WAA+C,GAAG,SAAS;AAC/D,QAAK,IAAI,WAAW,QAAQ;AAC5B,UAAO,QAAQ,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