@kubb/core 5.0.0-alpha.2 → 5.0.0-alpha.21

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 (55) hide show
  1. package/dist/{types-B7eZvqwD.d.ts → PluginDriver-CEQPafXV.d.ts} +687 -298
  2. package/dist/hooks.cjs +15 -9
  3. package/dist/hooks.cjs.map +1 -1
  4. package/dist/hooks.d.ts +11 -5
  5. package/dist/hooks.js +16 -10
  6. package/dist/hooks.js.map +1 -1
  7. package/dist/index.cjs +1131 -536
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +674 -89
  10. package/dist/index.js +1114 -532
  11. package/dist/index.js.map +1 -1
  12. package/package.json +6 -6
  13. package/src/Kubb.ts +37 -55
  14. package/src/{PluginManager.ts → PluginDriver.ts} +51 -40
  15. package/src/build.ts +74 -29
  16. package/src/config.ts +9 -8
  17. package/src/constants.ts +44 -1
  18. package/src/createAdapter.ts +25 -0
  19. package/src/createPlugin.ts +28 -0
  20. package/src/createStorage.ts +58 -0
  21. package/src/defineBuilder.ts +26 -0
  22. package/src/defineGenerator.ts +137 -0
  23. package/src/defineLogger.ts +13 -3
  24. package/src/definePreset.ts +27 -0
  25. package/src/definePresets.ts +16 -0
  26. package/src/defineResolver.ts +448 -0
  27. package/src/hooks/index.ts +1 -1
  28. package/src/hooks/useDriver.ts +8 -0
  29. package/src/hooks/useMode.ts +5 -2
  30. package/src/hooks/usePlugin.ts +5 -2
  31. package/src/index.ts +21 -6
  32. package/src/renderNode.tsx +105 -0
  33. package/src/storages/fsStorage.ts +2 -2
  34. package/src/storages/memoryStorage.ts +2 -2
  35. package/src/types.ts +342 -42
  36. package/src/utils/FunctionParams.ts +2 -2
  37. package/src/utils/TreeNode.ts +24 -1
  38. package/src/utils/diagnostics.ts +4 -1
  39. package/src/utils/executeStrategies.ts +23 -10
  40. package/src/utils/formatters.ts +10 -21
  41. package/src/utils/getBarrelFiles.ts +79 -9
  42. package/src/utils/getConfigs.ts +8 -22
  43. package/src/utils/getPreset.ts +52 -0
  44. package/src/utils/linters.ts +23 -3
  45. package/src/utils/mergeResolvers.ts +8 -0
  46. package/src/utils/packageJSON.ts +76 -0
  47. package/src/BarrelManager.ts +0 -74
  48. package/src/PackageManager.ts +0 -180
  49. package/src/PromiseManager.ts +0 -40
  50. package/src/defineAdapter.ts +0 -22
  51. package/src/definePlugin.ts +0 -12
  52. package/src/defineStorage.ts +0 -56
  53. package/src/errors.ts +0 -1
  54. package/src/hooks/usePluginManager.ts +0 -8
  55. package/src/utils/getPlugins.ts +0 -23
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#emitter","#options","#transformParam","#eachParam","#head","#tail","#size","#options","#plugins","#usedPluginNames","#promiseManager","#parse","#studioIsOpen","openInStudioFn","#getSortedPlugins","#execute","#executeSync","#emitProcessingEnd","#cache","#cwd","#match","#items","#orderItems","#addParams","#cachedLeaves"],"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/PromiseManager.ts","../src/PluginManager.ts","../src/defineStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/build.ts","../src/defineAdapter.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/BarrelManager.ts","../src/utils/getBarrelFiles.ts","../src/utils/getPlugins.ts","../src/utils/getConfigs.ts","../src/utils/linters.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 type { Strategy, StrategySwitch } from './utils/executeStrategies.ts'\nimport { hookFirst, hookParallel, hookSeq } from './utils/executeStrategies.ts'\n\ntype PromiseFunc<T = unknown, T2 = never> = () => T2 extends never ? Promise<T> : Promise<T> | T2\n\ntype Options<TState = unknown> = {\n nullCheck?: (state: TState) => boolean\n}\n\nexport class PromiseManager<TState = unknown> {\n #options: Options<TState> = {}\n\n constructor(options: Options<TState> = {}) {\n this.#options = options\n }\n\n run<TInput extends Array<PromiseFunc<TValue, null>>, TValue, TStrategy extends Strategy, TOutput = StrategySwitch<TStrategy, TInput, TValue>>(\n strategy: TStrategy,\n promises: TInput,\n { concurrency = Number.POSITIVE_INFINITY }: { concurrency?: number } = {},\n ): TOutput {\n if (strategy === 'seq') {\n return hookSeq<TInput, TValue, TOutput>(promises)\n }\n\n if (strategy === 'first') {\n return hookFirst<TInput, TValue, TOutput>(promises, this.#options.nullCheck as ((state: unknown) => boolean) | undefined)\n }\n\n if (strategy === 'parallel') {\n return hookParallel<TInput, TValue, TOutput>(promises, concurrency)\n }\n\n throw new Error(`${strategy} not implemented`)\n }\n}\n\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\n}\n","import path from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { setUniqueName, transformReservedWord } from '@internals/utils'\nimport type { RootNode } from '@kubb/ast/types'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport type { Fabric } from '@kubb/react-fabric'\nimport { CORE_PLUGIN_NAME, DEFAULT_STUDIO_URL } from './constants.ts'\nimport { openInStudio as openInStudioFn } from './devtools.ts'\nimport { ValidationPluginError } from './errors.ts'\nimport { isPromiseRejectedResult, PromiseManager } from './PromiseManager.ts'\nimport type {\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'\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: Fabric\n events: AsyncEventEmitter<KubbEvents>\n /**\n * @default Number.POSITIVE_INFINITY\n */\n concurrency?: number\n}\n\ntype GetFileProps<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 path.extname(fileOrFolder) ? 'single' : 'split'\n}\n\nexport class PluginManager {\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 #studioIsOpen = false\n\n readonly #plugins = new Set<Plugin>()\n readonly #usedPluginNames: Record<string, number> = {}\n readonly #promiseManager\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n this.#promiseManager = new PromiseManager({\n nullCheck: (state: SafeParseResult<'resolveName'> | null) => !!state?.result,\n })\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 pluginManager = this\n\n const baseContext = {\n fabric: this.options.fabric,\n config: this.config,\n plugin,\n events: this.options.events,\n pluginManager: this,\n mode: getMode(path.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 pluginManager.rootNode\n },\n openInStudio(options?: DevtoolsOptions) {\n if (typeof pluginManager.config.devtools !== 'object') {\n throw new Error('Devtools must be an object')\n }\n\n if (!pluginManager.rootNode) {\n throw new Error('RootNode is not defined, make sure you have set the parser in kubb.config.ts')\n }\n\n if (pluginManager.#studioIsOpen) {\n return\n }\n\n pluginManager.#studioIsOpen = true\n\n const studioUrl = pluginManager.config.devtools?.studioUrl ?? DEFAULT_STUDIO_URL\n\n return openInStudioFn(pluginManager.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 }: GetFileProps<TOptions>): KubbFile.File<{ pluginName: string }> {\n const baseName = `${name}${extname}` as const\n const path = this.resolvePath({ baseName, mode, pluginName, options })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${name}\" and pluginName \"${pluginName}\"`)\n }\n\n return {\n path,\n 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 = path.resolve(this.config.root, this.config.output.path)\n const defaultPath = path.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 this.#promiseManager.run('first', promises)\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 this.#promiseManager.run('parallel', promises, {\n concurrency: this.options.concurrency,\n })\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 this.#promiseManager.run('seq', 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 const missingPlugins = plugin.pre.filter((pluginName) => !plugins.find((pluginToFind) => pluginToFind.name === pluginName))\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 { KubbFile } from '@kubb/fabric-core/types'\nimport type { Fabric } from '@kubb/react-fabric'\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 { PluginManager } from './PluginManager.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: Fabric\n files: Array<KubbFile.ResolvedFile>\n pluginManager: PluginManager\n pluginTimings: Map<string, number>\n error?: Error\n sources: Map<KubbFile.Path, string>\n}\n\ntype SetupResult = {\n events: AsyncEventEmitter<KubbEvents>\n fabric: Fabric\n pluginManager: PluginManager\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 pluginManager = new PluginManager(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 pluginManager.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: ${pluginManager.rootNode.schemas.length}`,\n ` • Operations: ${pluginManager.rootNode.operations.length}`,\n ],\n })\n }\n\n return {\n events,\n fabric,\n pluginManager,\n sources,\n }\n}\n\nexport async function build(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, files, pluginManager, 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 pluginManager,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\nexport async function safeBuild(options: BuildOptions, overrides?: SetupResult): Promise<BuildOutput> {\n const { fabric, pluginManager, 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 = pluginManager.config\n\n try {\n for (const plugin of pluginManager.plugins) {\n const context = pluginManager.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, pluginManager }),\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 pluginManager,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n fabric,\n files: [],\n pluginManager,\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 pluginManager: PluginManager\n}\n\nfunction buildBarrelExports({ barrelFiles, rootDir, existingExports, config, pluginManager }: BuildBarrelExportsParams): KubbFile.Export[] {\n const pluginNameMap = new Map<string, Plugin>()\n for (const plugin of pluginManager.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 { 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 '../PluginManager.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'\n\nimport type { FileMetaBase } from './utils/getBarrelFiles.ts'\nimport { TreeNode } from './utils/TreeNode.ts'\n\nexport class BarrelManager {\n getFiles({ files: generatedFiles, root }: { files: KubbFile.File[]; root?: string; meta?: FileMetaBase | undefined }): Array<KubbFile.File> {\n const cachedFiles = new Map<KubbFile.Path, KubbFile.File>()\n\n TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {\n if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {\n return\n }\n\n const barrelFile: KubbFile.File = {\n path: join(treeNode.parent?.data.path, 'index.ts') as KubbFile.Path,\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}\n","import { join } from 'node:path'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport { BarrelManager } from '../BarrelManager.ts'\nimport type { BarrelType } from '../types.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 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<KubbFile.File[]> {\n if (!type || type === 'propagate') {\n return []\n }\n\n const barrelManager = new BarrelManager()\n\n const pathToBuildFrom = join(root, output.path)\n\n if (trimExtName(pathToBuildFrom).endsWith('index')) {\n return []\n }\n\n const barrelFiles = barrelManager.getFiles({\n files,\n root: pathToBuildFrom,\n meta,\n })\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"],"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,IAAI,cAAc;;;;;CAK7B,MA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AS,gBAAgB,SAAyC;AAChE,QAAO,mBAAmB,UAAU,CAAC,MAAM,QAAQ,QAAQ;;AAG7D,SAAgB,WAAW,SAAmE;AAC5F,KAAI,gBAAgB,QAAQ,CAC1B,OAAM,IAAI,MAAM,uGAAuG;AAGzH,KAAI,cAAc,QAAQ,CACxB,OAAM,IAAI,MAAM,qGAAqG;AAGvH,QAAO,QAAQ,QAAQ,QAAQ;;;;;;;ACdjC,eAAsB,WAAW,QAAkC,MAA0C;CAI3G,IAAI,cAAc,OAFhB,OAAO,WAAW,aAAa,QAAQ,QAAQ,OAAO,KAAmB,CAAC,GAAG,QAAQ,QAAQ,OAAO;AAItG,KAAI,CAAC,MAAM,QAAQ,YAAY,CAC7B,eAAc,CAAC,YAAY;CAG7B,MAAM,UAAyB,EAAE;AAEjC,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,UAAU,KAAK,UAAU,MAAM,WAAW,KAAK,QAAQ,GAAG,KAAA;AAEhE,UAAQ,KAAK;GACX,GAAG;GACH;GACD,CAAW;;AAGd,QAAO;;;;ACvBT,eAAe,kBAAkB,QAAkC;AACjE,KAAI;AACF,QAAM,EAAE,QAAQ,CAAC,YAAY,EAAE,EAAE,aAAa,EAAE,OAAO,UAAU,EAAE,CAAC;AACpE,SAAO;SACD;AACN,SAAO;;;AAIX,eAAsB,eAA4C;AAGhE,MAAK,MAAM,UAFmB;EAAC;EAAS;EAAU;EAAS,CAGzD,KAAI,MAAM,kBAAkB,OAAO,CACjC,QAAO"}
1
+ {"version":3,"file":"index.js","names":["#emitter","NodeEventEmitter","#options","#transformParam","#eachParam","#head","#tail","#size","#plugins","#usedPluginNames","#parse","#studioIsOpen","openInStudioFn","#getSortedPlugins","#execute","#executeSync","#emitProcessingEnd","#items","#orderItems","#addParams","#cachedLeaves"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/names.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../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/createStorage.ts","../src/storages/fsStorage.ts","../package.json","../src/utils/diagnostics.ts","../src/build.ts","../src/createAdapter.ts","../src/createPlugin.ts","../src/defineBuilder.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/definePreset.ts","../src/definePresets.ts","../src/defineResolver.ts","../src/renderNode.tsx","../src/storages/memoryStorage.ts","../src/utils/FunctionParams.ts","../src/utils/formatters.ts","../src/utils/TreeNode.ts","../src/utils/getBarrelFiles.ts","../src/utils/getConfigs.ts","../src/utils/mergeResolvers.ts","../src/utils/getPreset.ts","../src/utils/linters.ts","../src/utils/packageJSON.ts"],"sourcesContent":["/** Thrown when a plugin's configuration or input fails validation.\n *\n * @example\n * ```ts\n * throw new ValidationPluginError('Invalid config: \"output.path\" is required')\n * ```\n */\nexport class ValidationPluginError extends Error {}\n\n/**\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 in parallel.\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 await Promise.all(\n listeners.map(async (listener) => {\n try {\n return 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 /**\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 * 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","type Options = {\n /**\n * When `true`, dot-separated segments are split on `.` and joined with `/` after casing.\n */\n isFile?: boolean\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\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: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\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 *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\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 */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\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 */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\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 { readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, posix, resolve } from 'node:path'\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 * 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 */\nexport function getUniqueName(originalName: string, data: Record<string, number>): string {\n let used = data[originalName] || 0\n if (used) {\n data[originalName] = ++used\n originalName += used\n }\n data[originalName] = 1\n return originalName\n}\n\n/**\n * Registers `originalName` in `data` without altering the returned name.\n * Use when you need to track usage frequency but always emit the original identifier.\n *\n * @example\n * ```ts\n * const seen: Record<string, number> = {}\n * setUniqueName('Foo', seen) // 'Foo' (seen = { Foo: 1 })\n * setUniqueName('Foo', seen) // 'Foo' (seen = { Foo: 2 })\n * ```\n */\nexport function setUniqueName(originalName: string, data: Record<string, number>): string {\n let used = data[originalName] || 0\n if (used) {\n data[originalName] = ++used\n return originalName\n }\n data[originalName] = 1\n return originalName\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\n/** Returns `true` when `result` is a fulfilled `Promise.allSettled` result.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseFulfilledResult).map((r) => r.value)\n * ```\n */\nexport function isPromiseFulfilledResult<T = unknown>(result: PromiseSettledResult<unknown>): result is PromiseFulfilledResult<T> {\n return result.status === 'fulfilled'\n}\n\n/** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.\n *\n * @example\n * ```ts\n * const results = await Promise.allSettled([p1, p2])\n * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)\n * ```\n */\nexport function isPromiseRejectedResult<T>(result: PromiseSettledResult<unknown>): result is Omit<PromiseRejectedResult, 'reason'> & { reason: T } {\n return result.status === 'rejected'\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({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): 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 { 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 /**\n * Path to `kubb.config.js`.\n */\n config?: string\n /**\n * Enable watch mode for input files.\n */\n watch?: boolean\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\n/**\n * All accepted forms of a Kubb configuration.\n */\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\n/**\n * Base URL for the Kubb Studio web app.\n */\nexport const DEFAULT_STUDIO_URL = 'https://studio.kubb.dev' as const\n\n/**\n * Internal plugin name used to identify the core Kubb runtime.\n */\nexport const CORE_PLUGIN_NAME = 'core' as const\n\n/**\n * Maximum number of event-emitter listeners before Node.js emits a warning.\n */\nexport const DEFAULT_MAX_LISTENERS = 100\n\n/**\n * Default number of plugins that may run concurrently during a build.\n */\nexport const DEFAULT_CONCURRENCY = 15\n\n/**\n * File name used for generated barrel (index) files.\n */\nexport const BARREL_FILENAME = 'index.ts' as const\n\n/**\n * Default banner style written at the top of every generated file.\n */\nexport const DEFAULT_BANNER = 'simple' as const\n\n/**\n * Default file-extension mapping used when no explicit mapping is configured.\n */\nexport const DEFAULT_EXTENSION: Record<KubbFile.Extname, KubbFile.Extname | ''> = { '.ts': '.ts' }\n\n/**\n * Characters recognized as path separators on both POSIX and Windows.\n */\nexport const PATH_SEPARATORS = new Set(['/', '\\\\'] as const)\n\n/**\n * Numeric log-level thresholds used internally to compare verbosity.\n *\n * Higher numbers are more verbose.\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\n/**\n * CLI command descriptors for each supported linter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the linter is not found.\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\n/**\n * CLI command descriptors for each supported code formatter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the formatter is not found.\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 * Runs promise functions in sequence, threading each result into the next call.\n *\n * - Each function receives the accumulated state from the previous call.\n * - Skips functions that return a falsy value (acts as a no-op for that step).\n * - Returns an array of all individual results.\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 * Runs promise functions in sequence and returns the first non-null result.\n *\n * - Stops as soon as `nullCheck` passes for a result (default: `!== null`).\n * - Subsequent functions are skipped once a match is found.\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 promise functions concurrently and returns all settled results.\n *\n * - Limits simultaneous executions to `concurrency` (default: unlimited).\n * - Uses `Promise.allSettled` so individual failures do not cancel other tasks.\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\n/**\n * Execution strategy used when dispatching plugin hook calls.\n */\nexport type Strategy = 'seq' | 'first' | 'parallel'\n\ntype StrategyOutputMap<TInput extends Array<PromiseFunc<TValue, null>>, TValue> = {\n first: HookFirstOutput<TInput, TValue>\n seq: SeqOutput<TInput, TValue>\n parallel: HookParallelOutput<TInput, TValue>\n}\n\nexport type StrategySwitch<TStrategy extends Strategy, TInput extends Array<PromiseFunc<TValue, null>>, TValue> = StrategyOutputMap<TInput, TValue>[TStrategy]\n","import { basename, extname, resolve } from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { isPromiseRejectedResult, setUniqueName, transformReservedWord, ValidationPluginError } 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'\n\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","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 * 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 = createStorage(() => ({\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 * 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 { dirname, relative, resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError, 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 { PluginDriver } from './PluginDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { AdapterSource, Config, KubbEvents, Output, Plugin, Storage, 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\n/**\n * Full output produced by a successful or failed build.\n */\ntype BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n fabric: FabricType\n files: Array<KubbFile.ResolvedFile>\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<KubbFile.Path, string>\n}\n\n/**\n * Intermediate result returned by {@link setup} and accepted by {@link safeBuild}.\n */\ntype SetupResult = {\n events: AsyncEventEmitter<KubbEvents>\n fabric: FabricType\n driver: PluginDriver\n sources: Map<KubbFile.Path, string>\n}\n\n/**\n * Initializes all Kubb infrastructure for a build without executing any plugins.\n *\n * - Validates the input path (when applicable).\n * - Applies config defaults (`root`, `output.*`, `devtools`).\n * - Creates the Fabric instance and wires storage, format, and lint hooks.\n * - Runs the adapter (if configured) to produce the universal `RootNode`.\n *\n * Pass the returned {@link SetupResult} directly to {@link safeBuild} or {@link build}\n * via the `overrides` argument to reuse the same infrastructure across multiple runs.\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: Storage | 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\n/**\n * Runs a full Kubb build and throws on any error or plugin failure.\n *\n * Internally delegates to {@link safeBuild} and rethrows collected errors.\n * Pass an existing {@link SetupResult} via `overrides` to skip the setup phase.\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\n/**\n * Runs a full Kubb build and captures errors instead of throwing.\n *\n * - Installs each plugin in order, recording failures in `failedPlugins`.\n * - Generates the root barrel file when `output.barrelType` is set.\n * - Writes all files through Fabric.\n *\n * Returns a {@link BuildOutput} even on failure — inspect `error` and\n * `failedPlugins` to determine whether the build succeeded.\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) => (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","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","import type { PluginFactoryOptions, UserPluginWithLifeCycle } from './types.ts'\n\n/**\n * Builder type for a {@link UserPluginWithLifeCycle} — takes options and returns the plugin instance.\n */\ntype PluginBuilder<T extends PluginFactoryOptions = PluginFactoryOptions> = (options: T['options']) => UserPluginWithLifeCycle<T>\n\n/**\n * Creates a plugin factory. Call the returned function with optional options to get the plugin instance.\n *\n * @example\n * export const myPlugin = createPlugin<MyPlugin>((options) => {\n * return {\n * name: 'my-plugin',\n * options,\n * resolvePath(baseName) { ... },\n * resolveName(name, type) { ... },\n * }\n * })\n *\n * // instantiate\n * const plugin = myPlugin({ output: { path: 'src/gen' } })\n */\nexport function createPlugin<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 type { PluginFactoryOptions } from './types.ts'\n\n/**\n * Builder type for the plugin-specific builder fields.\n * `name` is required; all other methods are defined by the concrete plugin builder type.\n */\ntype BuilderBuilder<T extends PluginFactoryOptions> = () => T['builder'] & ThisType<T['builder']>\n\n/**\n * Defines a builder for a plugin — a named collection of schema-building helpers that\n * can be exported alongside the plugin and imported by other plugins or generators.\n *\n * @example\n * export const builder = defineBuilder<PluginTs>(() => ({\n * name: 'default',\n * buildParamsSchema({ params, node, resolver }) {\n * return createSchema({ type: 'object', properties: [] })\n * },\n * buildDataSchemaNode({ node, resolver }) {\n * return createSchema({ type: 'object', properties: [] })\n * },\n * }))\n */\nexport function defineBuilder<T extends PluginFactoryOptions>(build: BuilderBuilder<T>): T['builder'] {\n return build() as T['builder']\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/**\n * Props for the `operations` lifecycle — receives all operation nodes at once.\n */\nexport type OperationsV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n plugin: Plugin<TPlugin>\n adapter: Adapter\n options: Plugin<TPlugin>['options']\n nodes: Array<OperationNode>\n}\n\n/**\n * Props for the `operation` lifecycle — receives a single operation node.\n */\nexport type OperationV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n plugin: Plugin<TPlugin>\n options: Plugin<TPlugin>['options']\n node: OperationNode\n}\n\n/**\n * Props for the `schema` lifecycle — receives a single schema node.\n */\nexport type SchemaV2Props<TPlugin extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n adapter: Adapter\n plugin: Plugin<TPlugin>\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\n/**\n * Defines a generator with no-op defaults for any omitted lifecycle methods.\n * Works for both `core` (async file output) and `react` (JSX component) generators.\n *\n * @example\n * // react generator\n * export const typeGenerator = defineGenerator<PluginTs>({\n * name: 'typescript',\n * type: 'react',\n * Operation({ node, options }) { return <File>...</File> },\n * Schema({ node, options }) { return <File>...</File> },\n * })\n *\n * @example\n * // core generator\n * export const myGenerator = defineGenerator<MyPlugin>({\n * name: 'my-generator',\n * type: 'core',\n * async operation({ node, options }) { return [{ path: '...', content: '...' }] },\n * })\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>\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\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('info', (message) => console.log('ℹ', message))\n * context.on('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 { Visitor } from '@kubb/ast/types'\nimport type { Generator, Preset, Resolver } from './types.ts'\n\n/**\n * Creates a typed preset object that bundles a name, resolvers, optional\n * transformers, and optional generators — the building block for composable plugin presets.\n *\n * @example\n * import { definePreset } from '@kubb/core'\n * import { resolverTsLegacy } from '@kubb/plugin-ts'\n *\n * export const myPreset = definePreset('myPreset', { resolvers: [resolverTsLegacy] })\n *\n * @example\n * // With custom transformers\n * export const myPreset = definePreset('myPreset', { resolvers: [resolverTsLegacy], transformers: [myTransformer] })\n *\n * @example\n * // With generators\n * export const myPreset = definePreset('myPreset', { resolvers: [resolverTsLegacy], generators: [typeGeneratorLegacy] })\n */\nexport function definePreset<TResolver extends Resolver = Resolver, TName extends string = string>(\n name: TName,\n { resolvers, transformers, generators }: { resolvers: Array<TResolver>; transformers?: Array<Visitor>; generators?: Array<Generator<any>> },\n): Preset<TResolver> & { name: TName } {\n return { name, resolvers, transformers, generators }\n}\n","import type { Preset, Presets, Resolver } from './types.ts'\n\n/**\n * Creates a typed presets registry object — a named collection of {@link Preset} entries.\n *\n * @example\n * import { definePreset, definePresets } from '@kubb/core'\n * import { resolverTsLegacy } from '@kubb/plugin-ts'\n *\n * export const myPresets = definePresets({\n * kubbV4: definePreset('kubbV4', { resolvers: [resolverTsLegacy] }),\n * })\n */\nexport function definePresets<TResolver extends Resolver = Resolver>(presets: Presets<TResolver>): Presets<TResolver> {\n return presets\n}\n","import path from 'node:path'\nimport { camelCase, pascalCase } from '@internals/utils'\nimport { isOperationNode, isSchemaNode } from '@kubb/ast'\nimport type { Node, OperationNode, RootNode, SchemaNode } from '@kubb/ast/types'\nimport type { KubbFile } from '@kubb/fabric-core/types'\nimport { getMode } from './PluginDriver.ts'\nimport type {\n Config,\n PluginFactoryOptions,\n ResolveBannerContext,\n ResolveNameParams,\n ResolveOptionsContext,\n Resolver,\n ResolverContext,\n ResolverFileParams,\n ResolverPathParams,\n} from './types.ts'\n\n/**\n * Builder type for the plugin-specific resolver fields.\n *\n * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`\n * are optional — built-in fallbacks are injected when omitted.\n */\ntype ResolverBuilder<T extends PluginFactoryOptions> = () => Omit<\n T['resolver'],\n 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter' | 'name' | 'pluginName'\n> &\n Partial<Pick<T['resolver'], 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>> & {\n name: string\n pluginName: T['name']\n } & ThisType<T['resolver']>\n\n/**\n * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).\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\n/**\n * Checks if a schema matches a pattern for a given filter type (`schemaName`).\n *\n * Returns `null` when the filter type doesn't apply to schemas.\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 * Default name resolver used by `defineResolver`.\n *\n * - `camelCase` for `function` and `file` types.\n * - `PascalCase` for `type`.\n * - `camelCase` for everything else.\n */\nfunction defaultResolver(name: ResolveNameParams['name'], type: ResolveNameParams['type']): string {\n let resolvedName = camelCase(name)\n\n if (type === 'file' || type === 'function') {\n resolvedName = camelCase(name, {\n isFile: type === 'file',\n })\n }\n\n if (type === 'type') {\n resolvedName = pascalCase(name)\n }\n\n return resolvedName\n}\n\n/**\n * Default option resolver — applies include/exclude filters and merges matching override options.\n *\n * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.\n *\n * @example Include/exclude filtering\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { output: 'types' },\n * exclude: [{ type: 'tag', pattern: 'internal' }],\n * })\n * // → null when node has tag 'internal'\n * ```\n *\n * @example Override merging\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { enumType: 'asConst' },\n * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],\n * })\n * // → { enumType: 'enum' } when operationId matches\n * ```\n */\nexport function defaultResolveOptions<TOptions>(\n node: Node,\n { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>,\n): 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\n/**\n * Default path resolver used by `defineResolver`.\n *\n * - Returns the output directory in `single` mode.\n * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.\n * - Falls back to a flat `output/baseName` path otherwise.\n *\n * A custom `group.name` function overrides the default subdirectory naming.\n * For `tag` groups the default is `${camelCase(tag)}Controller`.\n * For `path` groups the default is the first path segment after `/`.\n *\n * @example Flat output\n * ```ts\n * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })\n * // → '/src/types/petTypes.ts'\n * ```\n *\n * @example Tag-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/petsController/petTypes.ts'\n * ```\n *\n * @example Path-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', path: '/pets/list' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\n *\n * @example Single-file mode\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', pathMode: 'single' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → '/src/types'\n * ```\n */\nexport function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }: ResolverPathParams, { root, output, group }: ResolverContext): KubbFile.Path {\n const mode = pathMode ?? getMode(path.resolve(root, output.path))\n\n if (mode === 'single') {\n return path.resolve(root, output.path) as KubbFile.Path\n }\n\n if (group && (groupPath || tag)) {\n const groupName = group.name\n ? group.name\n : (ctx: { group: string }) => {\n if (group.type === 'path') {\n return `${ctx.group.split('/')[1]}`\n }\n return `${camelCase(ctx.group)}Controller`\n }\n\n return path.resolve(root, output.path, groupName({ group: group.type === 'path' ? groupPath! : tag! }), baseName) as KubbFile.Path\n }\n\n return path.resolve(root, output.path, baseName) as KubbFile.Path\n}\n\n/**\n * Default file resolver used by `defineResolver`.\n *\n * Resolves a `KubbFile.File` by combining name resolution (`resolver.default`) with\n * path resolution (`resolver.resolvePath`). The resolved file always has empty\n * `sources`, `imports`, and `exports` arrays — consumers populate those separately.\n *\n * In `single` mode the name is omitted and the file sits directly in the output directory.\n *\n * @example Resolve a schema file\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'pet', extname: '.ts' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }\n * ```\n *\n * @example Resolve an operation file with tag grouping\n * ```ts\n * const file = defaultResolveFile.call(resolver,\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }\n * ```\n */\nexport function defaultResolveFile(this: Resolver, { name, extname, tag, path: groupPath }: ResolverFileParams, context: ResolverContext): KubbFile.File {\n const pathMode = getMode(path.resolve(context.root, context.output.path))\n const resolvedName = pathMode === 'single' ? '' : this.default(name, 'file')\n const baseName = `${resolvedName}${extname}` as KubbFile.BaseName\n const filePath = this.resolvePath({ baseName, pathMode, tag, path: groupPath }, context)\n\n return {\n path: filePath,\n baseName: path.basename(filePath) as KubbFile.BaseName,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n }\n}\n\n/**\n * Generates the default \"Generated by Kubb\" banner from config and optional node metadata.\n */\nexport function buildDefaultBanner({\n title,\n description,\n version,\n config,\n}: {\n title?: string\n description?: string\n version?: string\n config: Config\n}): string {\n try {\n let source = ''\n if (Array.isArray(config.input)) {\n const first = config.input[0]\n if (first && 'path' in first) {\n source = path.basename(first.path)\n }\n } else if ('path' in config.input) {\n source = path.basename(config.input.path)\n } else if ('data' in config.input) {\n source = 'text content'\n }\n\n let banner = '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n'\n\n if (config.output.defaultBanner === 'simple') {\n banner += '*/\\n'\n return banner\n }\n\n if (source) {\n banner += `* Source: ${source}\\n`\n }\n\n if (title) {\n banner += `* Title: ${title}\\n`\n }\n\n if (description) {\n const formattedDescription = description.replace(/\\n/gm, '\\n* ')\n banner += `* Description: ${formattedDescription}\\n`\n }\n\n if (version) {\n banner += `* OpenAPI spec version: ${version}\\n`\n }\n\n banner += '*/\\n'\n return banner\n } catch (_error) {\n return '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n*/'\n }\n}\n\n/**\n * Default banner resolver — returns the banner string for a generated file.\n *\n * - When `output.banner` is a function and `node` is provided, calls it with the node.\n * - When `output.banner` is a function and `node` is absent, falls back to the default Kubb banner.\n * - When `output.banner` is a string, returns it directly.\n * - When `config.output.defaultBanner` is `false`, returns `undefined`.\n * - Otherwise returns the default \"Generated by Kubb\" banner.\n *\n * @example String banner\n * ```ts\n * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })\n * // → '// my banner'\n * ```\n *\n * @example Function banner with node\n * ```ts\n * defaultResolveBanner(rootNode, { output: { banner: (node) => `// v${node.version}` }, config })\n * // → '// v3.0.0'\n * ```\n *\n * @example Disabled banner\n * ```ts\n * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })\n * // → undefined\n * ```\n */\nexport function defaultResolveBanner(node: RootNode | undefined, { output, config }: ResolveBannerContext): string | undefined {\n if (typeof output?.banner === 'function') {\n return node ? output.banner(node) : buildDefaultBanner({ config })\n }\n if (typeof output?.banner === 'string') {\n return output.banner\n }\n if (config.output.defaultBanner === false) {\n return undefined\n }\n return buildDefaultBanner({ config })\n}\n\n/**\n * Default footer resolver — returns the footer string for a generated file.\n *\n * - When `output.footer` is a function and `node` is provided, calls it with the node.\n * - When `output.footer` is a function and `node` is absent, returns `undefined`.\n * - When `output.footer` is a string, returns it directly.\n * - Otherwise returns `undefined`.\n *\n * @example String footer\n * ```ts\n * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })\n * // → '// end of file'\n * ```\n *\n * @example Function footer with node\n * ```ts\n * defaultResolveFooter(rootNode, { output: { footer: (node) => `// ${node.title}` }, config })\n * // → '// Pet Store'\n * ```\n */\nexport function defaultResolveFooter(node: RootNode | undefined, { output }: ResolveBannerContext): string | undefined {\n if (typeof output?.footer === 'function') {\n return node ? output.footer(node) : undefined\n }\n if (typeof output?.footer === 'string') {\n return output.footer\n }\n return undefined\n}\n\n/**\n * Defines a resolver for a plugin, injecting built-in defaults for name casing,\n * include/exclude/override filtering, path resolution, and file construction.\n *\n * All four defaults can be overridden by providing them in the builder function:\n * - `default` — name casing strategy (camelCase / PascalCase)\n * - `resolveOptions` — include/exclude/override filtering\n * - `resolvePath` — output path computation\n * - `resolveFile` — full `KubbFile.File` construction\n *\n * Methods in the builder have access to `this` (the full resolver object), so they\n * can call other resolver methods without circular imports.\n *\n * @example Basic resolver with naming helpers\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveName(node) {\n * return this.default(node.name, 'function')\n * },\n * resolveTypedName(node) {\n * return this.default(node.name, 'type')\n * },\n * }))\n * ```\n *\n * @example Override resolvePath for a custom output structure\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'custom',\n * resolvePath({ baseName }, { root, output }) {\n * return path.resolve(root, output.path, 'generated', baseName)\n * },\n * }))\n * ```\n *\n * @example Use this.default inside a helper\n * ```ts\n * export const resolver = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveParamName(node, param) {\n * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')\n * },\n * }))\n * ```\n */\nexport function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'] {\n return {\n default: defaultResolver,\n resolveOptions: defaultResolveOptions,\n resolvePath: defaultResolvePath,\n resolveFile: defaultResolveFile,\n resolveBanner: defaultResolveBanner,\n resolveFooter: defaultResolveFooter,\n ...build(),\n } as T['resolver']\n}\n","import type { OperationNode, SchemaNode } from '@kubb/ast/types'\nimport { createReactFabric, Fabric } from '@kubb/react-fabric'\nimport type { Fabric as FabricType } from '@kubb/react-fabric/types'\nimport type { PluginDriver } from './PluginDriver.ts'\nimport type { Adapter, Config, Plugin, PluginFactoryOptions, ReactGeneratorV2 } from './types.ts'\n\ntype BuildOperationsV2Options<TOptions extends PluginFactoryOptions> = {\n config: Config\n fabric: FabricType\n plugin: Plugin<TOptions>\n Component: ReactGeneratorV2<TOptions>['Operations'] | undefined\n adapter: Adapter\n driver: PluginDriver\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Renders a React component for a list of operation nodes (V2 generators).\n */\nexport async function renderOperations<TOptions extends PluginFactoryOptions>(\n nodes: Array<OperationNode>,\n options: BuildOperationsV2Options<TOptions>,\n): Promise<void> {\n const { config, fabric, plugin, Component, driver, adapter } = options\n\n if (!Component) {\n return undefined\n }\n\n const fabricChild = createReactFabric()\n\n await fabricChild.render(\n <Fabric meta={{ plugin, driver }}>\n <Component config={config} plugin={plugin} adapter={adapter} nodes={nodes} options={options.options} />\n </Fabric>,\n )\n\n fabric.context.fileManager.upsert(...fabricChild.files)\n fabricChild.unmount()\n}\n\ntype BuildOperationV2Options<TOptions extends PluginFactoryOptions> = {\n config: Config\n fabric: FabricType\n plugin: Plugin<TOptions>\n Component: ReactGeneratorV2<TOptions>['Operation'] | undefined\n adapter: Adapter\n driver: PluginDriver\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Renders a React component for a single operation node (V2 generators).\n */\nexport async function renderOperation<TOptions extends PluginFactoryOptions>(node: OperationNode, options: BuildOperationV2Options<TOptions>): Promise<void> {\n const { config, fabric, plugin, Component, adapter, driver } = options\n\n if (!Component) {\n return undefined\n }\n\n const fabricChild = createReactFabric()\n\n await fabricChild.render(\n <Fabric meta={{ plugin, driver }}>\n <Component config={config} plugin={plugin} adapter={adapter} node={node} options={options.options} />\n </Fabric>,\n )\n\n fabric.context.fileManager.upsert(...fabricChild.files)\n fabricChild.unmount()\n}\n\ntype BuildSchemaV2Options<TOptions extends PluginFactoryOptions> = {\n config: Config\n fabric: FabricType\n plugin: Plugin<TOptions>\n Component: ReactGeneratorV2<TOptions>['Schema'] | undefined\n adapter: Adapter\n driver: PluginDriver\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Renders a React component for a single schema node (V2 generators).\n */\nexport async function renderSchema<TOptions extends PluginFactoryOptions>(node: SchemaNode, options: BuildSchemaV2Options<TOptions>): Promise<void> {\n const { config, fabric, plugin, Component, adapter, driver } = options\n\n if (!Component) {\n return undefined\n }\n\n const fabricChild = createReactFabric()\n\n await fabricChild.render(\n <Fabric meta={{ plugin, driver }}>\n <Component config={config} plugin={plugin} adapter={adapter} node={node} options={options.options} />\n </Fabric>,\n )\n\n fabric.context.fileManager.upsert(...fabricChild.files)\n\n fabricChild.unmount()\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 { 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 = 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","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 use ast package instead\n */\nexport type FunctionParamsAST = FunctionParamsASTWithoutType | FunctionParamsASTWithType\n\n/**\n * @deprecated use ast package instead\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 * Returns `true` when the given formatter is installed and callable.\n *\n * Availability is detected by running `<formatter> --version` and checking\n * that the process exits without error.\n */\nasync function isFormatterAvailable(formatter: Formatter): Promise<boolean> {\n try {\n await x(formatter, ['--version'], { nodeOptions: { stdio: 'ignore' } })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Detects the first available code formatter on the current system.\n *\n * - Checks in preference order: `biome`, `oxfmt`, `prettier`.\n * - Returns `null` when none are found.\n *\n * @example\n * ```ts\n * const formatter = await detectFormatter()\n * if (formatter) {\n * console.log(`Using ${formatter} for formatting`)\n * }\n * ```\n */\nexport async function detectFormatter(): Promise<Formatter | null> {\n const formatterNames = new Set(['biome', 'oxfmt', 'prettier'] as const)\n\n for (const formatter of formatterNames) {\n if (await isFormatterAvailable(formatter)) {\n return formatter\n }\n }\n\n return null\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\n/**\n * Tree structure used to build per-directory barrel (`index.ts`) files from a\n * flat list of generated {@link KubbFile.File} entries.\n *\n * Each node represents either a directory or a file within the output tree.\n * Use {@link TreeNode.build} to construct a root node from a file list, then\n * traverse with {@link TreeNode.forEach}, {@link TreeNode.leaves}, or the\n * `*Deep` helpers.\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 /**\n * Returns the root ancestor of this node, walking up via `parent` links.\n */\n get root(): TreeNode {\n if (!this.parent) {\n return this\n }\n return this.parent.root\n }\n\n /**\n * Returns all leaf descendants (nodes with no children) of this node.\n *\n * Results are cached after the first traversal.\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 /**\n * Builds a {@link TreeNode} tree from a flat list of files.\n *\n * - Filters to files under `root` (when provided) and skips `.json` files.\n * - Returns `null` when no files match.\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?.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\n/**\n * Generates `index.ts` barrel files for all directories under `root/output.path`.\n *\n * - Returns an empty array when `type` is falsy or `'propagate'`.\n * - Skips generation when the output path itself ends with `index` (already a barrel).\n * - When `type` is `'all'`, strips named exports so every re-export becomes a wildcard (`export * from`).\n * - Attaches `meta` to each barrel file for downstream plugin identification.\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 { CLIOptions, ConfigInput } from '../config.ts'\nimport type { Config, UserConfig } from '../types.ts'\n\n/**\n * Resolves a {@link ConfigInput} into a normalized array of {@link Config} objects.\n *\n * - Awaits the config when it is a `Promise`.\n * - Calls the factory function with `args` when the config is a function.\n * - Wraps a single config object in an array for uniform downstream handling.\n */\nexport async function getConfigs(config: ConfigInput | UserConfig, args: CLIOptions): Promise<Array<Config>> {\n const resolved = await (typeof config === 'function' ? config(args as CLIOptions) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return userConfigs.map((item) => ({ ...item }) as Config)\n}\n","import type { Resolver } from '../types.ts'\n\n/**\n * Merges an array of resolvers into a single resolver. Later entries override earlier ones (last wins).\n */\nexport function mergeResolvers<T extends Resolver>(...resolvers: Array<T>): T {\n return resolvers.reduce<T>((acc, curr) => ({ ...acc, ...curr }), resolvers[0]!)\n}\n","import type { Visitor } from '@kubb/ast/types'\nimport type { CompatibilityPreset, Generator, Preset, Presets, Resolver } from '../types.ts'\nimport { mergeResolvers } from './mergeResolvers.ts'\n\ntype GetPresetParams<TResolver extends Resolver> = {\n preset: CompatibilityPreset\n presets: Presets<TResolver>\n resolvers: Array<TResolver>\n /**\n * User-supplied generators to append after the preset's generators.\n */\n generators: Array<Generator<any>>\n transformers?: Array<Visitor>\n}\n\ntype GetPresetResult<TResolver extends Resolver> = {\n resolver: TResolver\n transformers: Array<Visitor>\n generators: Array<Generator<any>>\n preset: Preset<TResolver> | undefined\n}\n\n/**\n * Resolves a named preset into merged resolvers, transformers, and generators.\n *\n * - Merges the preset's resolvers on top of the first (default)\n * - Merges any additional user-supplied resolvers on top of that to produce the final `resolver`.\n * - Concatenates preset transformers before user-supplied transformers.\n * - Combines preset generators with user-supplied generators; falls back to the `default` preset's generators when neither provides any.\n */\nexport function getPreset<TResolver extends Resolver = Resolver>(params: GetPresetParams<TResolver>): GetPresetResult<TResolver> {\n const { preset: presetName, presets, resolvers, transformers: userTransformers, generators: userGenerators } = params\n const [defaultResolver, ...userResolvers] = resolvers\n const preset = presets[presetName]\n\n const baseResolver = mergeResolvers(defaultResolver!, ...(preset?.resolvers ?? []))\n const resolver = mergeResolvers(baseResolver, ...(userResolvers ?? []))\n const transformers = [...(preset?.transformers ?? []), ...(userTransformers ?? [])]\n\n const presetGenerators = preset?.generators ?? []\n const defaultPresetGenerators = presets['default']?.generators ?? []\n const generators = (presetGenerators.length > 0 || userGenerators.length\n ? [...presetGenerators, ...userGenerators]\n : defaultPresetGenerators) as unknown as Array<Generator<any>>\n\n return {\n resolver,\n transformers,\n generators,\n preset,\n }\n}\n","import { x } from 'tinyexec'\nimport type { linters } from '../constants.ts'\n\ntype Linter = keyof typeof linters\n\n/**\n * Returns `true` when the given linter is installed and callable.\n *\n * Availability is detected by running `<linter> --version` and checking\n * that the process exits without error.\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\n/**\n * Detects the first available linter on the current system.\n *\n * - Checks in preference order: `biome`, `oxlint`, `eslint`.\n * - Returns `null` when none are found.\n *\n * @example\n * ```ts\n * const linter = await detectLinter()\n * if (linter) {\n * console.log(`Using ${linter} for linting`)\n * }\n * ```\n */\nexport async function detectLinter(): Promise<Linter | null> {\n const linterNames = new Set(['biome', 'oxlint', 'eslint'] as const)\n\n for (const linter of linterNames) {\n if (await isLinterAvailable(linter)) {\n return linter\n }\n }\n\n return null\n}\n","import { readSync } from '@internals/utils'\nimport * as pkg from 'empathic/package'\nimport { coerce, satisfies } from 'semver'\n\ntype PackageJSON = {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n}\n\ntype DependencyName = string\ntype DependencyVersion = string\n\nfunction getPackageJSONSync(cwd?: string): PackageJSON | null {\n const pkgPath = pkg.up({ cwd })\n if (!pkgPath) {\n return null\n }\n\n return JSON.parse(readSync(pkgPath)) as PackageJSON\n}\n\nfunction match(packageJSON: PackageJSON, dependency: DependencyName | RegExp): string | null {\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 matched = Object.keys(dependencies).find((dep) => dep.match(dependency))\n\n return matched ? (dependencies[matched] ?? null) : null\n}\n\nfunction getVersionSync(dependency: DependencyName | RegExp, cwd?: string): DependencyVersion | null {\n const packageJSON = getPackageJSONSync(cwd)\n\n return packageJSON ? match(packageJSON, dependency) : null\n}\n\n/**\n * Returns `true` when the nearest `package.json` declares a dependency that\n * satisfies the given semver range.\n *\n * - Searches both `dependencies` and `devDependencies`.\n * - Accepts a string package name or a `RegExp` to match scoped/pattern packages.\n * - Uses `semver.satisfies` for range comparison; returns `false` when the\n * version string cannot be coerced into a valid semver.\n *\n * @example\n * ```ts\n * satisfiesDependency('react', '>=18') // true when react@18.x is installed\n * satisfiesDependency(/^@tanstack\\//, '>=5') // true when any @tanstack/* >=5 is found\n * ```\n */\nexport function satisfiesDependency(dependency: DependencyName | RegExp, version: DependencyVersion, cwd?: string): boolean {\n const packageVersion = getVersionSync(dependency, cwd)\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"],"x_google_ignoreList":[12,13],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,wBAAb,cAA2C,MAAM;;;;;;;;;;AAWjD,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;;;;;;;;;;;;;;;ACrBlE,IAAa,oBAAb,MAAoF;;;;;CAKlF,YAAY,cAAc,IAAI;AAC5B,QAAA,QAAc,gBAAgB,YAAY;;CAG5C,WAAW,IAAIC,cAAkB;;;;;;;;;;CAWjC,MAAM,KAAgD,WAAuB,GAAG,WAA+C;EAC7H,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AAEpD,MAAI,UAAU,WAAW,EACvB;AAGF,QAAM,QAAQ,IACZ,UAAU,IAAI,OAAO,aAAa;AAChC,OAAI;AACF,WAAO,MAAM,SAAS,GAAG,UAAU;YAC5B,KAAK;IACZ,IAAI;AACJ,QAAI;AACF,sBAAiB,KAAK,UAAU,UAAU;YACpC;AACN,sBAAiB,OAAO,UAAU;;AAEpC,UAAM,IAAI,MAAM,gCAAgC,UAAU,mBAAmB,kBAAkB,EAAE,OAAO,QAAQ,IAAI,EAAE,CAAC;;IAEzH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