@kubb/core 4.35.0 → 4.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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","../package.json","../src/utils/diagnostics.ts","../src/build.ts","../src/defineAdapter.ts","../src/defineLogger.ts","../src/definePlugin.ts","../src/PackageManager.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 — useful for catching write failures on unreliable file systems.\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 pluginKey: Plugin['key']\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, pluginKey, options }: GetFileProps<TOptions>): KubbFile.File<{ pluginKey: Plugin['key'] }> {\n const baseName = `${name}${extname}` as const\n const path = this.resolvePath({ baseName, mode, pluginKey, options })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${name}\" and pluginKey [${JSON.stringify(pluginKey)}]`)\n }\n\n return {\n path,\n baseName,\n meta: {\n pluginKey,\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.pluginKey) {\n const paths = this.hookForPluginSync({\n pluginKey: params.pluginKey,\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.pluginKey) {\n const names = this.hookForPluginSync({\n pluginKey: params.pluginKey,\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 pluginKey,\n hookName,\n parameters,\n }: {\n pluginKey: Plugin['key']\n hookName: H\n parameters: PluginParameter<H>\n }): Promise<Array<ReturnType<ParseResult<H>> | null>> {\n const plugins = this.getPluginsByKey(hookName, pluginKey)\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 pluginKey,\n hookName,\n parameters,\n }: {\n pluginKey: Plugin['key']\n hookName: H\n parameters: PluginParameter<H>\n }): Array<ReturnType<ParseResult<H>>> | null {\n const plugins = this.getPluginsByKey(hookName, pluginKey)\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 getPluginByKey(pluginKey: Plugin['key']): Plugin | undefined {\n const plugins = [...this.#plugins]\n const [searchPluginName] = pluginKey\n\n return plugins.find((item) => {\n const [name] = item.key\n\n return name === searchPluginName\n })\n }\n\n getPluginsByKey(hookName: keyof PluginWithLifeCycle, pluginKey: Plugin['key']): Plugin[] {\n const plugins = [...this.plugins]\n const [searchPluginName, searchIdentifier] = pluginKey\n\n const pluginByPluginName = plugins\n .filter((plugin) => hookName in plugin)\n .filter((item) => {\n const [name, identifier] = item.key\n\n const identifierCheck = identifier?.toString() === searchIdentifier?.toString()\n const nameCheck = name === searchPluginName\n\n if (searchIdentifier) {\n return identifierCheck && nameCheck\n }\n\n return nameCheck\n })\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 // Removed noisy debug logs for missing hooks - these are expected behavior, not errors\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 // Emit warning if this is a duplicate plugin (will be removed in v5)\n const usageCount = usedPluginNames[plugin.name]\n if (usageCount && usageCount > 1) {\n this.events.emit(\n 'warn',\n `Multiple instances of plugin \"${plugin.name}\" detected. This behavior is deprecated and will be removed in v5.`,\n `Plugin key: [${plugin.name}, ${usageCount}]`,\n )\n }\n\n return {\n install() {},\n ...plugin,\n key: [plugin.name, usedPluginNames[plugin.name]].filter(Boolean) as [typeof plugin.name, string],\n } as unknown as Plugin\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, resolve } from 'node:path'\nimport { AsyncEventEmitter, clean, exists, formatMs, getElapsedMs, getRelativePath, URLPath, write } 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 type { AdapterSource, Config, 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 ` • Write: ${userConfig.output?.write !== false ? 'enabled' : 'disabled'}`,\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 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 clean(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 if (definedConfig.output.write) {\n await write(file.path, source, { sanity: false })\n }\n\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 ` • File writing: ${definedConfig.output.write ? 'enabled' : '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 Key: [${plugin.key.join(', ')}]`],\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 Key: ${JSON.stringify(plugin.key)}`,\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 pluginKeyMap = new Map<string, Plugin>()\n for (const plugin of pluginManager.plugins) {\n pluginKeyMap.set(JSON.stringify(plugin.key), 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?.pluginKey ? pluginKeyMap.get(JSON.stringify(meta.pluginKey)) : 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 { 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, Plugin } from '../types.ts'\n\nexport type FileMetaBase = {\n pluginKey?: Plugin['key']\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,MAAM,KAAK,WAAW,GAAG,WAAW;EACnC,MAAM,YAAY,MAAA,QAAc,UAAU,UAAU;AACpD,MAAI,UAAU,WAAW,EAAG;AAC5B,QAAM,QAAQ,IAAI,UAAU,IAAI,OAAO,aAAa;AACnD,OAAI;AACH,WAAO,MAAM,SAAS,GAAG,UAAU;YAC3B,KAAK;IACb,IAAI;AACJ,QAAI;AACH,sBAAiB,KAAK,UAAU,UAAU;YACnC;AACP,sBAAiB,OAAO,UAAU;;AAEnC,UAAM,IAAI,MAAM,gCAAgC,UAAU,mBAAmB,kBAAkB,EAAE,OAAO,QAAQ,IAAI,EAAE,CAAC;;IAEvH,CAAC;;;CAGJ,GAAG,WAAW,SAAS;AACtB,QAAA,QAAc,GAAG,WAAW,QAAQ;;;CAGrC,OAAO,WAAW,SAAS;EAC1B,MAAM,WAAW,GAAG,SAAS;AAC5B,QAAK,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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","#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 pluginKey: Plugin['key']\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, pluginKey, options }: GetFileProps<TOptions>): KubbFile.File<{ pluginKey: Plugin['key'] }> {\n const baseName = `${name}${extname}` as const\n const path = this.resolvePath({ baseName, mode, pluginKey, options })\n\n if (!path) {\n throw new Error(`Filepath should be defined for resolvedName \"${name}\" and pluginKey [${JSON.stringify(pluginKey)}]`)\n }\n\n return {\n path,\n baseName,\n meta: {\n pluginKey,\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.pluginKey) {\n const paths = this.hookForPluginSync({\n pluginKey: params.pluginKey,\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.pluginKey) {\n const names = this.hookForPluginSync({\n pluginKey: params.pluginKey,\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 pluginKey,\n hookName,\n parameters,\n }: {\n pluginKey: Plugin['key']\n hookName: H\n parameters: PluginParameter<H>\n }): Promise<Array<ReturnType<ParseResult<H>> | null>> {\n const plugins = this.getPluginsByKey(hookName, pluginKey)\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 pluginKey,\n hookName,\n parameters,\n }: {\n pluginKey: Plugin['key']\n hookName: H\n parameters: PluginParameter<H>\n }): Array<ReturnType<ParseResult<H>>> | null {\n const plugins = this.getPluginsByKey(hookName, pluginKey)\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 getPluginByKey(pluginKey: Plugin['key']): Plugin | undefined {\n const plugins = [...this.#plugins]\n const [searchPluginName] = pluginKey\n\n return plugins.find((item) => {\n const [name] = item.key\n\n return name === searchPluginName\n })\n }\n\n getPluginsByKey(hookName: keyof PluginWithLifeCycle, pluginKey: Plugin['key']): Plugin[] {\n const plugins = [...this.plugins]\n const [searchPluginName, searchIdentifier] = pluginKey\n\n const pluginByPluginName = plugins\n .filter((plugin) => hookName in plugin)\n .filter((item) => {\n const [name, identifier] = item.key\n\n const identifierCheck = identifier?.toString() === searchIdentifier?.toString()\n const nameCheck = name === searchPluginName\n\n if (searchIdentifier) {\n return identifierCheck && nameCheck\n }\n\n return nameCheck\n })\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 // Removed noisy debug logs for missing hooks - these are expected behavior, not errors\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 // Emit warning if this is a duplicate plugin (will be removed in v5)\n const usageCount = usedPluginNames[plugin.name]\n if (usageCount && usageCount > 1) {\n this.events.emit(\n 'warn',\n `Multiple instances of plugin \"${plugin.name}\" detected. This behavior is deprecated and will be removed in v5.`,\n `Plugin key: [${plugin.name}, ${usageCount}]`,\n )\n }\n\n return {\n install() {},\n ...plugin,\n key: [plugin.name, usedPluginNames[plugin.name]].filter(Boolean) as [typeof plugin.name, string],\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 Key: [${plugin.key.join(', ')}]`],\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 Key: ${JSON.stringify(plugin.key)}`,\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 pluginKeyMap = new Map<string, Plugin>()\n for (const plugin of pluginManager.plugins) {\n pluginKeyMap.set(JSON.stringify(plugin.key), 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?.pluginKey ? pluginKeyMap.get(JSON.stringify(meta.pluginKey)) : 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, Plugin } from '../types.ts'\n\nexport type FileMetaBase = {\n pluginKey?: Plugin['key']\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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