@kubb/cli 5.0.0-beta.82 → 5.0.0-beta.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/{Telemetry-ugO-B77y.js → Telemetry-Cuzoes9Y.js} +6 -2
  2. package/dist/Telemetry-Cuzoes9Y.js.map +1 -0
  3. package/dist/{Telemetry-jtbchpQE.cjs → Telemetry-CwQYBgsg.cjs} +11 -1
  4. package/dist/Telemetry-CwQYBgsg.cjs.map +1 -0
  5. package/dist/{generate-D5AWn6lH.js → generate-C1bIl1nH.js} +34 -24
  6. package/dist/generate-C1bIl1nH.js.map +1 -0
  7. package/dist/{generate-DfzX98Lx.cjs → generate-Cgmty90l.cjs} +34 -23
  8. package/dist/generate-Cgmty90l.cjs.map +1 -0
  9. package/dist/index.cjs +28 -192
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.js +29 -193
  12. package/dist/index.js.map +1 -1
  13. package/dist/{init-hKT7f8_b.cjs → init-DqgB69HY.cjs} +9 -10
  14. package/dist/init-DqgB69HY.cjs.map +1 -0
  15. package/dist/{init-GU5uRenE.js → init-EnhDxlBB.js} +10 -10
  16. package/dist/init-EnhDxlBB.js.map +1 -0
  17. package/dist/{mcp-B3TSdKiQ.js → mcp-5DDTiwIA.js} +6 -6
  18. package/dist/mcp-5DDTiwIA.js.map +1 -0
  19. package/dist/{mcp-B5ppXTnU.cjs → mcp-DYmjmXQb.cjs} +5 -6
  20. package/dist/mcp-DYmjmXQb.cjs.map +1 -0
  21. package/dist/{package-BBBrKion.cjs → package-B57sF1X0.cjs} +2 -2
  22. package/dist/package-B57sF1X0.cjs.map +1 -0
  23. package/dist/package-CQbxcw7I.js +6 -0
  24. package/dist/package-CQbxcw7I.js.map +1 -0
  25. package/dist/{run-DXEMoDFa.cjs → run-3qq_Q4Tg.cjs} +4 -4
  26. package/dist/run-3qq_Q4Tg.cjs.map +1 -0
  27. package/dist/{run-Bz6ZUrhp.cjs → run-B9FN0sHW.cjs} +2 -2
  28. package/dist/run-B9FN0sHW.cjs.map +1 -0
  29. package/dist/{run-CPBFfbI7.js → run-BFhNcn8b.js} +4 -10
  30. package/dist/run-BFhNcn8b.js.map +1 -0
  31. package/dist/{run-B0HOqTrU.js → run-CCsw-Y-v.js} +226 -268
  32. package/dist/run-CCsw-Y-v.js.map +1 -0
  33. package/dist/{run-BBLhhWZu.js → run-D0Gs_UzJ.js} +2 -2
  34. package/dist/run-D0Gs_UzJ.js.map +1 -0
  35. package/dist/{run-C4k6vPeY.cjs → run-DT9pRBLX.cjs} +228 -269
  36. package/dist/run-DT9pRBLX.cjs.map +1 -0
  37. package/dist/{run-DYkciQ4u.cjs → run-DYzUPE7Z.cjs} +4 -10
  38. package/dist/run-DYzUPE7Z.cjs.map +1 -0
  39. package/dist/{run-44Zxh8Ec.js → run-yMRylOST.js} +3 -3
  40. package/dist/run-yMRylOST.js.map +1 -0
  41. package/dist/{tools-D0UogMU3.js → tools-B23ltmWP.js} +3 -3
  42. package/dist/tools-B23ltmWP.js.map +1 -0
  43. package/dist/{tools-CZT9wSA6.cjs → tools-CeIABV0T.cjs} +3 -3
  44. package/dist/tools-CeIABV0T.cjs.map +1 -0
  45. package/dist/{validate-CbWRcTMP.cjs → validate-BTVjxR4L.cjs} +8 -9
  46. package/dist/validate-BTVjxR4L.cjs.map +1 -0
  47. package/dist/{validate-BMaesb7k.js → validate-CZFmahWd.js} +9 -9
  48. package/dist/validate-CZFmahWd.js.map +1 -0
  49. package/package.json +8 -7
  50. package/dist/Telemetry-jtbchpQE.cjs.map +0 -1
  51. package/dist/Telemetry-ugO-B77y.js.map +0 -1
  52. package/dist/defineCommand-Bo3yZTWI.cjs +0 -36
  53. package/dist/defineCommand-Bo3yZTWI.cjs.map +0 -1
  54. package/dist/defineCommand-DMEeqliP.js +0 -31
  55. package/dist/defineCommand-DMEeqliP.js.map +0 -1
  56. package/dist/generate-D5AWn6lH.js.map +0 -1
  57. package/dist/generate-DfzX98Lx.cjs.map +0 -1
  58. package/dist/init-GU5uRenE.js.map +0 -1
  59. package/dist/init-hKT7f8_b.cjs.map +0 -1
  60. package/dist/mcp-B3TSdKiQ.js.map +0 -1
  61. package/dist/mcp-B5ppXTnU.cjs.map +0 -1
  62. package/dist/package-BBBrKion.cjs.map +0 -1
  63. package/dist/package-DSkZlfZS.js +0 -6
  64. package/dist/package-DSkZlfZS.js.map +0 -1
  65. package/dist/run-44Zxh8Ec.js.map +0 -1
  66. package/dist/run-B0HOqTrU.js.map +0 -1
  67. package/dist/run-BBLhhWZu.js.map +0 -1
  68. package/dist/run-Bz6ZUrhp.cjs.map +0 -1
  69. package/dist/run-C4k6vPeY.cjs.map +0 -1
  70. package/dist/run-CPBFfbI7.js.map +0 -1
  71. package/dist/run-DXEMoDFa.cjs.map +0 -1
  72. package/dist/run-DYkciQ4u.cjs.map +0 -1
  73. package/dist/tools-CZT9wSA6.cjs.map +0 -1
  74. package/dist/tools-D0UogMU3.js.map +0 -1
  75. package/dist/validate-BMaesb7k.js.map +0 -1
  76. package/dist/validate-CbWRcTMP.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-DT9pRBLX.cjs","names":["toError","logLevelMap","clack","Diagnostics","process","logLevelMap","Diagnostics","logLevelMap","toCause","process","canUseTTY","jiti","process","NonZeroExitError","toError","WATCHER_IGNORED_PATHS","logLevelMap","toError","process","Telemetry","version","Diagnostics","path","detectTool","formatters","linters","KUBB_NPM_PACKAGE_URL","UPDATE_CHECK_TIMEOUT_MS","AsyncEventEmitter","cliReporter","clack"],"sources":["../../../internals/utils/src/time.ts","../../../internals/utils/src/colors.ts","../../../internals/utils/src/promise.ts","../src/loggers/defineLogger.ts","../src/loggers/clackLogger.ts","../src/loggers/plainLogger.ts","../src/loggers/utils.ts","../../../internals/shared/src/loader.ts","../src/runners/generate/utils.ts","../src/runners/generate/run.ts"],"sourcesContent":["/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","import { hash } from 'node:crypto'\nimport { styleText } from 'node:util'\nimport { formatMs } from './time.ts'\n\n/**\n * Parsed RGB channels from a CSS hex color string.\n */\ntype RGB = { r: number; g: number; b: number }\n\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: string): RGB {\n const int = Number.parseInt(color.replace('#', ''), 16)\n return Number.isNaN(int) ? { r: 255, g: 255, b: 255 } : { r: (int >> 16) & 0xff, g: (int >> 8) & 0xff, b: int & 0xff }\n}\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: string): (text: string) => string {\n const { r, g, b } = parseHex(color)\n return (text: string) => `\\x1b[38;2;${r};${g};${b}m${text}\\x1b[0m`\n}\n\nfunction gradient(colorStops: Array<string>, text: string): string {\n const chars = text.split('')\n return chars\n .map((char, i) => {\n const t = chars.length <= 1 ? 0 : i / (chars.length - 1)\n const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2)\n const lt = t * (colorStops.length - 1) - seg\n const from = parseHex(colorStops[seg]!)\n const to = parseHex(colorStops[seg + 1]!)\n const r = Math.round(from.r + (to.r - from.r) * lt)\n const g = Math.round(from.g + (to.g - from.g) * lt)\n const b = Math.round(from.b + (to.b - from.b) * lt)\n return `\\x1b[38;2;${r};${g};${b}m${char}\\x1b[0m`\n })\n .join('')\n}\n\n/**\n * ANSI color functions for each part of the Kubb mascot illustration.\n */\nconst palette = {\n /**\n * Top cap of the skittle.\n */\n lid: hex('#F55A17'),\n /**\n * Upper wood body.\n */\n woodTop: hex('#F5A217'),\n /**\n * Middle wood body.\n */\n woodMid: hex('#F58517'),\n /**\n * Base wood body.\n */\n woodBase: hex('#B45309'),\n /**\n * Eye whites.\n */\n eye: hex('#FFFFFF'),\n /**\n * Highlight accent.\n */\n highlight: hex('#adadc6'),\n /**\n * Cheek blush.\n */\n blush: hex('#FDA4AF'),\n}\n\n/**\n * Generates the Kubb mascot welcome banner as an ANSI-colored string.\n *\n * @example\n * ```ts\n * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))\n * ```\n */\nexport function getIntro({\n title,\n description,\n version,\n areEyesOpen,\n}: {\n /**\n * Name of the active configuration or tool being started.\n */\n title: string\n /**\n * Short subtitle shown next to the arrow prompt.\n */\n description: string\n /**\n * Kubb version string rendered in the gradient header.\n */\n version: string\n /**\n * When `false` the eyes are shown as closed dashes instead of open blocks.\n */\n areEyesOpen: boolean\n}): string {\n const kubbVersion = gradient(['#F58517', '#F5A217', '#F55A17'], `KUBB v${version}`)\n\n const eyeTop = areEyesOpen ? palette.eye('█▀█') : palette.eye('───')\n const eyeBottom = areEyesOpen ? palette.eye('▀▀▀') : palette.eye('───')\n\n return `\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\n/**\n * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.\n */\nconst randomColors = ['black', 'red', 'green', 'yellow', 'blue', 'white', 'magenta', 'cyan', 'gray'] as const\n\n/**\n * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.\n *\n * @example\n * ```ts\n * randomCliColor('petstore') // '\\x1b[33m' + 'petstore' + '\\x1b[39m' (always the same color for 'petstore')\n * ```\n */\nexport function randomCliColor(text?: string): string {\n if (!text) return ''\n const index = hash('sha256', text, 'buffer').readUInt32BE(0) % randomColors.length\n const color = randomColors[index] ?? 'white'\n\n return styleText(color, text)\n}\n\n/**\n * Formats a millisecond duration with a threshold-based ANSI color.\n * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.\n *\n * @example\n * ```ts\n * formatMsWithColor(200) // '\\x1b[32m200ms\\x1b[39m'\n * formatMsWithColor(800) // '\\x1b[33m800ms\\x1b[39m'\n * formatMsWithColor(1500) // '\\x1b[31m1.50s\\x1b[39m'\n * ```\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n if (ms <= 500) return styleText('green', formatted)\n if (ms <= 1000) return styleText('yellow', formatted)\n\n return styleText('red', formatted)\n}\n","import { toError } from './errors.ts'\n\n/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\n}\n","import type { KubbHooks, AsyncEventEmitter } from '@kubb/core'\n\n/**\n * Options accepted by a logger's `install` callback.\n */\nexport type LoggerOptions = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`).\n */\n logLevel: number\n}\n\n/**\n * Event emitter handed to `Logger.install`. Use `.on('kubb:info', ...)` to\n * subscribe to build events.\n */\nexport type LoggerContext = AsyncEventEmitter<KubbHooks>\n\n/**\n * Logger contract. A logger receives the build's event emitter and subscribes\n * to whichever lifecycle events it wants to forward to its destination\n * (console, file, remote service).\n */\nexport type Logger<TOptions extends LoggerOptions = LoggerOptions> = {\n /**\n * Display name used in diagnostics.\n */\n name: string\n /**\n * Called once per build with the shared event emitter. Subscribe to the\n * lifecycle events the logger wants to forward to its destination.\n */\n install: (context: LoggerContext, options?: TOptions) => void | Promise<void>\n}\n\n/**\n * Type-safe helper for authoring a {@link Logger}.\n *\n * @example\n * ```ts\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context) {\n * context.on('kubb:info', ({ message }) => console.log('ℹ', message))\n * },\n * })\n * ```\n */\nexport function defineLogger<TOptions extends LoggerOptions = LoggerOptions>(logger: Logger<TOptions>): Logger<TOptions> {\n return logger\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { formatMsWithColor, getElapsedMs, getIntro } from '@internals/utils'\nimport { Diagnostics, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { defineLogger } from './defineLogger.ts'\nimport {\n buildProgressLine,\n createProgressCounters,\n formatCommandWithArgs,\n formatErrorFrames,\n formatMessage,\n recordPluginResult,\n resetProgressCounters,\n} from './utils.ts'\n\n/**\n * TTY logger for local development, with spinners and progress bars.\n */\nexport const clackLogger = defineLogger({\n name: 'clack',\n install(context, options) {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const state = {\n ...createProgressCounters(),\n spinner: clack.spinner(),\n isSpinning: false,\n runningPlugins: new Set<string>(),\n activeProgress: new Map<string, { interval?: NodeJS.Timeout; progressBar: clack.ProgressResult }>(),\n activeHookLogs: new Map<string, { taskLog: ReturnType<typeof clack.taskLog>; hrStart: [number, number] }>(),\n }\n\n // Clear every active progress bar's interval, stop it, and drop the map.\n function stopActiveProgress() {\n for (const [, active] of state.activeProgress) {\n if (active.interval) {\n clearInterval(active.interval)\n }\n active.progressBar?.stop()\n }\n state.activeProgress.clear()\n }\n\n function reset() {\n stopActiveProgress()\n\n resetProgressCounters(state)\n state.spinner = clack.spinner()\n state.isSpinning = false\n state.runningPlugins.clear()\n state.activeHookLogs.clear()\n }\n\n // Label for the shared plugin bar, listing the plugins currently generating.\n function pluginProgressText(): string {\n const running = [...state.runningPlugins].map((name) => styleText('bold', name))\n return getMessage(running.length > 0 ? `Generating ${running.join(', ')}` : 'Generating plugins')\n }\n\n function showProgressStep() {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const line = buildProgressLine(state)\n if (line) {\n clack.log.step(getMessage(line))\n }\n }\n\n function getMessage(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n // Registers a handler that prints a fixed step message, skipped at silent level.\n function onStep<E extends keyof KubbHooks>(event: E, message: string): void {\n context.on(event, () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n clack.log.step(getMessage(message))\n })\n }\n\n function stopSpinner(text?: string) {\n if (!state.isSpinning) {\n return\n }\n state.spinner.stop(text)\n state.isSpinning = false\n }\n\n context.on('kubb:info', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n if (state.isSpinning) {\n state.spinner.message(text)\n return\n }\n clack.log.info(text)\n })\n\n context.on('kubb:success', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', '✓'), message, logLevel >= logLevelMap.info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n if (state.isSpinning) {\n stopSpinner(text)\n return\n }\n clack.log.success(text)\n })\n\n context.on('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n const text = getMessage(\n [styleText('yellow', '⚠'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '),\n )\n\n clack.log.warn(text)\n })\n\n context.on('kubb:error', ({ error }) => {\n const text = [styleText('red', '✗'), error.message].join(' ')\n\n if (state.isSpinning) {\n stopSpinner(getMessage(text))\n return\n }\n clack.log.error(getMessage(text))\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (frames) {\n for (const frame of frames.frames) {\n clack.log.message(getMessage(styleText('dim', frame)))\n }\n\n if (frames.cause) {\n clack.log.message(styleText('dim', frames.cause.header))\n\n for (const frame of frames.cause.frames) {\n clack.log.message(getMessage(` ${styleText('dim', frame)}`))\n }\n }\n }\n })\n\n context.on('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {\n return\n }\n\n stopSpinner()\n\n // Stop any lingering progress UI so the multi-line block renders cleanly.\n stopActiveProgress()\n\n // The version-update notice keeps its own framed box instead of the diagnostic gutter.\n if (Diagnostics.isUpdate(diagnostic)) {\n clack.box(\n `\\`v${diagnostic.currentVersion}\\` → \\`v${diagnostic.latestVersion}\\`\nRun \\`npm install -g @kubb/cli\\` to update`,\n 'Update available for `Kubb`',\n {\n width: 'auto',\n formatBorder: (s: string) => styleText('yellow', s),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n },\n )\n\n return\n }\n\n // The diagnostic carries the code and its own indented detail rows, so clear clack's\n // gutter and bar (`symbol`/`secondarySymbol`) and let the block stand on its own.\n const { headline, details } = Diagnostics.format(diagnostic)\n clack.log.message([headline, ...details], { symbol: '', secondarySymbol: '' })\n })\n\n context.on('kubb:lifecycle:start', async ({ version }) => {\n console.log(`\\n${getIntro({ title: 'The meta framework for code generation', description: 'Ready to start', version, areEyesOpen: true })}\\n`)\n\n reset()\n })\n\n context.on('kubb:generation:start', ({ config }) => {\n reset()\n\n // Initialize progress tracking for this generation\n state.totalPlugins = config.plugins?.length ?? 0\n\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(['Generation started', config.name ? `for ${styleText('dim', config.name)}` : undefined].filter(Boolean).join(' '))\n\n clack.intro(text)\n })\n\n // Plugins run concurrently, so they share a single progress bar. A bar per plugin\n // would make clack render them side by side and pile up keypress listeners.\n context.on('kubb:plugin:start', ({ plugin }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n state.runningPlugins.add(plugin.name)\n\n const active = state.activeProgress.get('plugins')\n if (active) {\n active.progressBar.advance(0, pluginProgressText())\n return\n }\n\n const progressBar = clack.progress({\n style: 'block',\n max: Math.max(state.totalPlugins, 1),\n size: 30,\n })\n progressBar.start(pluginProgressText())\n // Catch up to plugins already finished before this bar opened.\n progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText())\n state.activeProgress.set('plugins', { progressBar })\n })\n\n context.on('kubb:plugin:end', ({ plugin, success }) => {\n stopSpinner()\n\n const active = state.activeProgress.get('plugins')\n\n if (!active || logLevel === logLevelMap.silent) {\n return\n }\n\n state.runningPlugins.delete(plugin.name)\n recordPluginResult(state, success)\n active.progressBar.advance(1, pluginProgressText())\n\n // Close the bar once nothing is generating, then print the progress step.\n if (state.runningPlugins.size === 0) {\n active.progressBar.stop(getMessage('Plugins generated'))\n state.activeProgress.delete('plugins')\n showProgressStep()\n }\n })\n\n context.on('kubb:files:processing:start', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n state.totalFiles = files.length\n state.processedFiles = 0\n\n const text = `Writing ${files.length} files`\n const progressBar = clack.progress({\n style: 'block',\n max: files.length,\n size: 30,\n })\n\n context.emit('kubb:info', { message: text })\n progressBar.start(getMessage(text))\n state.activeProgress.set('files', { progressBar })\n })\n\n context.on('kubb:files:processing:update', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n const active = state.activeProgress.get('files')\n for (const { file, config } of files) {\n state.processedFiles++\n if (active) {\n active.progressBar.advance(undefined, `Writing ${relative(config.root, file.path)}`)\n }\n }\n })\n context.on('kubb:files:processing:end', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n const text = getMessage('Files written successfully')\n const active = state.activeProgress.get('files')\n\n if (!active) {\n return\n }\n\n active.progressBar.stop(text)\n state.activeProgress.delete('files')\n\n // Show final progress step after files are written\n showProgressStep()\n })\n\n context.on('kubb:generation:end', ({ config }) => {\n stopSpinner()\n\n const text = getMessage(config.name ? `Generation completed for ${styleText('dim', config.name)}` : 'Generation completed')\n\n clack.outro(text)\n })\n\n onStep('kubb:format:start', 'Formatting')\n onStep('kubb:lint:start', 'Linting')\n onStep('kubb:hooks:start', 'Running hooks')\n\n context.on('kubb:hook:start', ({ id, command, args }) => {\n if (logLevel <= logLevelMap.silent || !id) {\n return\n }\n\n stopSpinner()\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n const title = getMessage(`Running ${styleText('dim', commandWithArgs)}`)\n const taskLog = clack.taskLog({ title })\n\n state.activeHookLogs.set(id, { taskLog, hrStart: process.hrtime() })\n })\n\n // Registered only when not silent, so its presence is what tells the runner to stream\n // (`kubb:hook:line` listenerCount). At silent level the listener is absent, so no streaming happens.\n if (logLevel > logLevelMap.silent) {\n context.on('kubb:hook:line', ({ id, line }) => {\n const active = state.activeHookLogs.get(id)\n active?.taskLog.message(styleText('dim', line))\n })\n }\n\n context.on('kubb:hook:end', ({ id, command, args, success, error, stdout, stderr }) => {\n if (!id) {\n return\n }\n\n if (logLevel <= logLevelMap.silent) {\n // Even when silent, surface a failed hook's captured output.\n if (!success) {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n }\n return\n }\n\n const active = state.activeHookLogs.get(id)\n if (!active) {\n return\n }\n state.activeHookLogs.delete(id)\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n const duration = formatMsWithColor(getElapsedMs(active.hrStart))\n\n if (success) {\n active.taskLog.success(getMessage(`${styleText('dim', commandWithArgs)} completed in ${duration}`))\n } else {\n // The hook's output already reached the taskLog live via `kubb:hook:line`, so `showLog`\n // replays it here. `kubb:hook:end` carries no captured output on the streaming path.\n const reason = error?.message ? ` (${error.message})` : ''\n active.taskLog.error(getMessage(`${styleText('dim', commandWithArgs)} failed${reason}`), { showLog: true })\n }\n })\n\n context.on('kubb:lifecycle:end', () => {\n reset()\n })\n },\n})\n","import { relative } from 'node:path'\nimport { formatMs } from '@internals/utils'\nimport { Diagnostics, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { defineLogger } from './defineLogger.ts'\nimport { createHookTimer, formatCommandWithArgs, formatErrorFrames, formatMessage } from './utils.ts'\n\n/**\n * Plain console adapter for non-TTY environments, built on `console.log`.\n */\nexport const plainLogger = defineLogger({\n name: 'plain',\n install(context, options) {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const hookTimer = createHookTimer()\n\n function getMessage(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n // Registers a handler that logs a fixed message, skipped at silent level.\n function onStep<E extends keyof KubbHooks>(event: E, message: string): void {\n context.on(event, () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(message))\n })\n }\n\n context.on('kubb:info', ({ message, info }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(['ℹ', message, info].join(' '))\n\n console.log(text)\n })\n\n context.on('kubb:success', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(['✓', message, logLevel >= logLevelMap.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.on('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n const text = getMessage(['⚠', message, logLevel >= logLevelMap.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.on('kubb:error', ({ error }) => {\n const text = getMessage(['✗', error.message].join(' '))\n\n console.log(text)\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (frames) {\n for (const frame of frames.frames) {\n console.log(getMessage(frame))\n }\n\n if (frames.cause) {\n console.log(frames.cause.header)\n\n for (const frame of frames.cause.frames) {\n console.log(getMessage(` ${frame}`))\n }\n }\n }\n })\n\n context.on('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {\n return\n }\n console.log(getMessage(Diagnostics.formatLines(diagnostic).join('\\n')))\n })\n\n context.on('kubb:lifecycle:start', ({ version }) => {\n console.log(`Kubb CLI v${version}`)\n })\n\n context.on('kubb:generation:start', () => {\n const text = getMessage('Generation started')\n\n console.log(text)\n })\n\n context.on('kubb:plugin:start', ({ plugin }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n const text = getMessage(`Generating ${plugin.name}`)\n\n console.log(text)\n })\n\n context.on('kubb:plugin:end', ({ plugin, duration, success }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const durationStr = formatMs(duration)\n const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`)\n\n console.log(text)\n })\n\n context.on('kubb:files:processing:start', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(`Writing ${files.length} files`)\n\n console.log(text)\n })\n\n context.on('kubb:files:processing:update', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n for (const { file, config } of files) {\n console.log(getMessage(`Writing ${relative(config.root, file.path)}`))\n }\n })\n\n context.on('kubb:files:processing:end', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage('Files written successfully')\n\n console.log(text)\n })\n\n context.on('kubb:generation:end', ({ config }) => {\n const text = getMessage(config.name ? `Generation completed for ${config.name}` : 'Generation completed')\n\n console.log(text)\n })\n\n onStep('kubb:format:start', 'Format started')\n onStep('kubb:format:end', 'Format completed')\n onStep('kubb:lint:start', 'Lint started')\n onStep('kubb:lint:end', 'Lint completed')\n onStep('kubb:hooks:start', 'Hooks started')\n onStep('kubb:hooks:end', 'Hooks completed')\n\n context.on('kubb:hook:start', ({ id, command, args }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n if (id) {\n hookTimer.start(id)\n }\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n console.log(getMessage(`Hook ${commandWithArgs} started`))\n })\n\n context.on('kubb:hook:end', ({ id, command, args, success, error, stdout, stderr }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const ms = id ? hookTimer.end(id) : undefined\n const durationStr = ms !== undefined ? ` in ${formatMs(ms)}` : ''\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n\n if (success) {\n console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`))\n } else {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n const reason = error?.message ? ` (${error.message})` : ''\n console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`))\n }\n })\n },\n})\n","import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { canUseTTY, formatMs, getElapsedMs, toCause } from '@internals/utils'\nimport type { Reporter, ReporterContext } from '@kubb/core'\nimport { logLevel as logLevelMap } from '@kubb/core'\nimport type { LoggerContext, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/**\n * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.\n * Shared across all logger adapters to avoid duplication.\n */\nexport function formatMessage(message: string, logLevel: number): string {\n if (logLevel >= logLevelMap.verbose) {\n const timestamp = new Date().toLocaleTimeString('en-US', {\n hour12: false,\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n return `${styleText('dim', `[${timestamp}]`)} ${message}`\n }\n return message\n}\n\n/**\n * First stack frames for verbose error output, including an optional `cause` chain.\n */\nexport function formatErrorFrames(error: Error): { frames: Array<string>; cause?: { header: string; frames: Array<string> } } | null {\n if (!error.stack) {\n return null\n }\n\n const frames = error.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim())\n const caused = toCause(error)\n\n if (!caused?.stack) {\n return { frames }\n }\n\n return {\n frames,\n cause: {\n header: `└─ caused by ${caused.message}`,\n frames: caused.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim()),\n },\n }\n}\n\ntype ProgressState = {\n /**\n * Total number of plugins scheduled for this generation run.\n */\n totalPlugins: number\n /**\n * Number of plugins that have finished without error.\n */\n completedPlugins: number\n /**\n * Number of plugins that exited with an error.\n */\n failedPlugins: number\n /**\n * Total number of files expected to be written.\n */\n totalFiles: number\n /**\n * Number of files written so far.\n */\n processedFiles: number\n /**\n * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.\n */\n hrStart: [number, number]\n}\n\n/**\n * Build the progress summary line shown by the clack logger.\n * Returns null when there is nothing to display.\n */\nexport function buildProgressLine(state: ProgressState): string | null {\n const parts: Array<string> = []\n const duration = formatMs(getElapsedMs(state.hrStart))\n\n if (state.totalPlugins > 0) {\n const pluginStr =\n state.failedPlugins > 0\n ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`\n : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`\n parts.push(pluginStr)\n }\n\n if (state.totalFiles > 0) {\n parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)\n }\n\n if (parts.length === 0) {\n return null\n }\n\n parts.push(`${styleText('green', duration)} elapsed`)\n return parts.join(styleText('dim', ' | '))\n}\n\n/**\n * Creates the per-run progress counters used by the clack logger.\n */\nexport function createProgressCounters(): ProgressState {\n return {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n }\n}\n\n/**\n * Resets the progress counters in place at the start/end of a generation run.\n */\nexport function resetProgressCounters(state: ProgressState): void {\n state.totalPlugins = 0\n state.completedPlugins = 0\n state.failedPlugins = 0\n state.totalFiles = 0\n state.processedFiles = 0\n state.hrStart = process.hrtime()\n}\n\n/**\n * Records a finished plugin against the progress counters.\n */\nexport function recordPluginResult(state: ProgressState, success: boolean): void {\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n}\n\n/**\n * Tracks per-hook start times so a logger can report a hook's elapsed duration.\n * Used by the plain logger, which keys timing by hook `id`.\n */\nexport type HookTimer = {\n start(id: string): void\n /**\n * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.\n */\n end(id: string): number | undefined\n}\n\n/**\n * Creates a {@link HookTimer} backed by a private `id → hrtime` map.\n */\nexport function createHookTimer(): HookTimer {\n const starts = new Map<string, [number, number]>()\n\n return {\n start(id: string): void {\n starts.set(id, process.hrtime())\n },\n end(id: string): number | undefined {\n const hrStart = starts.get(id)\n if (!hrStart) {\n return undefined\n }\n starts.delete(id)\n return getElapsedMs(hrStart)\n },\n }\n}\n\n/**\n * Join a command and its optional args into a single display string.\n *\n * @example With args\n * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`\n */\nexport function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {\n return args?.length ? `${command} ${args.join(' ')}` : command\n}\n\n/**\n * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's\n * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.\n */\nexport function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {\n context.on('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart }, ctx)\n })\n\n if (reporter.drain) {\n context.on('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/**\n * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are\n * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This\n * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the\n * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.\n *\n * Loggers and reporters are independent, except for `cli`: it both installs the live logger view\n * here and registers as a reporter that prints the per-config summary. The `json` reporter owns\n * stdout, so the whole `cli` reporter (live logger and summary) is skipped whenever `json` is\n * among the reporters, even if `cli` is also listed.\n */\nasync function setupReporters(context: LoggerContext, { logLevel, reporters }: LoggerOptions & { reporters: ReadonlyArray<Reporter> }): Promise<void> {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name === 'cli') {\n if (hasJson) {\n continue\n }\n const logger = canUseTTY() ? clackLogger : plainLogger\n await logger.install(context, { logLevel })\n }\n\n installReporter(context, reporter, ctx)\n }\n}\n\nexport default setupReporters\n\n/**\n * Picks the reporters whose `name` matches one of `names`, in the order the names are given.\n * The config carries every available reporter, and the host selects which to activate by name\n * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are\n * skipped.\n */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n const seen = new Set<string>()\n const selected: Array<Reporter> = []\n\n for (const name of names) {\n if (seen.has(name)) {\n continue\n }\n seen.add(name)\n\n const reporter = reporters.find((candidate) => candidate.name === name)\n if (reporter) {\n selected.push(reporter)\n }\n }\n\n return selected\n}\n","import { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Per-call options for {@link ModuleLoader.load}.\n */\nexport type LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\nexport type ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { basename, dirname, resolve } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createModuleLoader } from '@internals/shared'\nimport { createSerialRunner, toError } from '@internals/utils'\nimport type { CLIOptions, Config, KubbHooks, PossibleConfig, AsyncEventEmitter } from '@kubb/core'\nimport { NonZeroExitError, x } from 'tinyexec'\nimport { type LoadConfigResult, type LoadConfigSource, loadConfig } from 'unconfig'\nimport { WATCHER_DEBOUNCE_MS, WATCHER_IGNORED_PATHS } from '../../constants.ts'\n\nconst loader = createModuleLoader()\n\n// Kubb configs are JS/TS modules (they call `defineConfig`/`pluginX()`), so YAML and JSON are not\n// supported. The jiti loader handles every module format and the JSX runtime, returning the default export.\nconst tsLoader = (configFile: string) => loader.load(configFile, { default: true })\n\nconst MODULE_NAME = 'kubb'\n\nconst SEARCH_FILES = ['', '.config/', 'configs/'].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`])\nconst SEARCH_EXTENSIONS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']\n\ntype GetConfigsOptions = {\n /**\n * Explicit path to the Kubb config file. When omitted, the loader searches up from the current directory.\n */\n configPath?: string\n /**\n * Optional OpenAPI input path that overrides `config.input.path` for this run.\n */\n input?: string\n /**\n * Watch flag forwarded to the user's `defineConfig` function.\n */\n watch?: boolean\n /**\n * Log level forwarded to the user's `defineConfig` function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /**\n * Absolute path to the resolved config file.\n */\n configPath: string\n /**\n * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.\n */\n configs: Array<Config>\n}\n\n/**\n * Discovers the Kubb config and resolves it into a normalized array of configs.\n * Every config in the result is guaranteed to have a `plugins` array.\n */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const abs = configPath ? resolve(configPath) : undefined\n const sources: Array<LoadConfigSource<unknown>> = abs\n ? [{ files: [basename(abs)], extensions: [], parser: tsLoader }]\n : [{ files: SEARCH_FILES, extensions: SEARCH_EXTENSIONS, parser: tsLoader }]\n\n let result: LoadConfigResult<unknown>\n try {\n result = await loadConfig<unknown>({ cwd: abs ? dirname(abs) : process.cwd(), sources, merge: false })\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n const [filepath] = result.sources\n if (!result.config || !filepath) {\n throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n const config = result.config as PossibleConfig<CLIOptions>\n const cli: CLIOptions = { config: configPath, input, watch, logLevel }\n const resolved = await (typeof config === 'function' ? config(cli) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return {\n configPath: filepath,\n configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),\n }\n}\n\ntype ExecuteHooksOptions = {\n configHooks: NonNullable<Config['hooks']>\n hooks: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Outcome of a single hook subprocess, returned by `runHook` alongside the\n * `kubb:hook:end` event it emits for the loggers.\n */\nexport type HookResult = {\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * What went wrong, `null` when the command succeeded.\n */\n error: Error | null\n /**\n * Captured stdout, only present on a non-zero exit.\n */\n stdout?: string\n /**\n * Captured stderr, only present on a non-zero exit.\n */\n stderr?: string\n}\n\nlet hookSequence = 0\n\n/**\n * Returns a process-unique id that correlates a hook's `kubb:hook:start` and `kubb:hook:end`\n * events, which loggers use to key their per-hook state.\n */\nexport function createHookId(): string {\n hookSequence += 1\n return `hook-${hookSequence}`\n}\n\n/**\n * Returns `true` when `latest` is a newer semver version than `current`. Compares each numeric\n * part, so `5.10.0` beats `5.9.0` where a plain string comparison would not. Prerelease\n * suffixes are ignored, and a malformed version never reports an update.\n *\n * @example Double-digit minor\n * `isNewerVersion('5.9.0', '5.10.0') // true`\n *\n * @example String comparison would get this wrong the other way\n * `isNewerVersion('5.10.0', '5.9.0') // false`\n */\nexport function isNewerVersion(current: string, latest: string): boolean {\n const release = (value: string) => value.split('-')[0] ?? ''\n const isNumeric = (value: string) => /^\\d+(\\.\\d+)*$/.test(value)\n\n const currentRelease = release(current)\n const latestRelease = release(latest)\n if (!isNumeric(currentRelease) || !isNumeric(latestRelease)) return false\n\n return currentRelease.localeCompare(latestRelease, undefined, { numeric: true }) < 0\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nfunction tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n\n/**\n * Runs the `done` hooks defined in a Kubb config in sequence and returns each hook's outcome,\n * so the caller can turn failures into diagnostics.\n */\nexport async function executeHooks({ configHooks, hooks }: ExecuteHooksOptions): Promise<Array<HookResult>> {\n const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)\n const results: Array<HookResult> = []\n\n for (const command of commands) {\n const [cmd, ...args] = tokenize(command)\n if (!cmd) continue\n\n const hookId = createHookId()\n const commandWithArgs = [cmd, ...args].join(' ')\n\n await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })\n results.push(await runHook({ id: hookId, command: cmd, args, commandWithArgs, hooks }))\n }\n\n return results\n}\n\ntype RunHookOptions = {\n id: string\n command: string\n args?: ReadonlyArray<string>\n commandWithArgs: string\n hooks: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Spawns a hook command and returns its outcome, mirroring it through `kubb:hook:end` for the\n * loggers. A non-zero exit returns `success: false` rather than throwing, so the caller can turn\n * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`\n * only while a listener is attached.\n */\nexport async function runHook({ id, command, args, commandWithArgs, hooks }: RunHookOptions): Promise<HookResult> {\n const emitEnd = async (result: HookResult): Promise<HookResult> => {\n await hooks.emit('kubb:hook:end', { command, args, id, ...result })\n return result\n }\n\n // Only stream line-by-line when a logger is listening, so the non-streaming plain\n // logger doesn't pay to iterate the subprocess output.\n const stream = hooks.listenerCount('kubb:hook:line') > 0\n\n try {\n const proc = x(command, [...(args ?? [])], {\n nodeOptions: { detached: process.platform !== 'win32' },\n throwOnError: true,\n })\n\n if (stream) {\n for await (const line of proc) {\n await hooks.emit('kubb:hook:line', { id, line })\n }\n }\n\n await proc\n await hooks.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })\n return emitEnd({ success: true, error: null })\n } catch (err) {\n if (!(err instanceof NonZeroExitError)) {\n return emitEnd({ success: false, error: toError(err) })\n }\n\n const stderr = err.output?.stderr ?? ''\n const stdout = err.output?.stdout ?? ''\n\n const error = new Error(`Hook execute failed: ${commandWithArgs}`)\n // Signal the failure via the result and `kubb:hook:end` only, carrying the captured output so\n // the logger can render it. The caller turns this into a coded diagnostic and emits that\n // through `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.\n return emitEnd({ success: false, error, stdout, stderr })\n }\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one build, and builds never overlap: changes during a build queue exactly\n * one rebuild.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<void> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { toError } from '@internals/utils'\nimport {\n AsyncEventEmitter,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n type KubbHooks,\n logLevel as logLevelMap,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { Telemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { createHookId, executeHooks, getConfigs, isNewerVersion, runHook, startWatcher } from './utils.ts'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: AsyncEventEmitter<KubbHooks>\n logLevel: number\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\ntype RunToolPassOptions = {\n toolValue: string\n detect: () => Promise<string | null>\n toolMap: ToolMap\n toolLabel: string\n successPrefix: string\n noToolMessage: string\n outputPath: string\n logLevel: number\n hooks: AsyncEventEmitter<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({\n toolValue,\n detect,\n toolMap,\n toolLabel,\n successPrefix,\n noToolMessage,\n outputPath,\n logLevel,\n hooks,\n onStart,\n onEnd,\n}: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await detect()\n if (!detected) {\n await hooks.emit('kubb:warn', { message: noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.emit('kubb:info', { message: `Auto-detected ${toolLabel}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in toolMap && existsSync(outputPath)) {\n const toolConfig = toolMap[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = createHookId()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.emit('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.emit('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (options.config.input && 'path' in options.config.input ? options.config.input.path : undefined)\n\n const config: Config = {\n ...options.config,\n input: inputPath ? { ...options.config.input, path: inputPath } : options.config.input,\n }\n\n const kubb = createKubb(config, { hooks })\n\n await hooks.emit('kubb:generation:start', { config })\n await hooks.emit('kubb:info', { message: config.name ? `Setup generation ${styleText('bold', config.name)}` : 'Setup generation', info: inputPath })\n\n await kubb.setup()\n\n await hooks.emit('kubb:info', { message: config.name ? `Build generation ${styleText('bold', config.name)}` : 'Build generation', info: inputPath })\n\n const { files, diagnostics, driver } = await kubb.safeBuild()\n\n await hooks.emit('kubb:info', { message: 'Load summary' })\n\n const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n\n const reportTelemetry = (status: 'success' | 'failed') =>\n Telemetry.send(Telemetry.build({ command: 'generate', kubbVersion: version, plugins: telemetryPlugins, hrStart, filesCreated: files.length, status }))\n\n // Render every problem, not just on failure, so warnings and info surface too.\n // `performance` diagnostics feed the summary, not the log.\n for (const diagnostic of diagnostics) {\n if (!Diagnostics.isProblem(diagnostic)) {\n continue\n }\n const unknown = Diagnostics.narrow(diagnostic, Diagnostics.code.unknown)\n if (unknown) {\n await hooks.emit('kubb:error', { error: unknown.cause ?? new Error(unknown.message) })\n } else {\n await Diagnostics.emit(hooks, diagnostic)\n }\n }\n\n // Only an error-severity diagnostic fails the run. Warnings and info do not.\n if (Diagnostics.hasError(diagnostics)) {\n await hooks.emit('kubb:generation:end', { config, storage: kubb.storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart })\n\n await reportTelemetry('failed')\n return false\n }\n\n const outputPath = path.resolve(config.root, config.output.path)\n\n // The build succeeded. The formatter, linter, and post-generate hooks run after it. Their\n // failures used to only emit `kubb:error`, so they never reached the summary, the json report,\n // or the exit code. Collect them as coded diagnostics here.\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n if (config.output.format) {\n const error = await runToolPass({\n toolValue: config.output.format,\n detect: () => detectTool(['oxfmt', 'biome', 'prettier'] as const),\n toolMap: formatters,\n toolLabel: 'formatter',\n successPrefix: 'Formatting',\n noToolMessage: 'No formatter found (oxfmt, biome, or prettier). Skipping formatting.',\n onStart: () => hooks.emit('kubb:format:start'),\n onEnd: () => hooks.emit('kubb:format:end'),\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(Diagnostics.code.formatFailed, 'formatter', error)\n }\n\n if (config.output.lint) {\n const error = await runToolPass({\n toolValue: config.output.lint,\n detect: () => detectTool(['oxlint', 'biome', 'eslint'] as const),\n toolMap: linters,\n toolLabel: 'linter',\n successPrefix: 'Linting',\n noToolMessage: 'No linter found (oxlint, biome, or eslint). Skipping linting.',\n onStart: () => hooks.emit('kubb:lint:start'),\n onEnd: () => hooks.emit('kubb:lint:end'),\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(Diagnostics.code.lintFailed, 'linter', error)\n }\n\n if (config.hooks) {\n await hooks.emit('kubb:hooks:start')\n const hookResults = await executeHooks({ configHooks: config.hooks, hooks })\n for (const result of hookResults) {\n if (result.success) continue\n await reportOutputFailure(Diagnostics.code.hookFailed, 'Post-generate hook', result.error ?? new Error('Post-generate hook failed'))\n }\n await hooks.emit('kubb:hooks:end')\n }\n\n const finalDiagnostics = [...diagnostics, ...outputDiagnostics]\n const failed = Diagnostics.hasError(outputDiagnostics)\n\n if (!failed) {\n await hooks.emit('kubb:success', { message: 'Generation succeeded', info: inputPath })\n }\n\n await hooks.emit('kubb:generation:end', {\n config,\n storage: kubb.storage,\n diagnostics: finalDiagnostics,\n filesCreated: files.length,\n status: failed ? 'failed' : 'success',\n hrStart,\n })\n\n await reportTelemetry(failed ? 'failed' : 'success')\n return !failed\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n}\n\nasync function checkForUpdate(hooks: AsyncEventEmitter<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new AsyncEventEmitter<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.emit('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const available = configs[0]?.reporters ?? []\n const reporters = selectReporters(available, requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.emit('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.emit('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.emit('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n if (config.input && 'path' in config.input && watch) {\n const watchedPaths = [input || config.input.path]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks })\n clack.log.step(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // The watcher ignores chokidar's startup events, so run the first build here. A failing\n // first build keeps watching, since the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.emit('kubb:error', { error: toError(buildError) })\n }\n\n await startWatcher(watchedPaths, build, { info: (msg) => clack.log.info(msg), error: (msg) => clack.log.error(msg) })\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.emit('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.emit('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.emit('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,aAAa,SAAmC;CAC9D,MAAM,CAAC,SAAS,eAAe,QAAQ,OAAO,OAAO;CACrD,MAAM,KAAK,UAAU,MAAO,cAAc;CAC1C,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI;AAChC;;;;;;;;;;;AAYA,SAAgB,SAAS,IAAoB;CAC3C,IAAI,MAAM,KAGR,OAAO,GAFM,KAAK,MAAM,KAAK,GAEhB,EAAE,KADA,KAAK,MAAS,IAAA,CAAM,QAAQ,CACrB,EAAE;CAG1B,IAAI,MAAM,KACR,OAAO,IAAI,KAAK,IAAA,CAAM,QAAQ,CAAC,EAAE;CAEnC,OAAO,GAAG,KAAK,MAAM,EAAE,EAAE;AAC3B;;;;;;;ACzBA,SAAS,SAAS,OAAoB;CACpC,MAAM,MAAM,OAAO,SAAS,MAAM,QAAQ,KAAK,EAAE,GAAG,EAAE;CACtD,OAAO,OAAO,MAAM,GAAG,IAAI;EAAE,GAAG;EAAK,GAAG;EAAK,GAAG;CAAI,IAAI;EAAE,GAAI,OAAO,KAAM;EAAM,GAAI,OAAO,IAAK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AM,KAAK,gBAAgB;GAAE,SAAS;GAA8B,MAAM;EAAmB,CAAC;EAEpG,IAAI,YAAY;EAChB,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,SAAS,UAAU,OAAO,SAAS,OAAO;GACnD,MAAM,eAAe,CAAC,SAAS,OAAO,MAAM,IAAI;GAIhD,MAAM,QAAQ,OAAO,UAAyB;IAC5C,MAAM,SAAS;KAAE;KAAO;KAAQ;KAAU;IAAM,CAAC;IACjD,eAAM,IAAI,MAAA,GAAA,UAAA,UAAA,CAAe,UAAU,2BAA2B,MAAM,KAAK,OAAO,GAAG,CAAC;GACtF;GAIA,IAAI;IACF,MAAM,MAAM,YAAY;GAC1B,SAAS,YAAY;IACnB,MAAM,MAAM,KAAK,cAAc,EAAE,OAAOD,eAAAA,QAAQ,UAAU,EAAE,CAAC;GAC/D;GAEA,MAAM,aAAa,cAAc,OAAO;IAAE,OAAO,QAAQa,eAAM,IAAI,KAAK,GAAG;IAAG,QAAQ,QAAQA,eAAM,IAAI,MAAM,GAAG;GAAE,CAAC;EACtH,OACE,IAAI;GAEF,IAAI,CAAC,MADmB,SAAS;IAAE;IAAO;IAAQ;IAAU;GAAM,CAAC,GACnD,YAAY;EAC9B,SAAS,aAAa;GACpB,MAAM,MAAM,KAAK,cAAc,EAAE,OAAOb,eAAAA,QAAQ,WAAW,EAAE,CAAC;GAC9D,YAAY;EACd;EAIJ,MAAM,MAAM,KAAK,oBAAoB;EAErC,IAAI,WACF,aAAA,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,KAAK,cAAc,EAAE,OAAOA,eAAAA,QAAQ,KAAK,EAAE,CAAC;EACxD,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,21 +1,15 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-Bx3C2hgW.cjs");
2
+ const require_Telemetry = require("./Telemetry-CwQYBgsg.cjs");
2
3
  const require_errors = require("./errors-gxFK0vrp.cjs");
3
- const require_Telemetry = require("./Telemetry-jtbchpQE.cjs");
4
4
  let node_util = require("node:util");
5
5
  let node_process = require("node:process");
6
6
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
7
7
  //#region src/runners/validate/run.ts
8
8
  /**
9
- * Dynamically loads `@kubb/adapter-oas` for OpenAPI validation.
10
- */
11
- function loadValidateModule() {
12
- return import("@kubb/adapter-oas");
13
- }
14
- /**
15
9
  * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.
16
10
  * Exits the process with code 1 on validation failure or missing dependency.
17
11
  */
18
- async function run({ input, version }, dependencies = { loadValidateModule }) {
12
+ async function run({ input, version }) {
19
13
  const hrStart = node_process.default.hrtime();
20
14
  const report = (status) => require_Telemetry.Telemetry.send(require_Telemetry.Telemetry.build({
21
15
  command: "validate",
@@ -24,7 +18,7 @@ async function run({ input, version }, dependencies = { loadValidateModule }) {
24
18
  status
25
19
  }));
26
20
  try {
27
- const { adapterOas } = await dependencies.loadValidateModule();
21
+ const { adapterOas } = await import("@kubb/adapter-oas");
28
22
  const adapter = adapterOas();
29
23
  if (!adapter.validate) throw new Error("The loaded adapter does not support validation.");
30
24
  await adapter.validate(input, { throwOnError: true });
@@ -49,4 +43,4 @@ async function run({ input, version }, dependencies = { loadValidateModule }) {
49
43
  //#endregion
50
44
  exports.run = run;
51
45
 
52
- //# sourceMappingURL=run-DYkciQ4u.cjs.map
46
+ //# sourceMappingURL=run-DYzUPE7Z.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-DYzUPE7Z.cjs","names":["process","Telemetry","getErrorMessage"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { getErrorMessage } from '@internals/utils'\nimport { Telemetry } from '../../Telemetry.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, version }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'validate', kubbVersion: version, hrStart, status }))\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n const adapter = adapterOas()\n if (!adapter.validate) {\n throw new Error('The loaded adapter does not support validation.')\n }\n\n await adapter.validate(input, { throwOnError: true })\n await report('success')\n\n console.log('✅ Validation success')\n } catch (error) {\n await report('failed')\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(getErrorMessage(error))\n\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;AAoBA,eAAsB,IAAI,EAAE,OAAO,WAA2C;CAC5E,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiCC,kBAAAA,UAAU,KAAKA,kBAAAA,UAAU,MAAM;EAAE,SAAS;EAAY,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE/I,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,MAAM,iDAAiD;EAGnE,MAAM,QAAQ,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACpD,MAAM,OAAO,SAAS;EAEtB,QAAQ,IAAI,sBAAsB;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,IAAI,iBAAiB,SAAS,qBAAqB,KAAK,MAAM,OAAO,GAAG;GACtE,QAAQ,OAAA,GAAA,UAAA,UAAA,CAAgB,OAAO,iDAAiD,CAAC;GACjF,QAAQ,MAAM,EAAE;GAChB,QAAQ,MAAM,kBAAkB;GAChC,QAAQ,OAAA,GAAA,UAAA,UAAA,CAAgB,QAAQ,iCAAiC,CAAC;GAClE,QAAQ,OAAA,GAAA,UAAA,UAAA,CAAgB,QAAQ,QAAQ,CAAC;GACzC,QAAQ,OAAA,GAAA,UAAA,UAAA,CAAgB,QAAQ,kCAAkC,CAAC;GACnE,QAAQ,MAAM,EAAE;EAClB;EACA,QAAQ,MAAM,qBAAqB;EACnC,QAAQ,MAAMC,eAAAA,gBAAgB,KAAK,CAAC;EAEpC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,9 +1,9 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { t as detectPackageManager } from "./tools-D0UogMU3.js";
2
+ import { t as detectPackageManager } from "./tools-B23ltmWP.js";
3
3
  import { styleText } from "node:util";
4
+ import process from "node:process";
4
5
  import fs from "node:fs";
5
6
  import path from "node:path";
6
- import process from "node:process";
7
7
  import * as clack from "@clack/prompts";
8
8
  import { x } from "tinyexec";
9
9
  //#region ../../internals/shared/src/constants.ts
@@ -286,4 +286,4 @@ async function run({ yes, version, input: inputFlag, output: outputFlag, plugins
286
286
  //#endregion
287
287
  export { run };
288
288
 
289
- //# sourceMappingURL=run-44Zxh8Ec.js.map
289
+ //# sourceMappingURL=run-yMRylOST.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-yMRylOST.js","names":[],"sources":["../../../internals/shared/src/constants.ts","../../../internals/shared/src/init.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import type { PluginOption } from './types.ts'\n\nexport const KUBB_CONFIG_FILENAME = 'kubb.config.ts' as const\n\nexport const initDefaults = {\n inputPath: './openapi.yaml',\n outputPath: './src/gen',\n plugins: ['plugin-ts'],\n} as const\n\nexport const availablePlugins: Array<PluginOption> = [\n {\n value: 'plugin-ts',\n label: 'TypeScript',\n hint: 'Recommended',\n packageName: '@kubb/plugin-ts',\n importName: 'pluginTs',\n category: 'types',\n },\n {\n value: 'plugin-axios',\n label: 'Axios Client',\n packageName: '@kubb/plugin-axios',\n importName: 'pluginAxios',\n category: 'client',\n },\n {\n value: 'plugin-fetch',\n label: 'Fetch Client',\n packageName: '@kubb/plugin-fetch',\n importName: 'pluginFetch',\n category: 'client',\n },\n {\n value: 'plugin-react-query',\n label: 'React Query / TanStack Query',\n packageName: '@kubb/plugin-react-query',\n importName: 'pluginReactQuery',\n category: 'framework',\n },\n {\n value: 'plugin-vue-query',\n label: 'Vue Query',\n packageName: '@kubb/plugin-vue-query',\n importName: 'pluginVueQuery',\n category: 'framework',\n },\n {\n value: 'plugin-zod',\n label: 'Zod Schemas',\n packageName: '@kubb/plugin-zod',\n importName: 'pluginZod',\n category: 'validation',\n },\n {\n value: 'plugin-faker',\n label: 'Faker.js Mocks',\n packageName: '@kubb/plugin-faker',\n importName: 'pluginFaker',\n category: 'mocks',\n },\n {\n value: 'plugin-msw',\n label: 'MSW Handlers',\n packageName: '@kubb/plugin-msw',\n importName: 'pluginMsw',\n category: 'mocks',\n },\n {\n value: 'plugin-cypress',\n label: 'Cypress Tests',\n packageName: '@kubb/plugin-cypress',\n importName: 'pluginCypress',\n category: 'testing',\n },\n {\n value: 'plugin-mcp',\n label: 'MCP Server (AI / Model Context Protocol)',\n packageName: '@kubb/plugin-mcp',\n importName: 'pluginMcp',\n category: 'ai',\n },\n {\n value: 'plugin-redoc',\n label: 'ReDoc Documentation',\n packageName: '@kubb/plugin-redoc',\n importName: 'pluginRedoc',\n category: 'documentation',\n },\n]\n","import type { PluginOption } from './types.ts'\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb'\n${imports}\n\nexport default defineConfig({\n root: '.',\n input: {\n path: '${inputPath}',\n },\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { availablePlugins, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, type PluginOption } from '@internals/shared'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n clack.intro(styleText('bgCyan', styleText('black', ' Kubb Init ')))\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n clack.log.info(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n clack.log.info(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = clack.spinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n clack.log.info(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const requested = pluginsFlag\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean)\n const plugins = availablePlugins.filter((p) => requested.includes(p.value))\n if (plugins.length === 0) {\n clack.log.warn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n clack.log.info(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n clack.log.info(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages\n const packagesToInstall = ['kubb', ...selectedPlugins.map((p) => p.packageName)]\n\n const spinner = clack.spinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await installPackages(packagesToInstall, packageManager, cwd)\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = clack.spinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await fs.promises.writeFile(configPath, configContent, 'utf-8')\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n clack.outro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n clack.log.error(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n clack.log.error(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;AAEA,MAAa,uBAAuB;AAEpC,MAAa,eAAe;CAC1B,WAAW;CACX,YAAY;CACZ,SAAS,CAAC,WAAW;AACvB;AAEA,MAAa,mBAAwC;CACnD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;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M,MACJ,UAAU,SAAS,YAAY,IAC7B,SACA,UAAU,OAAO,aAAa,IAC9B,OACA,UAAU,QAAQ,2CAA2C,WAAW,IACxE,OACA,UAAU,QAAQ,4CAA4C,IAC9D,OACA,UAAU,QAAQ,iCAAiC,YAAY,IAC/D,SACA,UAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,UAAU,OAAO,yCAAyC,CAAC;EAC3E,IAAI,iBAAiB,OACnB,MAAM,IAAI,MAAM,MAAM,OAAO;EAE/B,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,8 +1,8 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { spawn } from "node:child_process";
3
2
  import { existsSync, readFileSync } from "node:fs";
4
3
  import { join } from "node:path";
5
- //#region ../../internals/utils/src/tools.ts
4
+ import { spawn } from "node:child_process";
5
+ //#region src/tools.ts
6
6
  /**
7
7
  * CLI command descriptors for each supported code formatter.
8
8
  *
@@ -149,4 +149,4 @@ function detectPackageManager(cwd = process.cwd()) {
149
149
  //#endregion
150
150
  export { linters as i, detectTool as n, formatters as r, detectPackageManager as t };
151
151
 
152
- //# sourceMappingURL=tools-D0UogMU3.js.map
152
+ //# sourceMappingURL=tools-B23ltmWP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-B23ltmWP.js","names":[],"sources":["../src/tools.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * CLI command descriptors for each supported code formatter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the formatter is not found.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const\n\n/**\n * CLI command descriptors for each supported linter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the linter is not found.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const\n\n/**\n * Resolves to `true` when running `tool --version` exits with code 0.\n */\nasync function isToolAvailable(tool: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(tool, ['--version'], { stdio: 'ignore' })\n\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed tool from `candidates`, checked in order, or `null` when none are found.\n *\n * Availability is probed by running `<tool> --version` and checking for a zero exit code.\n *\n * @example\n * ```ts\n * const formatter = await detectTool(['oxfmt', 'biome', 'prettier'] as const)\n * const linter = await detectTool(['oxlint', 'biome', 'eslint'] as const)\n * ```\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const tool of candidates) {\n if (await isToolAvailable(tool)) {\n return tool\n }\n }\n\n return null\n}\n\n/**\n * Supported package manager identifiers.\n *\n * @example\n * ```ts\n * const pm: PackageManagerName = 'pnpm'\n * ```\n */\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\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 *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return pack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,UAAU;EACV,gBAAgB,CAAC,WAAW,YAAY;CAC1C;AACF;;;;;;;;;;;;AAuBA,SAAgB,qBAAqB,MAAc,QAAQ,IAAI,GAAuB;CACpF,MAAM,kBAAkB,KAAK,KAAK,cAAc;CAChD,IAAI,WAAW,eAAe,GAC5B,IAAI;EAEF,MAAM,UADc,KAAK,MAAM,aAAa,iBAAiB,OAAO,CAC1C,CAAC,CAAC;EAC5B,IAAI,OAAO,YAAY,UAAU;GAC/B,MAAM,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC;GAChC,IAAI,QAAQ,QAAQ,iBAClB,OAAO,gBAAgB;EAE3B;CACF,QAAQ,CAER;CAGF,KAAK,MAAM,MAAM,OAAO,OAAO,eAAe,GAC5C,IAAI,WAAW,KAAK,KAAK,GAAG,QAAQ,CAAC,GACnC,OAAO;CAIX,OAAO,gBAAgB;AACzB"}
@@ -1,8 +1,8 @@
1
1
  require("./rolldown-runtime-Bx3C2hgW.cjs");
2
- let node_child_process = require("node:child_process");
3
2
  let node_fs = require("node:fs");
4
3
  let node_path = require("node:path");
5
- //#region ../../internals/utils/src/tools.ts
4
+ let node_child_process = require("node:child_process");
5
+ //#region src/tools.ts
6
6
  /**
7
7
  * CLI command descriptors for each supported code formatter.
8
8
  *
@@ -172,4 +172,4 @@ Object.defineProperty(exports, "linters", {
172
172
  }
173
173
  });
174
174
 
175
- //# sourceMappingURL=tools-CZT9wSA6.cjs.map
175
+ //# sourceMappingURL=tools-CeIABV0T.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-CeIABV0T.cjs","names":[],"sources":["../src/tools.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * CLI command descriptors for each supported code formatter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the formatter is not found.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const\n\n/**\n * CLI command descriptors for each supported linter.\n *\n * Each entry contains the executable `command`, an `args` factory that maps an\n * output path to the correct argument list, and an `errorMessage` shown when\n * the linter is not found.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const\n\n/**\n * Resolves to `true` when running `tool --version` exits with code 0.\n */\nasync function isToolAvailable(tool: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(tool, ['--version'], { stdio: 'ignore' })\n\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed tool from `candidates`, checked in order, or `null` when none are found.\n *\n * Availability is probed by running `<tool> --version` and checking for a zero exit code.\n *\n * @example\n * ```ts\n * const formatter = await detectTool(['oxfmt', 'biome', 'prettier'] as const)\n * const linter = await detectTool(['oxlint', 'biome', 'eslint'] as const)\n * ```\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const tool of candidates) {\n if (await isToolAvailable(tool)) {\n return tool\n }\n }\n\n return null\n}\n\n/**\n * Supported package manager identifiers.\n *\n * @example\n * ```ts\n * const pm: PackageManagerName = 'pnpm'\n * ```\n */\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\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 *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,aAAa;CACxB,UAAU;EACR,SAAS;EACT,OAAO,eAAuB;GAAC;GAAoB;GAAW;EAAU;EACxE,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAU;GAAW;EAAU;EAC9D,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB,CAAC,UAAU;EACzC,cAAc;CAChB;AACF;;;;;;;;AASA,MAAa,UAAU;CACrB,QAAQ;EACN,SAAS;EACT,OAAO,eAAuB,CAAC,YAAY,OAAO;EAClD,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAQ;GAAS;EAAU;EAC1D,cAAc;CAChB;CACA,QAAQ;EACN,SAAS;EAET,OAAO,eAAuB;GAAC;GAAS;GAAe;EAAU;EACjE,cAAc;CAChB;AACF;;;;AAKA,eAAe,gBAAgB,MAAgC;CAC7D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAA,GAAA,mBAAA,MAAA,CAAc,MAAM,CAAC,WAAW,GAAG,EAAE,OAAO,SAAS,CAAC;EAE5D,MAAM,GAAG,UAAU,SAAS,QAAQ,SAAS,CAAC,CAAC;EAC/C,MAAM,GAAG,eAAe,QAAQ,KAAK,CAAC;CACxC,CAAC;AACH;;;;;;;;;;;;AAaA,eAAsB,WAAiC,YAAyD;CAC9G,KAAK,MAAM,QAAQ,YACjB,IAAI,MAAM,gBAAgB,IAAI,GAC5B,OAAO;CAIX,OAAO;AACT;;;;;;;;;;AAuCA,MAAM,kBAAkE;CACtE,MAAM;EACJ,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,MAAM;EACJ,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,WAAW,YAAY;CAC1C;AACF;;;;;;;;;;;;AAuBA,SAAgB,qBAAqB,MAAc,QAAQ,IAAI,GAAuB;CACpF,MAAM,mBAAA,GAAA,UAAA,KAAA,CAAuB,KAAK,cAAc;CAChD,KAAA,GAAA,QAAA,WAAA,CAAe,eAAe,GAC5B,IAAI;EAEF,MAAM,UADc,KAAK,OAAA,GAAA,QAAA,aAAA,CAAmB,iBAAiB,OAAO,CAC1C,CAAC,CAAC;EAC5B,IAAI,OAAO,YAAY,UAAU;GAC/B,MAAM,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC;GAChC,IAAI,QAAQ,QAAQ,iBAClB,OAAO,gBAAgB;EAE3B;CACF,QAAQ,CAER;CAGF,KAAK,MAAM,MAAM,OAAO,OAAO,eAAe,GAC5C,KAAA,GAAA,QAAA,WAAA,EAAA,GAAA,UAAA,KAAA,CAAoB,KAAK,GAAG,QAAQ,CAAC,GACnC,OAAO;CAIX,OAAO,gBAAgB;AACzB"}
@@ -1,21 +1,20 @@
1
1
  require("./rolldown-runtime-Bx3C2hgW.cjs");
2
- const require_defineCommand = require("./defineCommand-Bo3yZTWI.cjs");
3
- const require_package = require("./package-BBBrKion.cjs");
2
+ const require_package = require("./package-B57sF1X0.cjs");
4
3
  //#region src/commands/validate.ts
5
- const command = require_defineCommand.defineCommand({
4
+ const command = (0, require("gunshi").define)({
6
5
  name: "validate",
7
6
  description: "Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.",
8
- examples: ["kubb validate --input ./openapi.yaml", "kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json"],
9
- options: { input: {
7
+ examples: ["kubb validate --input ./openapi.yaml", "kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json"].join("\n"),
8
+ args: { input: {
10
9
  type: "string",
11
10
  description: "Path or URL to the OpenAPI/Swagger file to validate",
12
11
  short: "i",
13
12
  required: true
14
13
  } },
15
- async run({ values }) {
16
- const { run } = await Promise.resolve().then(() => require("./run-DYkciQ4u.cjs"));
14
+ async run(ctx) {
15
+ const { run } = await Promise.resolve().then(() => require("./run-DYzUPE7Z.cjs"));
17
16
  await run({
18
- input: values.input,
17
+ input: ctx.values.input,
19
18
  version: require_package.version
20
19
  });
21
20
  }
@@ -23,4 +22,4 @@ const command = require_defineCommand.defineCommand({
23
22
  //#endregion
24
23
  exports.command = command;
25
24
 
26
- //# sourceMappingURL=validate-CbWRcTMP.cjs.map
25
+ //# sourceMappingURL=validate-BTVjxR4L.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-BTVjxR4L.cjs","names":[],"sources":["../src/commands/validate.ts"],"sourcesContent":["import { define } from 'gunshi'\nimport { version } from '../../package.json'\n\nexport const command = define({\n name: 'validate',\n description:\n 'Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.',\n examples: ['kubb validate --input ./openapi.yaml', 'kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json'].join('\\n'),\n args: {\n input: {\n type: 'string',\n description: 'Path or URL to the OpenAPI/Swagger file to validate',\n short: 'i',\n required: true,\n },\n },\n async run(ctx) {\n const { run } = await import('../runners/validate/run.ts')\n\n await run({ input: ctx.values.input, version })\n },\n})\n"],"mappings":";;;AAGA,MAAa,WAAA,mBAAA,CAAA,CAAA,OAAA,CAAiB;CAC5B,MAAM;CACN,aACE;CACF,UAAU,CAAC,wCAAwC,wEAAwE,CAAC,CAAC,KAAK,IAAI;CACtI,MAAM,EACJ,OAAO;EACL,MAAM;EACN,aAAa;EACb,OAAO;EACP,UAAU;CACZ,EACF;CACA,MAAM,IAAI,KAAK;EACb,MAAM,EAAE,QAAQ,MAAA,QAAA,QAAA,CAAA,CAAA,WAAA,QAAM,oBAAA,CAAA;EAEtB,MAAM,IAAI;GAAE,OAAO,IAAI,OAAO;GAAO,SAAA,gBAAA;EAAQ,CAAC;CAChD;AACF,CAAC"}
@@ -1,21 +1,21 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { t as defineCommand } from "./defineCommand-DMEeqliP.js";
3
- import { t as version } from "./package-DSkZlfZS.js";
2
+ import { t as version } from "./package-CQbxcw7I.js";
3
+ import { define } from "gunshi";
4
4
  //#region src/commands/validate.ts
5
- const command = defineCommand({
5
+ const command = define({
6
6
  name: "validate",
7
7
  description: "Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.",
8
- examples: ["kubb validate --input ./openapi.yaml", "kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json"],
9
- options: { input: {
8
+ examples: ["kubb validate --input ./openapi.yaml", "kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json"].join("\n"),
9
+ args: { input: {
10
10
  type: "string",
11
11
  description: "Path or URL to the OpenAPI/Swagger file to validate",
12
12
  short: "i",
13
13
  required: true
14
14
  } },
15
- async run({ values }) {
16
- const { run } = await import("./run-CPBFfbI7.js");
15
+ async run(ctx) {
16
+ const { run } = await import("./run-BFhNcn8b.js");
17
17
  await run({
18
- input: values.input,
18
+ input: ctx.values.input,
19
19
  version
20
20
  });
21
21
  }
@@ -23,4 +23,4 @@ const command = defineCommand({
23
23
  //#endregion
24
24
  export { command };
25
25
 
26
- //# sourceMappingURL=validate-BMaesb7k.js.map
26
+ //# sourceMappingURL=validate-CZFmahWd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-CZFmahWd.js","names":[],"sources":["../src/commands/validate.ts"],"sourcesContent":["import { define } from 'gunshi'\nimport { version } from '../../package.json'\n\nexport const command = define({\n name: 'validate',\n description:\n 'Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.',\n examples: ['kubb validate --input ./openapi.yaml', 'kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json'].join('\\n'),\n args: {\n input: {\n type: 'string',\n description: 'Path or URL to the OpenAPI/Swagger file to validate',\n short: 'i',\n required: true,\n },\n },\n async run(ctx) {\n const { run } = await import('../runners/validate/run.ts')\n\n await run({ input: ctx.values.input, version })\n },\n})\n"],"mappings":";;;;AAGA,MAAa,UAAU,OAAO;CAC5B,MAAM;CACN,aACE;CACF,UAAU,CAAC,wCAAwC,wEAAwE,CAAC,CAAC,KAAK,IAAI;CACtI,MAAM,EACJ,OAAO;EACL,MAAM;EACN,aAAa;EACb,OAAO;EACP,UAAU;CACZ,EACF;CACA,MAAM,IAAI,KAAK;EACb,MAAM,EAAE,QAAQ,MAAM,OAAO;EAE7B,MAAM,IAAI;GAAE,OAAO,IAAI,OAAO;GAAO;EAAQ,CAAC;CAChD;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/cli",
3
- "version": "5.0.0-beta.82",
3
+ "version": "5.0.0-beta.85",
4
4
  "description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, and kubb mcp to manage the full code generation lifecycle.",
5
5
  "keywords": [
6
6
  "cli",
@@ -45,21 +45,22 @@
45
45
  "registry": "https://registry.npmjs.org/"
46
46
  },
47
47
  "dependencies": {
48
- "@clack/prompts": "^1.6.0",
48
+ "@clack/prompts": "^1.7.0",
49
49
  "chokidar": "^5.0.0",
50
+ "gunshi": "^0.35.1",
50
51
  "jiti": "^2.7.0",
51
52
  "tinyexec": "^1.2.4",
52
53
  "unconfig": "^7.5.0",
53
- "@kubb/core": "5.0.0-beta.82"
54
+ "@kubb/core": "5.0.0-beta.85"
54
55
  },
55
56
  "devDependencies": {
56
- "@internals/shared": "0.0.0",
57
57
  "@internals/utils": "0.0.0",
58
- "@kubb/adapter-oas": "5.0.0-beta.82"
58
+ "@internals/shared": "0.0.0",
59
+ "@kubb/adapter-oas": "5.0.0-beta.85"
59
60
  },
60
61
  "peerDependencies": {
61
- "@kubb/adapter-oas": "5.0.0-beta.82",
62
- "@kubb/mcp": "5.0.0-beta.82"
62
+ "@kubb/adapter-oas": "5.0.0-beta.85",
63
+ "@kubb/mcp": "5.0.0-beta.85"
63
64
  },
64
65
  "peerDependenciesMeta": {
65
66
  "@kubb/adapter-oas": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"Telemetry-jtbchpQE.cjs","names":["process","os"],"sources":["../../../internals/utils/src/env.ts","../../../internals/utils/src/runtime.ts","../src/constants.ts","../src/Telemetry.ts"],"sourcesContent":["/**\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 *\n * @example\n * ```ts\n * if (isCIEnvironment()) {\n * logger.level = 'error'\n * }\n * ```\n */\nexport function isCIEnvironment(): boolean {\n return !!(\n process.env.CI ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n\n/**\n * Returns `true` when the process has an interactive TTY with a valid terminal\n * width and is not running in CI.\n *\n * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,\n * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`\n * with a negative count and throw a `RangeError`). We therefore require a\n * positive column count before declaring the TTY usable.\n *\n * @example\n * ```ts\n * if (canUseTTY()) {\n * renderProgressBar()\n * }\n * ```\n */\nexport function canUseTTY(): boolean {\n return process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment()\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","/**\n * NPM registry endpoint used to check for @kubb/cli updates.\n */\nexport const KUBB_NPM_PACKAGE_URL = 'https://registry.npmjs.org/@kubb/cli/latest' as const\n\n/**\n * OpenTelemetry ingestion endpoint for anonymous usage telemetry.\n */\nexport const OTLP_ENDPOINT = 'https://otlp.kubb.dev' as const\n\n/**\n * Glob pattern for paths the file watcher ignores.\n */\nexport const WATCHER_IGNORED_PATHS = '**/{.git,node_modules}/**' as const\n\n/**\n * Flags that short-circuit execution (help and version). The telemetry notice is suppressed for these.\n */\nexport const QUIET_FLAGS = new Set<string>(['--help', '-h', '--version', '-v'])\n","import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { isCIEnvironment, runtime } from '@internals/utils'\nimport { OTLP_ENDPOINT } from './constants.ts'\n\n// OpenTelemetry OTLP JSON types\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/common/v1/common.proto\n\ntype OtlpStringValue = { stringValue: string }\ntype OtlpBoolValue = { boolValue: boolean }\ntype OtlpIntValue = { intValue: number }\ntype OtlpDoubleValue = { doubleValue: number }\ntype OtlpBytesValue = { bytesValue: string }\ntype OtlpArrayValue = { arrayValue: { values: Array<OtlpAnyValue> } }\ntype OtlpKvListValue = { kvlistValue: { values: Array<OtlpKeyValue> } }\n\ntype OtlpAnyValue = OtlpStringValue | OtlpBoolValue | OtlpIntValue | OtlpDoubleValue | OtlpBytesValue | OtlpArrayValue | OtlpKvListValue\n\ntype OtlpKeyValue = {\n key: string\n value: OtlpAnyValue\n}\n\ntype OtlpResource = {\n attributes: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpInstrumentationScope = {\n name: string\n version?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\n/**\n * @see https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto#L103\n */\ntype OtlpSpanKind = 0 | 1 | 2 | 3 | 4 | 5\n\n/**\n * Span status code.\n * - `0` is unset\n * - `1` is OK\n * - `2` is error\n */\ntype OtlpStatusCode = 0 | 1 | 2\n\ntype OtlpStatus = {\n code: OtlpStatusCode\n message?: string\n}\n\ntype OtlpSpan = {\n traceId: string\n spanId: string\n traceState?: string\n parentSpanId?: string\n name: string\n kind: OtlpSpanKind\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n events?: Array<OtlpSpanEvent>\n droppedEventsCount?: number\n links?: Array<OtlpSpanLink>\n droppedLinksCount?: number\n status?: OtlpStatus\n}\n\ntype OtlpSpanEvent = {\n timeUnixNano: string\n name: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpSpanLink = {\n traceId: string\n spanId: string\n traceState?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpScopeSpans = {\n scope: OtlpInstrumentationScope\n spans: Array<OtlpSpan>\n schemaUrl?: string\n}\n\ntype OtlpResourceSpans = {\n resource: OtlpResource\n scopeSpans: Array<OtlpScopeSpans>\n schemaUrl?: string\n}\n\n/**\n * Root payload sent to POST /v1/traces.\n */\ntype OtlpExportTraceServiceRequest = {\n resourceSpans: Array<OtlpResourceSpans>\n}\n\n/**\n * Anonymous plugin name and options snapshot sent with each telemetry event.\n */\nexport type TelemetryPlugin = {\n /**\n * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.\n */\n name: string\n /**\n * Anonymized snapshot of the plugin options. Values are included but cannot be traced back to a user.\n */\n options: Record<string, unknown>\n}\n\n/**\n * Anonymous snapshot of a single Kubb run, built by {@link Telemetry.build} and sent by {@link Telemetry.send}.\n */\nexport type TelemetryEvent = {\n command: string\n kubbVersion: string\n /**\n * Major version of Node that executed the run, e.g. `'22'`.\n */\n nodeVersion: string\n /**\n * Name of the JavaScript runtime that executed the run, `'bun'`, `'deno'`, or `'node'`.\n */\n runtime: string\n /**\n * Major version of the active runtime, e.g. `'1'` under Bun or `'22'` under Node.\n */\n runtimeVersion: string\n platform: string\n ci: boolean\n plugins: Array<TelemetryPlugin>\n duration: number\n filesCreated: number\n status: 'success' | 'failed'\n}\n\n/**\n * Anonymous OTLP usage telemetry for a Kubb run. The API is static, so call it as `Telemetry.build(...)`\n * and `Telemetry.send(...)`. No file paths, OpenAPI specs, or secrets are sent, and sending fails\n * silently so a failed request never breaks the run.\n */\nexport class Telemetry {\n /**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\n static get isDisabled(): boolean {\n return (\n process.env['DO_NOT_TRACK'] === '1' ||\n process.env['DO_NOT_TRACK'] === 'true' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === '1' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === 'true'\n )\n }\n\n /**\n * Build an anonymous telemetry payload from a completed generation run.\n */\n static build(options: {\n command: 'generate' | 'mcp' | 'validate' | 'agent'\n kubbVersion: string\n plugins?: Array<TelemetryPlugin>\n hrStart: [number, number]\n filesCreated?: number\n status: 'success' | 'failed'\n }): TelemetryEvent {\n const [seconds, nanoseconds] = process.hrtime(options.hrStart)\n const duration = Math.round(seconds * 1000 + nanoseconds / 1e6)\n\n return {\n command: options.command,\n kubbVersion: options.kubbVersion,\n nodeVersion: process.versions.node.split('.')[0] as string,\n runtime: runtime.name,\n runtimeVersion: runtime.version.split('.')[0] as string,\n platform: os.platform(),\n ci: isCIEnvironment(),\n plugins: options.plugins ?? [],\n duration,\n filesCreated: options.filesCreated ?? 0,\n status: options.status,\n }\n }\n\n /**\n * Convert a {@link TelemetryEvent} into an OTLP-compatible JSON trace payload.\n *\n * @see https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\n static buildOtlpPayload(event: TelemetryEvent): OtlpExportTraceServiceRequest {\n const traceId = randomBytes(16).toString('hex')\n const spanId = randomBytes(8).toString('hex')\n const endTimeNs = BigInt(Date.now()) * 1_000_000n\n const startTimeNs = endTimeNs - BigInt(event.duration) * 1_000_000n\n\n const attributes: Array<OtlpKeyValue> = [\n { key: 'kubb.command', value: { stringValue: event.command } },\n { key: 'kubb.version', value: { stringValue: event.kubbVersion } },\n { key: 'kubb.node_version', value: { stringValue: event.nodeVersion } },\n { key: 'kubb.runtime', value: { stringValue: event.runtime } },\n { key: 'kubb.runtime_version', value: { stringValue: event.runtimeVersion } },\n { key: 'kubb.platform', value: { stringValue: event.platform } },\n { key: 'kubb.ci', value: { boolValue: event.ci } },\n { key: 'kubb.files_created', value: { intValue: event.filesCreated } },\n { key: 'kubb.status', value: { stringValue: event.status } },\n {\n key: 'kubb.plugins',\n value: {\n arrayValue: {\n values: event.plugins.map(\n (p): OtlpKvListValue => ({\n kvlistValue: {\n values: [\n { key: 'name', value: { stringValue: p.name } },\n {\n key: 'options',\n value: {\n stringValue: JSON.stringify({\n ...p.options,\n usedEnumNames: undefined,\n }),\n },\n },\n ],\n },\n }),\n ),\n },\n },\n },\n ]\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb-core' } },\n {\n key: 'service.version',\n value: { stringValue: event.kubbVersion },\n },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-core', version: event.kubbVersion },\n spans: [\n {\n traceId,\n spanId,\n name: event.command,\n kind: 1 satisfies OtlpSpanKind,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: (event.status === 'success' ? 1 : 2) satisfies OtlpStatusCode,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n }\n\n /**\n * Send an anonymous telemetry event to the Kubb OTLP endpoint. Respects `DO_NOT_TRACK` and\n * `KUBB_DISABLE_TELEMETRY`, and fails silently so telemetry never interrupts a run.\n */\n static async send(event: TelemetryEvent): Promise<void> {\n if (Telemetry.isDisabled) {\n return\n }\n\n try {\n await fetch(`${OTLP_ENDPOINT}/v1/traces`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Kubb-Telemetry-Version': '1',\n 'Kubb-Telemetry-Source': 'kubb-core',\n },\n body: JSON.stringify(Telemetry.buildOtlpPayload(event)),\n signal: AbortSignal.timeout(5_000),\n })\n }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