@kubb/cli 5.5.3 → 5.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Telemetry-BgVmgqiW.js → Telemetry-CvAyhsKS.js} +2 -2
- package/dist/{Telemetry-BgVmgqiW.js.map → Telemetry-CvAyhsKS.js.map} +1 -1
- package/dist/{Telemetry-BGfj0cEE.cjs → Telemetry-n_kUNSrX.cjs} +2 -2
- package/dist/{Telemetry-BGfj0cEE.cjs.map → Telemetry-n_kUNSrX.cjs.map} +1 -1
- package/dist/{agent-BPqs9VRj.cjs → agent-DiB4CRre.cjs} +4 -2
- package/dist/agent-DiB4CRre.cjs.map +1 -0
- package/dist/{agent-w0Hlq4mG.js → agent-yA5vrXJB.js} +4 -2
- package/dist/agent-yA5vrXJB.js.map +1 -0
- package/dist/{background-jYe6T1xA.cjs → background-BYXeahB6.cjs} +2 -2
- package/dist/{background-jYe6T1xA.cjs.map → background-BYXeahB6.cjs.map} +1 -1
- package/dist/background-C6vo0wKq.js +2 -0
- package/dist/{background-CWFFlm4o.js → background-DFF1AApF.js} +2 -2
- package/dist/{background-CWFFlm4o.js.map → background-DFF1AApF.js.map} +1 -1
- package/dist/{connect-gJ6ZRAzK.js → connect-8DMnVD4a.js} +2 -2
- package/dist/{connect-gJ6ZRAzK.js.map → connect-8DMnVD4a.js.map} +1 -1
- package/dist/{connect-DD9E5xID.cjs → connect-DGGCyVkT.cjs} +2 -2
- package/dist/{connect-DD9E5xID.cjs.map → connect-DGGCyVkT.cjs.map} +1 -1
- package/dist/{generate-DyRXvcxe.cjs → generate-BdVtr-Ih.cjs} +2 -2
- package/dist/{generate-DyRXvcxe.cjs.map → generate-BdVtr-Ih.cjs.map} +1 -1
- package/dist/{generate-BInRHip9.js → generate-EeLzy7nF.js} +2 -2
- package/dist/{generate-BInRHip9.js.map → generate-EeLzy7nF.js.map} +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.js +8 -8
- package/dist/{init-CnZ7p4Vg.js → init-CxEsiTUA.js} +3 -3
- package/dist/{init-CnZ7p4Vg.js.map → init-CxEsiTUA.js.map} +1 -1
- package/dist/{init-CVviBhG3.cjs → init-Dpko3KuM.cjs} +3 -3
- package/dist/{init-CVviBhG3.cjs.map → init-Dpko3KuM.cjs.map} +1 -1
- package/dist/{login-Bbbg2s8l.js → login-BpMNY0lG.js} +2 -2
- package/dist/{login-Bbbg2s8l.js.map → login-BpMNY0lG.js.map} +1 -1
- package/dist/{login-Cr4stnxS.cjs → login-vLd_Hyha.cjs} +2 -2
- package/dist/{login-Cr4stnxS.cjs.map → login-vLd_Hyha.cjs.map} +1 -1
- package/dist/{logout-RxxQZeWV.js → logout-CTkmUoN-.js} +3 -3
- package/dist/{logout-RxxQZeWV.js.map → logout-CTkmUoN-.js.map} +1 -1
- package/dist/{logout-CZB5wqbv.cjs → logout-zwyy8spm.cjs} +3 -3
- package/dist/{logout-CZB5wqbv.cjs.map → logout-zwyy8spm.cjs.map} +1 -1
- package/dist/{output-9qUFmWFq.cjs → output-CVLosNZq.cjs} +2 -2
- package/dist/{output-9qUFmWFq.cjs.map → output-CVLosNZq.cjs.map} +1 -1
- package/dist/{output-Dkoh9Ig6.js → output-FDo-db-w.js} +2 -2
- package/dist/{output-Dkoh9Ig6.js.map → output-FDo-db-w.js.map} +1 -1
- package/dist/{package-g1KvvYSm.cjs → package-BUJ-63vs.cjs} +2 -2
- package/dist/package-BUJ-63vs.cjs.map +1 -0
- package/dist/package-Ojd_aa3n.js +6 -0
- package/dist/package-Ojd_aa3n.js.map +1 -0
- package/dist/{run-BbY1YILf.js → run-BArG5Ae4.js} +3 -3
- package/dist/{run-BbY1YILf.js.map → run-BArG5Ae4.js.map} +1 -1
- package/dist/{run-Dl4mj2BE.js → run-BJZ76KFh.js} +13 -7
- package/dist/run-BJZ76KFh.js.map +1 -0
- package/dist/{run-BhRWMu9D.cjs → run-C-jBKNbI.cjs} +9 -9
- package/dist/run-C-jBKNbI.cjs.map +1 -0
- package/dist/{run-BufW4vEp.cjs → run-CYhgEL0t.cjs} +7 -7
- package/dist/{run-BufW4vEp.cjs.map → run-CYhgEL0t.cjs.map} +1 -1
- package/dist/{run-CDyUAifJ.cjs → run-Cq918oF2.cjs} +12 -6
- package/dist/run-Cq918oF2.cjs.map +1 -0
- package/dist/{run-DPrihroK.cjs → run-Ct6V14Pb.cjs} +3 -3
- package/dist/{run-DPrihroK.cjs.map → run-Ct6V14Pb.cjs.map} +1 -1
- package/dist/{run--9Y1EUyV.cjs → run-Ctlbe9el.cjs} +3 -3
- package/dist/{run--9Y1EUyV.cjs.map → run-Ctlbe9el.cjs.map} +1 -1
- package/dist/{run-CxR5Zknq.js → run-DCGh2Fj4.js} +3 -3
- package/dist/{run-CxR5Zknq.js.map → run-DCGh2Fj4.js.map} +1 -1
- package/dist/{run-BH26mNIp.js → run-Dn8HVjnM.js} +9 -9
- package/dist/run-Dn8HVjnM.js.map +1 -0
- package/dist/{run-CQVaplUK.js → run-xFtD6VJU.js} +7 -7
- package/dist/{run-CQVaplUK.js.map → run-xFtD6VJU.js.map} +1 -1
- package/dist/{snapshot-DaFn9yiC.js → snapshot-Cl3jveFD.js} +4 -4
- package/dist/{snapshot-DaFn9yiC.js.map → snapshot-Cl3jveFD.js.map} +1 -1
- package/dist/{snapshot-CgX3BGck.cjs → snapshot-D6ameNUn.cjs} +4 -4
- package/dist/{snapshot-CgX3BGck.cjs.map → snapshot-D6ameNUn.cjs.map} +1 -1
- package/dist/{start-BS92Ivbv.cjs → start-BPtzQP_Q.cjs} +3 -3
- package/dist/{start-BS92Ivbv.cjs.map → start-BPtzQP_Q.cjs.map} +1 -1
- package/dist/{start-D_9wyV-T.js → start-DdPBi6sG.js} +3 -3
- package/dist/{start-D_9wyV-T.js.map → start-DdPBi6sG.js.map} +1 -1
- package/dist/{status-DtpmPN0R.js → status-DOoqWoSs.js} +3 -3
- package/dist/{status-DtpmPN0R.js.map → status-DOoqWoSs.js.map} +1 -1
- package/dist/{status-DgdCvE9X.cjs → status-G9jhCLnC.cjs} +3 -3
- package/dist/{status-DgdCvE9X.cjs.map → status-G9jhCLnC.cjs.map} +1 -1
- package/dist/{stop-Dfqcy0ew.js → stop-BId6tXES.js} +2 -2
- package/dist/{stop-Dfqcy0ew.js.map → stop-BId6tXES.js.map} +1 -1
- package/dist/{stop-DWZyFXiX.cjs → stop-RWNwCW4c.cjs} +2 -2
- package/dist/{stop-DWZyFXiX.cjs.map → stop-RWNwCW4c.cjs.map} +1 -1
- package/dist/{studio-CeFmDSDf.cjs → studio-Be5-0N-F.cjs} +9 -9
- package/dist/{studio-CeFmDSDf.cjs.map → studio-Be5-0N-F.cjs.map} +1 -1
- package/dist/{studio-CHijB7Hx.js → studio-Ds88eHQV.js} +9 -9
- package/dist/{studio-CHijB7Hx.js.map → studio-Ds88eHQV.js.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/dist/{utils-Df1bph_y.js → utils-8Nb5AjvE.js} +9 -11
- package/dist/utils-8Nb5AjvE.js.map +1 -0
- package/dist/{utils-X_TeMQxy.cjs → utils-dyQmM0lJ.cjs} +9 -11
- package/dist/utils-dyQmM0lJ.cjs.map +1 -0
- package/package.json +7 -7
- package/dist/agent-BPqs9VRj.cjs.map +0 -1
- package/dist/agent-w0Hlq4mG.js.map +0 -1
- package/dist/background-B5-JmKlV.js +0 -2
- package/dist/package-DIx38T_A.js +0 -6
- package/dist/package-DIx38T_A.js.map +0 -1
- package/dist/package-g1KvvYSm.cjs.map +0 -1
- package/dist/run-BH26mNIp.js.map +0 -1
- package/dist/run-BhRWMu9D.cjs.map +0 -1
- package/dist/run-CDyUAifJ.cjs.map +0 -1
- package/dist/run-Dl4mj2BE.js.map +0 -1
- package/dist/utils-Df1bph_y.js.map +0 -1
- package/dist/utils-X_TeMQxy.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-dyQmM0lJ.cjs","names":["spawn","logLevelMap","process","formatMsWithColor","getElapsedMs","styleText","Diagnostics","formatMs","relative","clack","styleText","logLevelMap","styleText","formatMs","getElapsedMs","process","canUseTTY","getAgentName","createCliReporter","jiti","createJiti","resolve","basename","loadConfig","dirname","process","isValid","isGreaterThan","truncate","randomUUID","x","styleText","NonZeroExitError","toError","WATCHER_IGNORED_PATHS","URL_WATCHER_TIMEOUT_MS","URL_WATCHER_INTERVAL_MS"],"sources":["../../../internals/utils/src/tools.ts","../src/loggers/createLogger.ts","../src/loggers/clackLogger.ts","../src/loggers/plainLogger.ts","../src/loggers/utils.ts","../../../internals/shared/src/loader.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\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 satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\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 satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH and answers `--version` with a zero exit.\n */\nexport function isToolAvailable(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(name, ['--version'], { stdio: 'ignore' })\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate)) {\n return candidate\n }\n }\n\n return null\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 */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport { Diagnostics, logLevel as logLevelMap } from '@kubb/core'\nimport { formatMsWithColor } from './banner.ts'\nimport type { LoggerContext, LoggerHandle, LoggerOptions, LoggerWriter, LogStatus, WriterProgress, WriterSpinner } from './defineLogger.ts'\nimport {\n buildProgressLine,\n createProgressCounters,\n formatCommandWithArgs,\n formatErrorFrames,\n formatMessage,\n formatVersions,\n getInputPath,\n pluralize,\n recordPluginResult,\n resetProgressCounters,\n} from './utils.ts'\n\n/**\n * One output phase while its step owns the line. A phase buffers what it is told, because a spinner\n * redraws over anything written under it, and prints the lot once it knows its own result.\n */\ntype Phase = {\n successLabel: string\n failureLabel: string\n /**\n * Whether each hook's own result is worth a line. Format and lint run one command, so the phase\n * result already says everything; the post-generate phase runs several.\n */\n showHookResults: boolean\n failed: boolean\n hrStart: [number, number]\n lines: Array<string>\n /**\n * Raw lines a hook printed, drawn outside the group.\n */\n output: Array<string>\n}\n\ntype StartPhaseOptions = {\n /**\n * Shown while the phase runs.\n */\n running: string\n success: string\n failure: string\n showHookResults?: boolean\n}\n\n/**\n * The three output phases, in the order the generate runner runs them.\n */\nconst PHASES = {\n format: { running: 'Formatting', success: 'Formatted', failure: 'Formatting failed' },\n lint: { running: 'Linting', success: 'Linted', failure: 'Linting failed' },\n hooks: {\n running: 'Running post-generate hooks',\n success: 'Post-generate hooks completed',\n failure: 'Post-generate hooks failed',\n showHookResults: true,\n },\n} as const satisfies Record<string, StartPhaseOptions>\n\n/**\n * Drops the blank lines a subprocess leaves at either end of its output, so its block does not open\n * or close on an empty row.\n */\nfunction trimBlankEdges(lines: ReadonlyArray<string>): Array<string> {\n const start = lines.findIndex((line) => line.trim())\n if (start === -1) {\n return []\n }\n\n return lines.slice(start, lines.findLastIndex((line) => line.trim()) + 1)\n}\n\n/**\n * Wires a {@link LoggerWriter} onto the run's hooks. This owns what a run says and in what order:\n * one group per config, a step over the plugin work, a progress bar for the writes, one step per\n * output phase, then the summary and the group's closing result. The writer only decides how each\n * line looks, so every logger reports the same run the same way.\n *\n * @example\n * ```ts\n * export const plainLogger = { name: 'plain', install: (context, options) => createLogger(writer)(context, options) }\n * ```\n */\nexport function createLogger(writer: LoggerWriter) {\n return function install(context: LoggerContext, options?: LoggerOptions): LoggerHandle {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const silent = logLevel <= logLevelMap.silent\n const state = {\n ...createProgressCounters(),\n spinner: null as WriterSpinner | null,\n progress: null as WriterProgress | null,\n hooks: new Map<string, { hrStart: [number, number]; lines: Array<string> }>(),\n /**\n * Plugin results held back while the generation step owns the line.\n */\n pluginLines: [] as Array<string>,\n phase: null as Phase | null,\n groupOpen: false,\n }\n\n function text(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n function startSpinner(message: string) {\n if (silent) {\n return\n }\n\n state.spinner = writer.spinner()\n state.spinner.start(text(message))\n }\n\n function stopSpinner(message?: string, status: LogStatus = 'success') {\n const spinner = state.spinner\n if (!spinner) {\n return\n }\n state.spinner = null\n\n if (message === undefined) {\n spinner.clear()\n return\n }\n if (status === 'failed') {\n spinner.error(text(message))\n return\n }\n spinner.stop(text(message))\n }\n\n function stopProgress(message?: string) {\n const progress = state.progress\n if (!progress) {\n return\n }\n state.progress = null\n progress.stop(message === undefined ? '' : text(message))\n }\n\n function startPhase({ running, success, failure, showHookResults = false }: StartPhaseOptions) {\n state.phase = { successLabel: success, failureLabel: failure, showHookResults, failed: false, hrStart: process.hrtime(), lines: [], output: [] }\n startSpinner(running)\n }\n\n function endPhase() {\n const phase = state.phase\n state.phase = null\n\n if (!phase || silent) {\n return\n }\n\n const duration = formatMsWithColor(getElapsedMs(phase.hrStart))\n\n stopSpinner(phase.failed ? `${phase.failureLabel} after ${duration}` : `${phase.successLabel} in ${duration}`, phase.failed ? 'failed' : 'success')\n\n if (phase.lines.length) {\n writer.block(phase.lines)\n }\n writeOutput(phase.output)\n }\n\n function writeOutput(lines: ReadonlyArray<string>) {\n const output = trimBlankEdges(lines)\n if (output.length) {\n writer.raw(output)\n }\n }\n\n // A run that throws before `kubb:generation:end` never reaches the summary, so the lifecycle\n // end calls this too rather than leave a group without its closing line.\n function closeGroup(status: LogStatus) {\n if (!state.groupOpen) {\n return\n }\n state.groupOpen = false\n\n stopSpinner()\n stopProgress()\n writer.groupEnd(status === 'failed' ? styleText('red', '✗ Generation failed') : styleText('green', '✓ Generation succeeded'))\n }\n\n function reset() {\n stopSpinner()\n stopProgress()\n resetProgressCounters(state)\n state.hooks.clear()\n state.pluginLines = []\n state.phase = null\n state.groupOpen = false\n }\n\n context.hook('kubb:info', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // Info carries something new (the auto-detected tool), so inside a phase it waits for the\n // phase to print rather than being spent on a frame the next one overwrites.\n if (state.phase) {\n state.phase.lines.push(line)\n return\n }\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.info(line)\n })\n\n context.hook('kubb:success', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('green', '✓'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // A phase step outlives the successes reported inside it, and its own result says the same\n // thing, so let the step carry them.\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.success(line)\n })\n\n context.hook('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n writer.warn(\n text([styleText('yellow', '⚠'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' ')),\n )\n })\n\n // Unguarded: a failure stays visible even at silent.\n context.hook('kubb:error', ({ error }) => {\n if (state.phase) {\n state.phase.failed = true\n }\n\n // The writer draws the error symbol, so the message goes in bare.\n if (state.spinner) {\n stopSpinner(error.message, 'failed')\n } else {\n writer.error(text(error.message))\n }\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (!frames) {\n return\n }\n\n writer.block(frames.frames.map((frame) => text(styleText('dim', frame))))\n if (frames.cause) {\n writer.block([styleText('dim', frames.cause.header), ...frames.cause.frames.map((frame) => text(` ${styleText('dim', frame)}`))])\n }\n })\n\n context.hook('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (silent && diagnostic.severity !== 'error') {\n return\n }\n\n stopSpinner()\n stopProgress()\n\n if (Diagnostics.isUpdate(diagnostic)) {\n writer.update(\n [`\\`v${diagnostic.currentVersion}\\` → \\`v${diagnostic.latestVersion}\\``, 'Run `npm install -g @kubb/cli` to update'],\n 'Update available for `Kubb`',\n )\n return\n }\n\n const { headline, details } = Diagnostics.format(diagnostic)\n writer.diagnostic([headline, ...details])\n })\n\n // A `kubb studio` session emits these on the same emitter as its generations, so one logger\n // renders the whole command. The socket opens without being awaited, hence the step.\n context.hook('studio:connecting', ({ url }) => {\n startSpinner(`Connecting to ${styleText('cyan', url)}`)\n })\n\n context.hook('studio:connected', ({ url, versions }) => {\n if (silent) {\n return\n }\n\n const line = `Connected to ${styleText('cyan', url)} ${styleText('dim', `(${formatVersions(versions)})`)}`\n\n if (state.spinner) {\n stopSpinner(line)\n return\n }\n writer.success(text(`✓ ${line}`))\n })\n\n context.hook('studio:ready', () => {\n if (silent) {\n return\n }\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:disconnected', ({ reason }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n stopSpinner()\n writer.warn(text(`⚠ Kubb Studio ended the session (${reason})`))\n })\n\n context.hook('studio:command:start', ({ command }) => {\n if (silent) {\n return\n }\n stopSpinner()\n writer.info(text(`Kubb Studio asked to ${styleText('bold', command)}`))\n })\n\n context.hook('studio:command:end', ({ command, info }) => {\n if (silent) {\n return\n }\n writer.success(text(`✓ Finished ${command}${info ? ` ${styleText('dim', `(${info})`)}` : ''}`))\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:reconnecting', ({ delayMs }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n writer.info(text(styleText('dim', `Retrying connection to Kubb Studio in ${formatMs(delayMs)}`)))\n })\n\n context.hook('studio:warn', ({ message, permission }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n const remedy = permission ? `; pass --${permission.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)} to allow it` : ''\n writer.warn(text(`⚠ ${message}${remedy}`))\n })\n\n // Unguarded, like `kubb:error`: a failure stays visible even at silent.\n context.hook('studio:error', ({ error }) => {\n if (state.spinner) {\n stopSpinner(error.message, 'failed')\n return\n }\n writer.error(text(error.message))\n })\n\n context.hook('kubb:lifecycle:start', () => {\n reset()\n })\n\n context.hook('kubb:generation:start', ({ config }) => {\n closeGroup('failed')\n reset()\n\n state.totalPlugins = config.plugins?.length ?? 0\n\n if (silent) {\n return\n }\n\n const inputPath = getInputPath(config)\n\n writer.group(text([styleText('bold', config.name ?? 'kubb'), inputPath ? styleText('dim', inputPath) : undefined].filter(Boolean).join(' ')))\n state.groupOpen = true\n\n startSpinner('Generating')\n })\n\n context.hook('kubb:plugin:start', ({ plugin }) => {\n if (silent) {\n return\n }\n state.spinner?.message(text(`Generating ${styleText('dim', plugin.name)}`))\n })\n\n // Buffered, not printed: a step redraws over anything written while it runs.\n context.hook('kubb:plugin:end', ({ plugin, duration, success }) => {\n if (silent) {\n return\n }\n\n recordPluginResult(state, success)\n state.pluginLines.push(text(`${plugin.name} ${success ? 'completed' : 'failed'} in ${formatMsWithColor(duration)}`))\n })\n\n context.hook('kubb:plugins:end', () => {\n if (silent) {\n return\n }\n\n const failed = state.failedPlugins > 0\n stopSpinner(buildProgressLine(state) ?? 'No plugins ran', failed ? 'failed' : 'success')\n\n if (state.pluginLines.length) {\n writer.block(state.pluginLines)\n state.pluginLines = []\n }\n })\n\n context.hook('kubb:files:processing:start', ({ files }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n state.totalFiles = files.length\n state.processedFiles = 0\n\n state.progress = writer.progress(files.length)\n state.progress.start(text(`Writing ${pluralize(files.length, 'file')}`))\n })\n\n context.hook('kubb:files:processing:update', ({ files }) => {\n if (silent) {\n return\n }\n\n for (const { file, config } of files) {\n state.processedFiles++\n state.progress?.advance(`Writing ${relative(config.root, file.path)}`)\n }\n })\n\n context.hook('kubb:files:processing:end', () => {\n if (silent) {\n return\n }\n stopProgress(`Wrote ${pluralize(state.processedFiles, 'file')}`)\n })\n\n context.hook('kubb:format:start', () => startPhase(PHASES.format))\n context.hook('kubb:format:end', endPhase)\n context.hook('kubb:lint:start', () => startPhase(PHASES.lint))\n context.hook('kubb:lint:end', endPhase)\n context.hook('kubb:hooks:start', () => startPhase(PHASES.hooks))\n context.hook('kubb:hooks:end', endPhase)\n\n context.hook('kubb:hook:start', ({ id }) => {\n if (silent || !id) {\n return\n }\n state.hooks.set(id, { hrStart: process.hrtime(), lines: [] })\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 (!silent) {\n context.hook('kubb:hook:line', ({ id, line }) => {\n const active = state.hooks.get(id)\n if (!active) {\n return\n }\n\n // A phase step redraws its own line, so its output waits until the phase ends.\n if (state.phase) {\n active.lines.push(line)\n return\n }\n writer.raw([line])\n })\n }\n\n context.hook('kubb:hook:end', ({ id, command, name, args, success, error, stdout, stderr }) => {\n if (!id) {\n return\n }\n\n if (!success && state.phase) {\n state.phase.failed = true\n }\n\n if (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.hooks.get(id)\n if (!active) {\n return\n }\n state.hooks.delete(id)\n\n const label = styleText('dim', name ?? formatCommandWithArgs(command, args))\n const reason = error?.message ? ` (${error.message})` : ''\n const result = success\n ? `${styleText('green', '✓')} ${label} in ${formatMsWithColor(getElapsedMs(active.hrStart))}`\n : `${styleText('red', '✗')} ${label} failed${reason}`\n\n const phase = state.phase\n if (phase) {\n if (phase.showHookResults || !success) {\n phase.lines.push(result)\n }\n phase.output.push(...active.lines)\n return\n }\n\n stopSpinner()\n writer.step(text(result))\n writeOutput(active.lines)\n })\n\n context.hook('kubb:generation:end', () => {\n stopSpinner()\n stopProgress()\n })\n\n context.hook('kubb:lifecycle:end', () => {\n closeGroup('failed')\n reset()\n })\n\n return {\n renderSummary(lines, { status }) {\n if (silent || !state.groupOpen) {\n return\n }\n\n closeGroup(status)\n writer.diagnostic([...lines])\n },\n }\n }\n}\n","import { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Draws with clack: a gutter bar per group, animated steps, and a progress bar for the writes.\n */\nconst writer: LoggerWriter = {\n group: (title) => clack.intro(title),\n groupEnd: (text) => clack.outro(text),\n step: (text) => clack.log.step(text, { spacing: 0 }),\n info: (text) => clack.log.info(text),\n success: (text) => clack.log.success(text),\n warn: (text) => clack.log.warn(text),\n error: (text) => clack.log.error(text),\n block: (lines) => clack.log.message(lines, { spacing: 0 }),\n // A subprocess's output is not Kubb's tree, so it goes out past clack and its gutter bar. The\n // step above it is already stopped by the time this runs.\n raw: (lines) => console.log(styleText('dim', lines.join('\\n'))),\n // The diagnostic carries its own code and indented rows, so clear clack's gutter and bar and let\n // the block stand on its own.\n diagnostic: (lines) => clack.log.message(lines, { symbol: '', secondarySymbol: '' }),\n update: (lines, title) =>\n clack.box(lines.join('\\n'), title, {\n width: 'auto',\n formatBorder: (border: string) => styleText('yellow', border),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n }),\n spinner() {\n const spinner = clack.spinner()\n\n return {\n start: (text) => spinner.start(text),\n message: (text) => spinner.message(text),\n clear: () => spinner.clear(),\n stop: (text) => spinner.stop(text),\n error: (text) => spinner.error(text),\n }\n },\n progress(max) {\n const bar = clack.progress({ style: 'block', max, size: 30 })\n\n return {\n start: (text) => bar.start(text),\n advance: (text) => bar.advance(1, text),\n stop: (text) => bar.stop(text),\n }\n },\n}\n\n/**\n * TTY logger for local development, with animated steps and progress bars.\n */\nexport const clackLogger = {\n name: 'clack',\n install: createLogger(writer),\n} satisfies Logger\n","import { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Prefixes that stand in for the symbols clack draws, so plain output reads the same way.\n */\nconst SYMBOLS = { info: 'ℹ', warn: '⚠', error: '✗', step: '◇' } as const\n\n/** Draws with one `write` call per line. Nothing animates, so a step prints at start and end. */\nfunction createWriter(write: (line: string) => void): LoggerWriter {\n return {\n group: write,\n groupEnd: write,\n step: (text) => write(`${SYMBOLS.step} ${text}`),\n info: write,\n success: write,\n warn: write,\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n block: (lines) => write(lines.join('\\n')),\n raw: (lines) => write(lines.join('\\n')),\n diagnostic: (lines) => write(lines.join('\\n')),\n update: (lines, title) => write([title, ...lines].join('\\n')),\n spinner: () => ({\n start: write,\n message: write,\n clear: () => {},\n stop: (text) => text && write(text),\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n }),\n progress: () => ({\n start: write,\n advance: write,\n stop: (text) => text && write(text),\n }),\n }\n}\n\n/** The plain logger writing through `write`, e.g. `console.error` so stdout carries only JSON. */\nexport function createPlainLogger(write: (line: string) => void) {\n return {\n name: 'plain',\n install: createLogger(createWriter(write)),\n } satisfies Logger\n}\n\n/**\n * Console adapter for non-TTY environments, and for an AI coding agent reading the output. Reports\n * the same run in the same order as `clackLogger`, without the animation.\n */\nexport const plainLogger = createPlainLogger((line) => console.log(line))\n","import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport type { Config, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport type { StudioConnectedContext } from '@kubb/studio'\nimport { getAgentName } from '../agent.ts'\nimport { canUseTTY } from '../utils/env.ts'\nimport type { Logger, LoggerContext, LoggerHandle, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/**\n * Display path for a config's input: the string form, or its `path` field when the input is an\n * object. Loggers show it alongside `Generation started`.\n */\nexport function getInputPath(config: Config): string | undefined {\n const { input } = config\n if (typeof input === 'string') return input\n return typeof input?.path === 'string' ? input.path : undefined\n}\n\n/**\n * Counts a noun, so a message never reads `1 files`.\n *\n * @example\n * `pluralize(1, 'config')` returns `'1 config'`\n */\nexport function pluralize(count: number, noun: string): string {\n return `${count} ${count === 1 ? noun : `${noun}s`}`\n}\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 * Renders the versions from a `studio:connected` event as one parenthetical. The runtime is listed\n * only when it differs from the host, and Studio's only when it sent one.\n */\nexport function formatVersions({ studio, kubb, agent }: StudioConnectedContext['versions']): string {\n return [`v${agent}`, kubb !== agent ? `runtime v${kubb}` : undefined, studio ? `Studio v${studio}` : undefined].filter(Boolean).join(', ')\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n */\nfunction toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\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 */\ntype 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 hook 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 const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('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 a reporter that renders the per-config summary through that logger, so the\n * summary lands inside the group the logger opened. The `json` reporter owns stdout, so the whole\n * `cli` reporter (live logger and summary) is skipped whenever `json` is among the reporters, even\n * if `cli` is also listed.\n */\nasync function setupReporters(\n context: LoggerContext,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): Promise<LoggerHandle | undefined> {\n let cliHandle: LoggerHandle | undefined\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 installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n // Spinners and cursor-movement escapes are hard for an AI coding agent to parse, even over a pseudo-TTY.\n const logger = forcedLogger ?? (canUseTTY() && !getAgentName() ? clackLogger : plainLogger)\n const handle = (await logger.install(context, { logLevel })) ?? undefined\n cliHandle = handle\n\n // The summary belongs inside the group the logger opened for this config, so hand the writing\n // to the logger rather than letting the reporter print alongside it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n\n return cliHandle\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 */\ntype 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 */\ntype 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 { randomUUID } from 'node:crypto'\nimport { basename, dirname, resolve } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createModuleLoader } from '@internals/shared'\nimport { toError, tokenize } from '@internals/utils'\nimport type { CLIOptions, Config, KubbHooks, PossibleConfig, PostGenerateCommand, Hookable } from '@kubb/core'\nimport { NonZeroExitError, x } from 'tinyexec'\nimport { type LoadConfigResult, type LoadConfigSource, loadConfig } from 'unconfig'\nimport { isGreaterThan, isValid, truncate } from 'verkit'\nimport { URL_WATCHER_INTERVAL_MS, URL_WATCHER_TIMEOUT_MS, 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 or URL that overrides `config.input` 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) => {\n const config: Config = { ...item, plugins: item.plugins ?? [] }\n return config\n }),\n }\n}\n\ntype RunPostGenerateOptions = {\n commands: Array<PostGenerateCommand>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Outcome of a single hook subprocess, returned by `runHook` alongside the\n * `kubb:hook:end` hook it emits for the loggers.\n */\ntype 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\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 if (!isValid(current) || !isValid(latest)) return false\n\n return isGreaterThan(truncate(latest, 'patch') as string, truncate(current, 'patch') as string)\n}\n\n/**\n * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's\n * outcome, so the caller can turn failures into diagnostics.\n */\nexport async function runPostGenerate({ commands, hooks }: RunPostGenerateOptions): Promise<Array<HookResult>> {\n const results: Array<HookResult> = []\n\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [cmd, ...args] = tokenize(command)\n if (!cmd) continue\n\n const hookId = randomUUID()\n const commandWithArgs = [cmd, ...args].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: cmd, name, args })\n results.push(await runHook({ id: hookId, command: cmd, name, args, commandWithArgs, hooks }))\n }\n\n return results\n}\n\ntype RunHookOptions = {\n id: string\n command: string\n name?: string\n args?: ReadonlyArray<string>\n commandWithArgs: string\n hooks: Hookable<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, name, args, commandWithArgs, hooks }: RunHookOptions): Promise<HookResult> {\n const emitEnd = async (result: HookResult): Promise<HookResult> => {\n await hooks.callHook('kubb:hook:end', { command, name, 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.callHook('kubb:hook:line', { id, line })\n }\n }\n\n await proc\n await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? 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 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\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\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body within the timeout. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, timeoutMs: number = URL_WATCHER_TIMEOUT_MS): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n try {\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)])\n const response = await fetch(url, { signal })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`)\n }\n const body = await response.text()\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n } catch {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n }\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n void poll()\n\n return stop\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,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;;;;AAKA,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,eAAu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U,QAAQ,oBAAoB,KAAK,CAAC,CAAC;GAE5E,IAAI,WAAW,aAAa,KAAA,GAC1B,SAAc;GAEhB,WAAW;EACb,QAAQ;GAEN,IAAI,CAAC,WAAW,CAAC,SAAS;IACxB,UAAU;IACV,IAAI,OAAA,GAAMA,UAAAA,UAAAA,CAAU,OAAO,gBAAgB,IAAI,kCAAkC,CAAC;GACpF;EACF;EACA,IAAI,CAAC,SACH,QAAQ,iBAAiB,KAAK,KAAK,GAAG,UAAU;CAEpD;CAEA,KAAU;CAEV,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/cli",
|
|
3
|
-
"version": "5.5.
|
|
3
|
+
"version": "5.5.5",
|
|
4
4
|
"description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb studio, and kubb mcp to manage the full code generation lifecycle.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@clack/prompts": "^1.8.1",
|
|
65
65
|
"@gunshi/plugin-dryrun": "^0.37.3",
|
|
66
|
-
"@kubb/core": "5.5.
|
|
66
|
+
"@kubb/core": "5.5.5",
|
|
67
67
|
"chokidar": "^5.0.0",
|
|
68
68
|
"gunshi": "^0.37.3",
|
|
69
69
|
"jiti": "^2.7.0",
|
|
@@ -74,13 +74,13 @@
|
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@internals/shared": "0.0.1",
|
|
76
76
|
"@internals/utils": "0.0.1",
|
|
77
|
-
"@kubb/adapter-oas": "5.5.
|
|
78
|
-
"@kubb/studio": "5.5.
|
|
77
|
+
"@kubb/adapter-oas": "5.5.5",
|
|
78
|
+
"@kubb/studio": "5.5.5"
|
|
79
79
|
},
|
|
80
80
|
"peerDependencies": {
|
|
81
|
-
"@kubb/adapter-oas": "5.5.
|
|
82
|
-
"@kubb/mcp": "5.5.
|
|
83
|
-
"@kubb/studio": "5.5.
|
|
81
|
+
"@kubb/adapter-oas": "5.5.5",
|
|
82
|
+
"@kubb/mcp": "5.5.5",
|
|
83
|
+
"@kubb/studio": "5.5.5"
|
|
84
84
|
},
|
|
85
85
|
"peerDependenciesMeta": {
|
|
86
86
|
"@kubb/adapter-oas": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-BPqs9VRj.cjs","names":["process","getAgentProfile"],"sources":["../../../internals/utils/src/isCIEnvironment.ts","../src/agent.ts"],"sourcesContent":["import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\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","import { getAgentProfile } from 'gunshi/agent'\n\n/**\n * Name of the AI coding agent driving this process, when one is detected (e.g. `'claude'`,\n * `'cursor'`). `undefined` when run by a human or an unrecognized caller.\n */\nexport function getAgentName(): string | undefined {\n const profile = getAgentProfile()\n return profile.isAgent ? profile.name : undefined\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,EACNA,aAAAA,QAAQ,IAAI,MACZA,aAAAA,QAAQ,IAAI,kBACZA,aAAAA,QAAQ,IAAI,aACZA,aAAAA,QAAQ,IAAI,0BACZA,aAAAA,QAAQ,IAAI,eACZA,aAAAA,QAAQ,IAAI,YACZA,aAAAA,QAAQ,IAAI,UACZA,aAAAA,QAAQ,IAAI,oBACZA,aAAAA,QAAQ,IAAI,aACZA,aAAAA,QAAQ,IAAI;AAEhB;;;;;;;ACZA,SAAgB,eAAmC;CACjD,MAAM,WAAA,GAAUC,aAAAA,gBAAAA,CAAgB;CAChC,OAAO,QAAQ,UAAU,QAAQ,OAAO,KAAA;AAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-w0Hlq4mG.js","names":[],"sources":["../../../internals/utils/src/isCIEnvironment.ts","../src/agent.ts"],"sourcesContent":["import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\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","import { getAgentProfile } from 'gunshi/agent'\n\n/**\n * Name of the AI coding agent driving this process, when one is detected (e.g. `'claude'`,\n * `'cursor'`). `undefined` when run by a human or an unrecognized caller.\n */\nexport function getAgentName(): string | undefined {\n const profile = getAgentProfile()\n return profile.isAgent ? profile.name : undefined\n}\n"],"mappings":";;;;;;;AAKA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,EACN,QAAQ,IAAI,MACZ,QAAQ,IAAI,kBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI,0BACZ,QAAQ,IAAI,eACZ,QAAQ,IAAI,YACZ,QAAQ,IAAI,UACZ,QAAQ,IAAI,oBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI;AAEhB;;;;;;;ACZA,SAAgB,eAAmC;CACjD,MAAM,UAAU,gBAAgB;CAChC,OAAO,QAAQ,UAAU,QAAQ,OAAO,KAAA;AAC1C"}
|
package/dist/package-DIx38T_A.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"package-DIx38T_A.js","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"package-g1KvvYSm.cjs","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
|
package/dist/run-BH26mNIp.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-BH26mNIp.js","names":["process","process"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\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/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\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","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 type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\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 * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\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, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: 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<NoInfer<T> | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${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 = createSpinner()\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 logInfo(`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 plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`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, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\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 = createSpinner()\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 dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\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 logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAO,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,MAAM,MADa,QAAQ,MAAM,WAAW,CAAC,GAAG,MACtB;CAE1B,OAAO,SAAS,KAAK,SAAU,SAAA,SAA6B,GAAG,KAA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,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,SAAS,UAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,SAAS,MAAM,OAAO;EAExB,UAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-BhRWMu9D.cjs","names":["availablePlugins","join","existsSync","readFileSync","process","fs","path","x","process","styleText","clack","createSpinner","initDefaults","availablePlugins","KUBB_PACKAGE_NAME","KUBB_CONFIG_FILENAME","path","fs"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\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/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\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","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 type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\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 * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\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, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: 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<NoInfer<T> | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${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 = createSpinner()\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 logInfo(`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 plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`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, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\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 = createSpinner()\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 dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\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 logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAOA,kBAAAA,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,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AAS,OAAO;EACd,eAAA,UAAA,GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,eAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-CDyUAifJ.cjs","names":["styleText","existsSync","logLevelMap","randomUUID","runHook","toError","process","memoryStorage","Diagnostics","formatters","detectTool","FORMATTER_PREFERENCE","linters","LINTER_PREFERENCE","runPostGenerate","createKubb","sendTelemetry","buildTelemetryEvent","version","KUBB_NPM_PACKAGE_URL","UPDATE_CHECK_TIMEOUT_MS","isNewerVersion","Hookable","createSpinner","getConfigs","path","setupReporters","cliReporter","selectReporters","pluralize","getInputKind","fetchUrlBody","logInfo","logError","startWatcher"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\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 { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { pluralize, selectReporters } from '../../loggers/utils.ts'\nimport { createSpinner, logBanner, logError, logInfo, logIntro, logOutro, logSpacer, logStep, logTip } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<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({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${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 tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.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 = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('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.callHook('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, dryRun = false } = options\n\n const hrStart = process.hrtime()\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\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 // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\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 dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<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, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\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\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const quiet = logLevel <= logLevelMap.silent || requestedNames.includes('json')\n\n if (!quiet) {\n logBanner(version)\n logIntro({ title: 'Configuration' })\n }\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 const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\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\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate(hooks)\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\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 const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,KAAA,GAAIA,UAAAA,UAAAA,CAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,QAAA,GAAOC,QAAAA,WAAAA,CAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,SAAA,GAAQD,UAAAA,UAAAA,CAAU,OAAO,YAAY;GAC3D,YAAYE,WAAAA,SAAY,OAAO,OAAA,GAAMF,UAAAA,UAAAA,CAAU,OAAO,UAAU,MAAM,KAAA;GACt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KAAO;KAAQ;KAAU;KAAO;IAAO,CAAC,GAC3D,YAAY;GAC9B,SAAS,aAAa;IACpB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO5B,eAAAA,QAAQ,WAAW,EAAE,CAAC;IAClE,YAAY;GACd;EAEJ;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAIzC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,WACvB,eAAA,OAAO;EAGT,IAAI,WACF,aAAA,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,SAAS,cAAc,EAAE,OAAOA,eAAAA,QAAQ,KAAK,EAAE,CAAC;EAC5D,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
package/dist/run-Dl4mj2BE.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-Dl4mj2BE.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\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 { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { pluralize, selectReporters } from '../../loggers/utils.ts'\nimport { createSpinner, logBanner, logError, logInfo, logIntro, logOutro, logSpacer, logStep, logTip } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<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({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${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 tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.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 = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('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.callHook('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, dryRun = false } = options\n\n const hrStart = process.hrtime()\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\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 // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\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 dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<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, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\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\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const quiet = logLevel <= logLevelMap.silent || requestedNames.includes('json')\n\n if (!quiet) {\n logBanner(version)\n logIntro({ title: 'Configuration' })\n }\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 const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\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\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate(hooks)\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\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 const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAA,YAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,IAAI,UAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,OAAO,WAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,QAAQ,UAAU,OAAO,YAAY;GAC3DA,cAAYC,SAAY,OAAO,MAAM,UAAU,OAAO,UAAU,MAAM,KAAA;GACtE;EACF,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;EA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