UNPKG

@kubb/cli

Version:

Command-line interface for Kubb, enabling easy generation of TypeScript, React-Query, Zod, and other code from OpenAPI specifications.

1 lines 97.9 kB
{"version":3,"file":"generate-C8gS4Z2F.cjs","names":["path","Writable","LogLevel","process","clack","LogLevel","LogLevel","LogLevel","process","LogLevel","formatters","path","linters","AsyncEventEmitter","PromiseManager","LogLevel","version","path","process"],"sources":["../src/utils/formatMsWithColor.ts","../src/utils/getIntro.ts","../src/utils/randomColor.ts","../src/utils/getSummary.ts","../src/utils/Writables.ts","../src/loggers/clackLogger.ts","../src/loggers/envDetection.ts","../src/loggers/fileSystemLogger.ts","../src/loggers/githubActionsLogger.ts","../src/loggers/plainLogger.ts","../src/loggers/utils.ts","../src/utils/executeHooks.ts","../src/runners/generate.ts","../src/utils/getCosmiConfig.ts","../src/utils/watcher.ts","../src/commands/generate.ts"],"sourcesContent":["import { styleText } from 'node:util'\nimport { formatMs } from '@kubb/core/utils'\n\n/**\n * Formats milliseconds with color based on duration thresholds:\n * - Green: <= 500ms\n * - Yellow: > 500ms and <= 1000ms\n * - Red: > 1000ms\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n\n if (ms <= 500) {\n return styleText('green', formatted)\n }\n\n if (ms <= 1000) {\n return styleText('yellow', formatted)\n }\n\n return styleText('red', formatted)\n}\n","import { styleText } from 'node:util'\n\n/**\n * ANSI True Color (24-bit) utilities for terminal output\n * Supports hex color codes without external dependencies like chalk\n */\n\n/**\n * Convert hex color to ANSI 24-bit true color escape sequence\n * @param color - Hex color code (with or without #), e.g., '#FF5500' or 'FF5500'\n * @returns Function that wraps text with the color\n */\nfunction hex(color: string): (text: string) => string {\n const cleanHex = color.replace('#', '')\n const r = Number.parseInt(cleanHex.slice(0, 2), 16)\n const g = Number.parseInt(cleanHex.slice(2, 4), 16)\n const b = Number.parseInt(cleanHex.slice(4, 6), 16)\n\n // Default to white (255) if parsing fails (NaN)\n const safeR = Number.isNaN(r) ? 255 : r\n const safeG = Number.isNaN(g) ? 255 : g\n const safeB = Number.isNaN(b) ? 255 : b\n\n return (text: string) => `\\x1b[38;2;${safeR};${safeG};${safeB}m${text}\\x1b[0m`\n}\n\nfunction hexToRgb(color: string) {\n const c = color.replace('#', '')\n return { r: Number.parseInt(c.slice(0, 2), 16), g: Number.parseInt(c.slice(2, 4), 16), b: Number.parseInt(c.slice(4, 6), 16) }\n}\n\nfunction gradient(colors: string[]) {\n return (text: string) => {\n const chars = [...text]\n return chars\n .map((char, i) => {\n const t = chars.length <= 1 ? 0 : i / (chars.length - 1)\n const seg = Math.min(Math.floor(t * (colors.length - 1)), colors.length - 2)\n const lt = t * (colors.length - 1) - seg\n const from = hexToRgb(colors[seg]!)\n const to = hexToRgb(colors[seg + 1]!)\n const r = Math.round(from.r + (to.r - from.r) * lt)\n const g = Math.round(from.g + (to.g - from.g) * lt)\n const b = Math.round(from.b + (to.b - from.b) * lt)\n return `\\x1b[38;2;${r};${g};${b}m${char}\\x1b[0m`\n })\n .join('')\n }\n}\n\n// Custom Color Palette for \"Wooden\" Depth\nconst colors = {\n lid: hex('#F55A17'), // Dark Wood\n woodTop: hex('#F5A217'), // Bright Orange (Light source)\n woodMid: hex('#F58517'), // Main Orange\n woodBase: hex('#B45309'), // Shadow Orange\n eye: hex('#FFFFFF'), // Deep Slate\n highlight: hex('#adadc6'), // Eye shine\n blush: hex('#FDA4AF'), // Soft Rose\n}\n\n/**\n * Generates the Kubb mascot face welcome message\n * @param version - The version string to display\n * @returns Formatted mascot face string\n */\nexport function getIntro({ title, description, version, areEyesOpen }: { title: string; description: string; version: string; areEyesOpen: boolean }): string {\n // Use gradient-string for the KUBB version text\n const kubbVersion = gradient(['#F58517', '#F5A217', '#F55A17'])(`KUBB v${version}`)\n\n const eyeTop = areEyesOpen ? colors.eye('█▀█') : colors.eye('───')\n const eyeBottom = areEyesOpen ? colors.eye('▀▀▀') : colors.eye('───')\n\n return `\n ${colors.lid('▄▄▄▄▄▄▄▄▄▄▄▄▄')}\n ${colors.woodTop('█ ')}${colors.highlight('▄▄')}${colors.woodTop(' ')}${colors.highlight('▄▄')}${colors.woodTop(' █')} ${kubbVersion}\n ${colors.woodMid('█ ')}${eyeTop}${colors.woodMid(' ')}${eyeTop}${colors.woodMid(' █')} ${styleText('gray', title)}\n ${colors.woodMid('█ ')}${eyeBottom}${colors.woodMid(' ')}${colors.blush('◡')}${colors.woodMid(' ')}${eyeBottom}${colors.woodMid(' █')} ${styleText('yellow', '➜')} ${styleText('white', description)}\n ${colors.woodBase('▀▀▀▀▀▀▀▀▀▀▀▀▀')}\n`\n}\n","import { createHash } from 'node:crypto'\nimport { styleText } from 'node:util'\n\nexport function randomColor(text?: string): 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' {\n if (!text) {\n return 'white'\n }\n\n const defaultColors = ['black', 'red', 'green', 'yellow', 'blue', 'red', 'green', 'magenta', 'cyan', 'gray'] as const\n const index = createHash('sha256').update(text).digest().readUInt32BE(0) % defaultColors.length\n\n return defaultColors[index] ?? 'white'\n}\n\nexport function randomCliColor(text?: string): string {\n if (!text) {\n return ''\n }\n\n const color = randomColor(text)\n\n return styleText(color, text)\n}\n","import path from 'node:path'\nimport { styleText } from 'node:util'\nimport type { Config, Plugin } from '@kubb/core'\nimport { formatHrtime } from '@kubb/core/utils'\nimport { randomCliColor } from './randomColor.ts'\n\ntype SummaryProps = {\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n status: 'success' | 'failed'\n hrStart: [number, number]\n filesCreated: number\n config: Config\n pluginTimings?: Map<string, number>\n}\n\nexport function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }: SummaryProps): string[] {\n const duration = formatHrtime(hrStart)\n\n const pluginsCount = config.plugins?.length || 0\n const successCount = pluginsCount - failedPlugins.size\n\n const meta = {\n plugins:\n status === 'success'\n ? `${styleText('green', `${successCount} successful`)}, ${pluginsCount} total`\n : `${styleText('green', `${successCount} successful`)}, ${styleText('red', `${failedPlugins.size} failed`)}, ${pluginsCount} total`,\n pluginsFailed: status === 'failed' ? [...failedPlugins]?.map(({ plugin }) => randomCliColor(plugin.name))?.join(', ') : undefined,\n filesCreated: filesCreated,\n time: styleText('green', duration),\n output: path.isAbsolute(config.root) ? path.resolve(config.root, config.output.path) : config.root,\n } as const\n\n const labels = {\n plugins: 'Plugins:',\n failed: 'Failed:',\n generated: 'Generated:',\n pluginTimings: 'Plugin Timings:',\n output: 'Output:',\n }\n const maxLength = Math.max(0, ...[...Object.values(labels), ...(pluginTimings ? Array.from(pluginTimings.keys()) : [])].map((s) => s.length))\n\n const summaryLines: string[] = []\n summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`)\n\n if (meta.pluginsFailed) {\n summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`)\n }\n\n summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`)\n\n if (pluginTimings && pluginTimings.size > 0) {\n const TIME_SCALE_DIVISOR = 100\n const MAX_BAR_LENGTH = 10\n\n const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1])\n\n if (sortedTimings.length > 0) {\n summaryLines.push(`${labels.pluginTimings}`)\n\n sortedTimings.forEach(([name, time]) => {\n const timeStr = time >= 1000 ? `${(time / 1000).toFixed(2)}s` : `${Math.round(time)}ms`\n const barLength = Math.min(Math.ceil(time / TIME_SCALE_DIVISOR), MAX_BAR_LENGTH)\n const bar = styleText('dim', '█'.repeat(barLength))\n\n summaryLines.push(`${styleText('dim', '•')} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`)\n })\n }\n }\n\n summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`)\n\n return summaryLines\n}\n","import type { WritableOptions } from 'node:stream'\nimport { Writable } from 'node:stream'\nimport { styleText } from 'node:util'\nimport type * as clack from '@clack/prompts'\n\nexport class ClackWritable extends Writable {\n taskLog: ReturnType<typeof clack.taskLog>\n constructor(taskLog: ReturnType<typeof clack.taskLog>, opts?: WritableOptions) {\n super(opts)\n\n this.taskLog = taskLog\n }\n _write(chunk: any, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n this.taskLog.message(`${styleText('dim', chunk?.toString())}`)\n callback()\n }\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { defineLogger, LogLevel } from '@kubb/core'\nimport { formatHrtime, formatMs } from '@kubb/core/utils'\nimport { type NonZeroExitError, x } from 'tinyexec'\nimport { formatMsWithColor } from '../utils/formatMsWithColor.ts'\nimport { getIntro } from '../utils/getIntro.ts'\nimport { getSummary } from '../utils/getSummary.ts'\nimport { ClackWritable } from '../utils/Writables.ts'\n\n/**\n * Clack adapter for local TTY environments\n * Provides a beautiful CLI UI with flat structure inspired by Claude's CLI patterns\n */\nexport const clackLogger = defineLogger({\n name: 'clack',\n install(context, options) {\n const logLevel = options?.logLevel || LogLevel.info\n const state = {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n spinner: clack.spinner(),\n isSpinning: false,\n activeProgress: new Map<string, { interval?: NodeJS.Timeout; progressBar: clack.ProgressResult }>(),\n }\n\n function reset() {\n for (const [_key, active] of state.activeProgress) {\n if (active.interval) {\n clearInterval(active.interval)\n }\n active.progressBar?.stop()\n }\n\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 state.spinner = clack.spinner()\n state.isSpinning = false\n state.activeProgress.clear()\n }\n\n function showProgressStep() {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const parts: string[] = []\n const duration = formatHrtime(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 parts.push(`${styleText('green', duration)} elapsed`)\n clack.log.step(getMessage(parts.join(styleText('dim', ' | '))))\n }\n }\n\n function getMessage(message: string): string {\n if (logLevel >= LogLevel.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\n return [styleText('dim', `[${timestamp}]`), message].join(' ')\n }\n\n return message\n }\n\n function startSpinner(text?: string) {\n state.spinner.start(text)\n state.isSpinning = true\n }\n\n function stopSpinner(text?: string) {\n state.spinner.stop(text)\n state.isSpinning = false\n }\n\n context.on('info', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', 'ℹ'), message, styleText('dim', info)].join(' '))\n\n if (state.isSpinning) {\n state.spinner.message(text)\n } else {\n clack.log.info(text)\n }\n })\n\n context.on('success', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', '✓'), message, logLevel >= LogLevel.info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n if (state.isSpinning) {\n stopSpinner(text)\n } else {\n clack.log.success(text)\n }\n })\n\n context.on('warn', (message, info) => {\n if (logLevel < LogLevel.warn) {\n return\n }\n\n const text = getMessage(\n [styleText('yellow', '⚠'), message, logLevel >= LogLevel.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '),\n )\n\n clack.log.warn(text)\n })\n\n context.on('error', (error) => {\n const caused = error.cause as Error | undefined\n\n const text = [styleText('red', '✗'), error.message].join(' ')\n\n if (state.isSpinning) {\n stopSpinner(getMessage(text))\n } else {\n clack.log.error(getMessage(text))\n }\n\n // Show stack trace in debug mode (first 3 frames)\n if (logLevel >= LogLevel.debug && error.stack) {\n const frames = error.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n clack.log.message(getMessage(styleText('dim', frame.trim())))\n }\n\n if (caused?.stack) {\n clack.log.message(styleText('dim', `└─ caused by ${caused.message}`))\n\n const frames = caused.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n clack.log.message(getMessage(` ${styleText('dim', frame.trim())}`))\n }\n }\n }\n })\n\n context.on('version:new', (version, latestVersion) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n clack.box(\n `\\`v${version}\\` → \\`v${latestVersion}\\`\nRun \\`npm install -g @kubb/cli\\` to update`,\n 'Update available for `Kubb`',\n {\n width: 'auto',\n formatBorder: (s: string) => styleText('yellow', s),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n },\n )\n })\n\n context.on('lifecycle:start', async (version) => {\n console.log(`\\n${getIntro({ title: 'The ultimate toolkit for working with APIs', description: 'Ready to start', version, areEyesOpen: true })}\\n`)\n\n reset()\n })\n\n context.on('config:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration started')\n\n clack.intro(text)\n startSpinner(getMessage('Configuration loading'))\n })\n\n context.on('config:end', (_configs) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration completed')\n\n clack.outro(text)\n })\n\n context.on('generation:start', (config) => {\n // Initialize progress tracking\n state.totalPlugins = config.plugins?.length || 0\n\n const text = getMessage(['Generation started', config.name ? `for ${styleText('dim', config.name)}` : undefined].filter(Boolean).join(' '))\n\n clack.intro(text)\n reset()\n })\n\n context.on('plugin:start', (plugin) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n stopSpinner()\n\n const progressBar = clack.progress({\n style: 'block',\n max: 100,\n size: 30,\n })\n const text = getMessage(`Generating ${styleText('bold', plugin.name)}`)\n progressBar.start(text)\n\n const interval = setInterval(() => {\n progressBar.advance()\n }, 100)\n\n state.activeProgress.set(plugin.name, { progressBar, interval })\n })\n\n context.on('plugin:end', (plugin, { duration, success }) => {\n stopSpinner()\n\n const active = state.activeProgress.get(plugin.name)\n\n if (!active || logLevel === LogLevel.silent) {\n return\n }\n\n clearInterval(active.interval)\n\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n\n const durationStr = formatMsWithColor(duration)\n const text = getMessage(\n success\n ? `${styleText('bold', plugin.name)} completed in ${durationStr}`\n : `${styleText('bold', plugin.name)} failed in ${styleText('red', formatMs(duration))}`,\n )\n\n active.progressBar.stop(text)\n state.activeProgress.delete(plugin.name)\n\n // Show progress step after each plugin\n showProgressStep()\n })\n\n context.on('files:processing:start', (files) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n stopSpinner()\n\n state.totalFiles = files.length\n state.processedFiles = 0\n\n const text = `Writing ${files.length} files`\n const progressBar = clack.progress({\n style: 'block',\n max: files.length,\n size: 30,\n })\n\n context.emit('info', text)\n progressBar.start(getMessage(text))\n state.activeProgress.set('files', { progressBar })\n })\n\n context.on('file:processing:update', ({ file, config }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n stopSpinner()\n\n state.processedFiles++\n\n const text = `Writing ${relative(config.root, file.path)}`\n const active = state.activeProgress.get('files')\n\n if (!active) {\n return\n }\n\n active.progressBar.advance(undefined, text)\n })\n context.on('files:processing:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n stopSpinner()\n\n const text = getMessage('Files written successfully')\n const active = state.activeProgress.get('files')\n\n if (!active) {\n return\n }\n\n active.progressBar.stop(text)\n state.activeProgress.delete('files')\n\n // Show final progress step after files are written\n showProgressStep()\n })\n\n context.on('generation:end', (config) => {\n const text = getMessage(config.name ? `Generation completed for ${styleText('dim', config.name)}` : 'Generation completed')\n\n clack.outro(text)\n })\n\n context.on('format:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format started')\n\n clack.intro(text)\n })\n\n context.on('format:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format completed')\n\n clack.outro(text)\n })\n\n context.on('lint:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint started')\n\n clack.intro(text)\n })\n\n context.on('lint:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint completed')\n\n clack.outro(text)\n })\n\n context.on('hook:start', async ({ id, command, args }) => {\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} started`)\n\n // Skip hook execution if no id is provided (e.g., during benchmarks or tests)\n if (!id) {\n return\n }\n\n if (logLevel <= LogLevel.silent) {\n try {\n const result = await x(command, [...(args ?? [])], {\n nodeOptions: { detached: true },\n throwOnError: true,\n })\n\n await context.emit('debug', {\n date: new Date(),\n logs: [result.stdout.trimEnd()],\n })\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: true,\n error: null,\n })\n } catch (err) {\n const error = err as NonZeroExitError\n const stderr = error.output?.stderr ?? ''\n const stdout = error.output?.stdout ?? ''\n\n await context.emit('debug', {\n date: new Date(),\n logs: [stdout, stderr].filter(Boolean),\n })\n\n if (stderr) {\n console.error(stderr)\n }\n if (stdout) {\n console.log(stdout)\n }\n\n const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`)\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: false,\n error: errorMessage,\n })\n await context.emit('error', errorMessage)\n }\n\n return\n }\n\n clack.intro(text)\n\n const logger = clack.taskLog({\n title: getMessage(['Executing hook', logLevel >= LogLevel.info ? styleText('dim', commandWithArgs) : undefined].filter(Boolean).join(' ')),\n })\n\n const writable = new ClackWritable(logger)\n\n try {\n const proc = x(command, [...(args ?? [])], {\n nodeOptions: { detached: true },\n throwOnError: true,\n })\n\n for await (const line of proc) {\n writable.write(line)\n }\n\n const result = await proc\n\n await context.emit('debug', {\n date: new Date(),\n logs: [result.stdout.trimEnd()],\n })\n\n await context.emit('hook:end', { command, args, id, success: true, error: null })\n } catch (err) {\n const error = err as NonZeroExitError\n const stderr = error.output?.stderr ?? ''\n const stdout = error.output?.stdout ?? ''\n\n await context.emit('debug', {\n date: new Date(),\n logs: [stdout, stderr].filter(Boolean),\n })\n\n if (stderr) {\n logger.error(stderr)\n }\n if (stdout) {\n logger.message(stdout)\n }\n\n const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`)\n\n await context.emit('hook:end', { command, args, id, success: false, error: errorMessage })\n await context.emit('error', errorMessage)\n }\n })\n\n context.on('hook:end', ({ command, args }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} successfully executed`)\n\n clack.outro(text)\n })\n\n context.on('generation:summary', (config, { pluginTimings, failedPlugins, filesCreated, status, hrStart }) => {\n const summary = getSummary({\n failedPlugins,\n filesCreated,\n config,\n status,\n hrStart,\n pluginTimings: logLevel >= LogLevel.verbose ? pluginTimings : undefined,\n })\n const title = config.name || ''\n\n summary.unshift('\\n')\n summary.push('\\n')\n\n if (status === 'success') {\n clack.box(summary.join('\\n'), getMessage(title), {\n width: 'auto',\n formatBorder: (s: string) => styleText('green', s),\n rounded: true,\n withGuide: false,\n contentAlign: 'left',\n titleAlign: 'center',\n })\n\n return\n }\n\n clack.box(summary.join('\\n'), getMessage(title), {\n width: 'auto',\n formatBorder: (s: string) => styleText('red', s),\n rounded: true,\n withGuide: false,\n contentAlign: 'left',\n titleAlign: 'center',\n })\n })\n\n context.on('lifecycle:end', () => {\n reset()\n })\n },\n})\n","/**\n * Check if running in GitHub Actions environment\n */\nexport function isGitHubActions(): boolean {\n return !!process.env.GITHUB_ACTIONS\n}\n\n/**\n * Check if running in any CI environment\n */\nexport function isCIEnvironment(): boolean {\n return !!(\n process.env.CI ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.JENKINS_URL ||\n process.env.BUILDKITE\n )\n}\n\n/**\n * Check if TTY is available for interactive output\n */\nexport function canUseTTY(): boolean {\n return !!process.stdout.isTTY && !isCIEnvironment()\n}\n","import { relative, resolve } from 'node:path'\nimport { defineLogger } from '@kubb/core'\nimport { write } from '@kubb/core/fs'\nimport { formatMs } from '@kubb/core/utils'\n\ntype CachedEvent = {\n date: Date\n logs: string[]\n fileName?: string\n}\n\n/**\n * FileSystem logger for debug log persistence\n * Captures debug and verbose events and writes them to files in .kubb directory\n *\n * Note: Logs are written on lifecycle:end or process exit. If the process crashes\n * before these events, some cached logs may be lost.\n */\nexport const fileSystemLogger = defineLogger({\n name: 'filesystem',\n install(context) {\n const state = {\n cachedLogs: new Set<CachedEvent>(),\n startDate: Date.now(),\n }\n\n function reset() {\n state.cachedLogs = new Set<CachedEvent>()\n state.startDate = Date.now()\n }\n\n async function writeLogs(name?: string) {\n if (state.cachedLogs.size === 0) {\n return []\n }\n\n const files: Record<string, string[]> = {}\n\n for (const log of state.cachedLogs) {\n const baseName = log.fileName || `${['kubb', name, state.startDate].filter(Boolean).join('-')}.log`\n const pathName = resolve(process.cwd(), '.kubb', baseName)\n\n if (!files[pathName]) {\n files[pathName] = []\n }\n\n if (log.logs.length > 0) {\n const timestamp = log.date.toLocaleString()\n files[pathName].push(`[${timestamp}]\\n${log.logs.join('\\n')}`)\n }\n }\n\n await Promise.all(\n Object.entries(files).map(async ([fileName, logs]) => {\n return write(fileName, logs.join('\\n\\n'))\n }),\n )\n\n return Object.keys(files)\n }\n\n context.on('info', (message, info) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`ℹ ${message} ${info}`],\n fileName: undefined,\n })\n })\n\n context.on('success', (message, info) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`✓ ${message} ${info}`],\n fileName: undefined,\n })\n })\n\n context.on('warn', (message, info) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`⚠ ${message} ${info}`],\n fileName: undefined,\n })\n })\n\n context.on('error', (error) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`✗ ${error.message}`, error.stack || 'unknown stack'],\n fileName: undefined,\n })\n })\n\n context.on('debug', (message) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: message.logs,\n fileName: undefined,\n })\n })\n\n context.on('plugin:start', (plugin) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`Generating ${plugin.name}`],\n fileName: undefined,\n })\n })\n\n context.on('plugin:end', (plugin, { duration, success }) => {\n const durationStr = formatMs(duration)\n\n state.cachedLogs.add({\n date: new Date(),\n logs: [success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`],\n fileName: undefined,\n })\n })\n\n context.on('files:processing:start', (files) => {\n state.cachedLogs.add({\n date: new Date(),\n logs: [`Start ${files.length} writing:`, ...files.map((file) => file.path)],\n fileName: undefined,\n })\n })\n\n context.on('generation:end', async (config) => {\n const writtenFilePaths = await writeLogs(config.name)\n if (writtenFilePaths.length > 0) {\n const files = writtenFilePaths.map((f) => relative(process.cwd(), f))\n await context.emit('info', 'Debug files written to:', files.join(', '))\n }\n reset()\n })\n\n context.on('lifecycle:end', async () => {\n // lifecycle:end handler can be used for cleanup if needed in the future\n })\n\n // Fallback: Write logs on process exit to handle crashes\n const exitHandler = () => {\n // Synchronous write on exit - best effort\n if (state.cachedLogs.size > 0) {\n writeLogs().catch(() => {\n // Ignore errors on exit\n })\n }\n }\n\n process.once('exit', exitHandler)\n process.once('SIGINT', exitHandler)\n process.once('SIGTERM', exitHandler)\n },\n})\n","import { styleText } from 'node:util'\nimport { type Config, defineLogger, LogLevel } from '@kubb/core'\nimport { formatHrtime, formatMs } from '@kubb/core/utils'\nimport { type NonZeroExitError, x } from 'tinyexec'\nimport { formatMsWithColor } from '../utils/formatMsWithColor.ts'\n\n/**\n * GitHub Actions adapter for CI environments\n * Uses Github group annotations for collapsible sections\n */\nexport const githubActionsLogger = defineLogger({\n name: 'github-actions',\n install(context, options) {\n const logLevel = options?.logLevel || LogLevel.info\n const state = {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n currentConfigs: [] as Array<Config>,\n }\n\n function reset() {\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 function showProgressStep() {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const parts: string[] = []\n const duration = formatHrtime(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 parts.push(`${styleText('green', duration)} elapsed`)\n console.log(getMessage(parts.join(styleText('dim', ' | '))))\n }\n }\n\n function getMessage(message: string): string {\n if (logLevel >= LogLevel.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\n return [styleText('dim', `[${timestamp}]`), message].join(' ')\n }\n\n return message\n }\n\n function openGroup(name: string) {\n console.log(`::group::${name}`)\n }\n\n function closeGroup(_name: string) {\n console.log('::endgroup::')\n }\n\n context.on('info', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', 'ℹ'), message, styleText('dim', info)].join(' '))\n\n console.log(text)\n })\n\n context.on('success', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', '✓'), message, logLevel >= LogLevel.info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.on('warn', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage([styleText('yellow', '⚠'), message, logLevel >= LogLevel.info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n console.warn(`::warning::${text}`)\n })\n\n context.on('error', (error) => {\n const caused = error.cause as Error | undefined\n\n if (logLevel <= LogLevel.silent) {\n return\n }\n const message = error.message || String(error)\n console.error(`::error::${message}`)\n\n // Show stack trace in debug mode (first 3 frames)\n if (logLevel >= LogLevel.debug && error.stack) {\n const frames = error.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n console.log(getMessage(styleText('dim', frame.trim())))\n }\n\n if (caused?.stack) {\n console.log(styleText('dim', `└─ caused by ${caused.message}`))\n\n const frames = caused.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n console.log(getMessage(` ${styleText('dim', frame.trim())}`))\n }\n }\n }\n })\n\n context.on('lifecycle:start', (version) => {\n console.log(styleText('yellow', `Kubb ${version} 🧩`))\n reset()\n })\n\n context.on('config:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration started')\n\n openGroup('Configuration')\n\n console.log(text)\n })\n\n context.on('config:end', (configs) => {\n state.currentConfigs = configs\n\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration completed')\n\n console.log(text)\n\n closeGroup('Configuration')\n })\n\n context.on('generation:start', (config) => {\n // Initialize progress tracking\n state.totalPlugins = config.plugins?.length || 0\n\n const text = config.name ? `Generation for ${styleText('bold', config.name)}` : 'Generation'\n\n if (state.currentConfigs.length > 1) {\n openGroup(text)\n }\n\n if (state.currentConfigs.length === 1) {\n console.log(getMessage(text))\n }\n\n reset()\n })\n\n context.on('plugin:start', (plugin) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n const text = getMessage(`Generating ${styleText('bold', plugin.name)}`)\n\n if (state.currentConfigs.length === 1) {\n openGroup(`Plugin: ${plugin.name}`)\n }\n\n console.log(text)\n })\n\n context.on('plugin:end', (plugin, { duration, success }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n\n const durationStr = formatMsWithColor(duration)\n const text = getMessage(\n success\n ? `${styleText('bold', plugin.name)} completed in ${durationStr}`\n : `${styleText('bold', plugin.name)} failed in ${styleText('red', formatMs(duration))}`,\n )\n\n console.log(text)\n if (state.currentConfigs.length > 1) {\n console.log(' ')\n }\n\n if (state.currentConfigs.length === 1) {\n closeGroup(`Plugin: ${plugin.name}`)\n }\n\n // Show progress step after each plugin\n showProgressStep()\n })\n\n context.on('files:processing:start', (files) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n state.totalFiles = files.length\n state.processedFiles = 0\n\n if (state.currentConfigs.length === 1) {\n openGroup('File Generation')\n }\n const text = getMessage(`Writing ${files.length} files`)\n\n console.log(text)\n })\n\n context.on('files:processing:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n const text = getMessage('Files written successfully')\n\n console.log(text)\n\n if (state.currentConfigs.length === 1) {\n closeGroup('File Generation')\n }\n })\n\n context.on('file:processing:update', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n state.processedFiles++\n })\n\n context.on('files:processing:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n // Show final progress step after files are written\n showProgressStep()\n })\n\n context.on('generation:end', (config) => {\n const text = getMessage(\n config.name ? `${styleText('blue', '✓')} Generation completed for ${styleText('dim', config.name)}` : `${styleText('blue', '✓')} Generation completed`,\n )\n\n console.log(text)\n })\n\n context.on('format:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format started')\n\n if (state.currentConfigs.length === 1) {\n openGroup('Formatting')\n }\n\n console.log(text)\n })\n\n context.on('format:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format completed')\n\n console.log(text)\n\n if (state.currentConfigs.length === 1) {\n closeGroup('Formatting')\n }\n })\n\n context.on('lint:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint started')\n\n if (state.currentConfigs.length === 1) {\n openGroup('Linting')\n }\n\n console.log(text)\n })\n\n context.on('lint:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint completed')\n\n console.log(text)\n\n if (state.currentConfigs.length === 1) {\n closeGroup('Linting')\n }\n })\n\n context.on('hook:start', async ({ id, command, args }) => {\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} started`)\n\n if (logLevel > LogLevel.silent) {\n if (state.currentConfigs.length === 1) {\n openGroup(`Hook ${commandWithArgs}`)\n }\n\n console.log(text)\n }\n\n // Skip hook execution if no id is provided (e.g., during benchmarks or tests)\n if (!id) {\n return\n }\n\n try {\n const result = await x(command, [...(args ?? [])], {\n nodeOptions: { detached: true },\n throwOnError: true,\n })\n\n await context.emit('debug', {\n date: new Date(),\n logs: [result.stdout.trimEnd()],\n })\n\n if (logLevel > LogLevel.silent) {\n console.log(result.stdout.trimEnd())\n }\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: true,\n error: null,\n })\n } catch (err) {\n const error = err as NonZeroExitError\n const stderr = error.output?.stderr ?? ''\n const stdout = error.output?.stdout ?? ''\n\n await context.emit('debug', {\n date: new Date(),\n logs: [stdout, stderr].filter(Boolean),\n })\n\n // Display stderr/stdout in GitHub Actions format\n if (stderr) {\n console.error(`::error::${stderr}`)\n }\n if (stdout) {\n console.log(stdout)\n }\n\n const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`)\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: false,\n error: errorMessage,\n })\n await context.emit('error', errorMessage)\n }\n })\n\n context.on('hook:end', ({ command, args }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} completed`)\n\n console.log(text)\n\n if (state.currentConfigs.length === 1) {\n closeGroup(`Hook ${commandWithArgs}`)\n }\n })\n\n context.on('generation:summary', (config, { status, hrStart, failedPlugins }) => {\n const pluginsCount = config.plugins?.length || 0\n const successCount = pluginsCount - failedPlugins.size\n const duration = formatHrtime(hrStart)\n\n if (state.currentConfigs.length > 1) {\n console.log(' ')\n }\n\n console.log(\n status === 'success'\n ? `Kubb Summary: ${styleText('blue', '✓')} ${`${successCount} successful`}, ${pluginsCount} total, ${styleText('green', duration)}`\n : `Kubb Summary: ${styleText('blue', '✓')} ${`${successCount} successful`}, ✗ ${`${failedPlugins.size} failed`}, ${pluginsCount} total, ${styleText('green', duration)}`,\n )\n\n if (state.currentConfigs.length > 1) {\n closeGroup(config.name ? `Generation for ${styleText('bold', config.name)}` : 'Generation')\n }\n })\n },\n})\n","import { relative } from 'node:path'\nimport { defineLogger, LogLevel } from '@kubb/core'\nimport { formatMs } from '@kubb/core/utils'\nimport { type NonZeroExitError, x } from 'tinyexec'\nimport { getSummary } from '../utils/getSummary.ts'\n\n/**\n * Plain console adapter for non-TTY environments\n * Simple console.log output with indentation\n */\nexport const plainLogger = defineLogger({\n name: 'plain',\n install(context, options) {\n const logLevel = options?.logLevel || 3\n\n function getMessage(message: string): string {\n if (logLevel >= LogLevel.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\n return [`[${timestamp}]`, message].join(' ')\n }\n\n return message\n }\n\n context.on('info', (message, info) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage(['ℹ', message, info].join(' '))\n\n console.log(text)\n })\n\n context.on('success', (message, info = '') => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage(['✓', message, logLevel >= LogLevel.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.on('warn', (message, info) => {\n if (logLevel < LogLevel.warn) {\n return\n }\n\n const text = getMessage(['⚠', message, logLevel >= LogLevel.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.on('error', (error) => {\n const caused = error.cause as Error | undefined\n\n const text = getMessage(['✗', error.message].join(' '))\n\n console.log(text)\n\n // Show stack trace in debug mode (first 3 frames)\n if (logLevel >= LogLevel.debug && error.stack) {\n const frames = error.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n console.log(getMessage(frame.trim()))\n }\n\n if (caused?.stack) {\n console.log(`└─ caused by ${caused.message}`)\n\n const frames = caused.stack.split('\\n').slice(1, 4)\n for (const frame of frames) {\n console.log(getMessage(` ${frame.trim()}`))\n }\n }\n }\n })\n\n context.on('lifecycle:start', () => {\n console.log('Kubb CLI 🧩')\n })\n\n context.on('config:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration started')\n\n console.log(text)\n })\n\n context.on('config:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Configuration completed')\n\n console.log(text)\n })\n\n context.on('generation:start', () => {\n const text = getMessage('Configuration started')\n\n console.log(text)\n })\n\n context.on('plugin:start', (plugin) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n const text = getMessage(`Generating ${plugin.name}`)\n\n console.log(text)\n })\n\n context.on('plugin:end', (plugin, { duration, success }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const durationStr = formatMs(duration)\n const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`)\n\n console.log(text)\n })\n\n context.on('files:processing:start', (files) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage(`Writing ${files.length} files`)\n\n console.log(text)\n })\n\n context.on('file:processing:update', ({ file, config }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage(`Writing ${relative(config.root, file.path)}`)\n\n console.log(text)\n })\n\n context.on('files:processing:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Files written successfully')\n\n console.log(text)\n })\n\n context.on('generation:end', (config) => {\n const text = getMessage(config.name ? `Generation completed for ${config.name}` : 'Generation completed')\n\n console.log(text)\n })\n\n context.on('format:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format started')\n\n console.log(text)\n })\n\n context.on('format:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Format completed')\n\n console.log(text)\n })\n\n context.on('lint:start', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint started')\n\n console.log(text)\n })\n\n context.on('lint:end', () => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const text = getMessage('Lint completed')\n\n console.log(text)\n })\n\n context.on('hook:start', async ({ id, command, args }) => {\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${commandWithArgs} started`)\n\n if (logLevel > LogLevel.silent) {\n console.log(text)\n }\n\n // Skip hook execution if no id is provided (e.g., during benchmarks or tests)\n if (!id) {\n return\n }\n\n try {\n const result = await x(command, [...(args ?? [])], {\n nodeOptions: { detached: true },\n throwOnError: true,\n })\n\n await context.emit('debug', {\n date: new Date(),\n logs: [result.stdout.trimEnd()],\n })\n\n if (logLevel > LogLevel.silent) {\n console.log(result.stdout.trimEnd())\n }\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: true,\n error: null,\n })\n } catch (err) {\n const error = err as NonZeroExitError\n const stderr = error.output?.stderr ?? ''\n const stdout = error.output?.stdout ?? ''\n\n await context.emit('debug', {\n date: new Date(),\n logs: [stdout, stderr].filter(Boolean),\n })\n\n if (stderr) {\n console.error(stderr)\n }\n if (stdout) {\n console.log(stdout)\n }\n\n const errorMessage = new Error(`Hook execute failed: ${commandWithArgs}`)\n\n await context.emit('hook:end', {\n command,\n args,\n id,\n success: false,\n error: errorMessage,\n })\n await context.emit('error', errorMessage)\n }\n })\n\n context.on('hook:end', ({ command, args }) => {\n if (logLevel <= LogLevel.silent) {\n return\n }\n\n const commandWithArgs = args?.length ? `${command} ${args.join(' ')}` : command\n const text = getMessage(`Hook ${commandWithArgs} completed`)\n\n console.log(text)\n })\n\n context.on('generation:summary', (config, { pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {\n const summary = getSummary({\n failedPlugins,\n filesCreated,\n config,\n status,\n hrStart,\n pluginTimings: logLevel >= LogLevel.verbose ? pluginTimings : undefined,\n })\n\n console.log('---------------------------')\n console.log(summary.join('\\n'))\n console.log('---------------------------')\n })\n },\n})\n","import type { Logger, LoggerContext, LoggerOptions } from '@kubb/core'\nimport { LogLevel } from '@kubb/core'\nimport { clackLogger } from './clackLogger.ts'\nimport { canUseTTY, isGitHubActions } from './envDetection.ts'\nimport { fileSystemLogger } from './fileSystemLogger.ts'\nimport { githubActionsLogger } from './githubActionsLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\nimport type { LoggerType } from './types.ts'\n\nexport function detec