@kubb/cli 5.0.0-beta.63 → 5.0.0-beta.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/kubb.js +9 -3
  2. package/dist/{Telemetry-C6rbhJMo.cjs → Telemetry-CfPP7MYq.cjs} +4 -4
  3. package/dist/{Telemetry-C6rbhJMo.cjs.map → Telemetry-CfPP7MYq.cjs.map} +1 -1
  4. package/dist/{Telemetry-DTKcvgbx.js → Telemetry-uAr3lK_-.js} +2 -2
  5. package/dist/{Telemetry-DTKcvgbx.js.map → Telemetry-uAr3lK_-.js.map} +1 -1
  6. package/dist/{define-C4AB3POr.cjs → define-Cq9hOxpK.cjs} +2 -2
  7. package/dist/{define-C4AB3POr.cjs.map → define-Cq9hOxpK.cjs.map} +1 -1
  8. package/dist/{define-C63T4jp6.js → define-GYXr00ky.js} +2 -2
  9. package/dist/{define-C63T4jp6.js.map → define-GYXr00ky.js.map} +1 -1
  10. package/dist/{errors-BsemQCMn.js → errors-Dc_d7BfX.js} +2 -2
  11. package/dist/{errors-BsemQCMn.js.map → errors-Dc_d7BfX.js.map} +1 -1
  12. package/dist/{errors-DykI11xo.cjs → errors-gxFK0vrp.cjs} +2 -2
  13. package/dist/{errors-DykI11xo.cjs.map → errors-gxFK0vrp.cjs.map} +1 -1
  14. package/dist/{generate-DC4--Iha.js → generate-DHQnl_F1.js} +4 -4
  15. package/dist/{generate-DC4--Iha.js.map → generate-DHQnl_F1.js.map} +1 -1
  16. package/dist/{generate-Dw7aWzeb.cjs → generate-svfhwhEK.cjs} +4 -4
  17. package/dist/{generate-Dw7aWzeb.cjs.map → generate-svfhwhEK.cjs.map} +1 -1
  18. package/dist/index.cjs +8 -8
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +8 -8
  21. package/dist/{init-D2VvDsET.js → init-B02NN_88.js} +5 -5
  22. package/dist/{init-D2VvDsET.js.map → init-B02NN_88.js.map} +1 -1
  23. package/dist/{init-C7GC2NA8.cjs → init-Bg_68Ok6.cjs} +5 -5
  24. package/dist/{init-C7GC2NA8.cjs.map → init-Bg_68Ok6.cjs.map} +1 -1
  25. package/dist/{mcp-uTUssJam.cjs → mcp-DUzIXdRV.cjs} +7 -25
  26. package/dist/mcp-DUzIXdRV.cjs.map +1 -0
  27. package/dist/mcp-ZJQksVUU.js +21 -0
  28. package/dist/mcp-ZJQksVUU.js.map +1 -0
  29. package/dist/package-BoXPsuNH.js +6 -0
  30. package/dist/package-BoXPsuNH.js.map +1 -0
  31. package/dist/{package-IO7JFU8g.cjs → package-Cdu8eJMb.cjs} +2 -2
  32. package/dist/package-Cdu8eJMb.cjs.map +1 -0
  33. package/dist/{run-DpKny2hT.cjs → run-B4rIAnch.cjs} +7 -7
  34. package/dist/{run-DpKny2hT.cjs.map → run-B4rIAnch.cjs.map} +1 -1
  35. package/dist/{run-D_sbcTfX.cjs → run-BM1t8CSM.cjs} +8 -13
  36. package/dist/run-BM1t8CSM.cjs.map +1 -0
  37. package/dist/{run-Ctz9-vGE.js → run-BlFVmIJl.js} +7 -12
  38. package/dist/run-BlFVmIJl.js.map +1 -0
  39. package/dist/{run-BoXg14l_.cjs → run-CBc896in.cjs} +5 -5
  40. package/dist/{run-BoXg14l_.cjs.map → run-CBc896in.cjs.map} +1 -1
  41. package/dist/{run-FiqbWZEH.cjs → run-CD3BE8yP.cjs} +55 -62
  42. package/dist/run-CD3BE8yP.cjs.map +1 -0
  43. package/dist/{run-Bp8sI6h0.js → run-D_dWNFhX.js} +4 -4
  44. package/dist/{run-Bp8sI6h0.js.map → run-D_dWNFhX.js.map} +1 -1
  45. package/dist/{run-DybX4Hpr.js → run-DkW2VQBq.js} +53 -60
  46. package/dist/run-DkW2VQBq.js.map +1 -0
  47. package/dist/{run-BG7Giryi.js → run-DzYeru-0.js} +3 -3
  48. package/dist/{run-BG7Giryi.js.map → run-DzYeru-0.js.map} +1 -1
  49. package/dist/{tools-_Xp8-_zy.cjs → tools-CZT9wSA6.cjs} +2 -2
  50. package/dist/{tools-_Xp8-_zy.cjs.map → tools-CZT9wSA6.cjs.map} +1 -1
  51. package/dist/{tools-BU99bhi8.js → tools-D0UogMU3.js} +2 -2
  52. package/dist/{tools-BU99bhi8.js.map → tools-D0UogMU3.js.map} +1 -1
  53. package/dist/{validate-DVYs1uzP.cjs → validate-B3EwltHu.cjs} +5 -5
  54. package/dist/{validate-DVYs1uzP.cjs.map → validate-B3EwltHu.cjs.map} +1 -1
  55. package/dist/{validate-C6tYZ5Bd.js → validate-DXYcZCm_.js} +5 -5
  56. package/dist/{validate-C6tYZ5Bd.js.map → validate-DXYcZCm_.js.map} +1 -1
  57. package/package.json +7 -8
  58. package/dist/mcp-DKPUyzpK.js +0 -39
  59. package/dist/mcp-DKPUyzpK.js.map +0 -1
  60. package/dist/mcp-uTUssJam.cjs.map +0 -1
  61. package/dist/package-DCrqV1yP.js +0 -6
  62. package/dist/package-DCrqV1yP.js.map +0 -1
  63. package/dist/package-IO7JFU8g.cjs.map +0 -1
  64. package/dist/run-Ctz9-vGE.js.map +0 -1
  65. package/dist/run-D_sbcTfX.cjs.map +0 -1
  66. package/dist/run-DybX4Hpr.js.map +0 -1
  67. package/dist/run-FiqbWZEH.cjs.map +0 -1
  68. package/src/Telemetry.ts +0 -304
  69. package/src/commands/generate.ts +0 -65
  70. package/src/commands/init.ts +0 -51
  71. package/src/commands/mcp.ts +0 -36
  72. package/src/commands/validate.ts +0 -22
  73. package/src/constants.ts +0 -19
  74. package/src/index.ts +0 -32
  75. package/src/loggers/clackLogger.ts +0 -392
  76. package/src/loggers/defineLogger.ts +0 -59
  77. package/src/loggers/plainLogger.ts +0 -199
  78. package/src/loggers/types.ts +0 -6
  79. package/src/loggers/utils.ts +0 -250
  80. package/src/runners/generate/run.ts +0 -399
  81. package/src/runners/generate/utils.ts +0 -235
  82. package/src/runners/init/run.ts +0 -210
  83. package/src/runners/init/utils.ts +0 -39
  84. package/src/runners/mcp/run.ts +0 -42
  85. package/src/runners/validate/run.ts +0 -63
  86. /package/dist/{chunk-Bx3C2hgW.cjs → rolldown-runtime-Bx3C2hgW.cjs} +0 -0
  87. /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,250 +0,0 @@
1
- import process from 'node:process'
2
- import { styleText } from 'node:util'
3
- import { canUseTTY, formatHrtime, getElapsedMs } from '@internals/utils'
4
- import type { Reporter, ReporterContext } from '@kubb/core'
5
- import { logLevel as logLevelMap } from '@kubb/core'
6
- import type { Logger, LoggerContext, LoggerOptions } from './defineLogger.ts'
7
- import { clackLogger } from './clackLogger.ts'
8
- import { plainLogger } from './plainLogger.ts'
9
- import type { LoggerType } from './types.ts'
10
-
11
- /**
12
- * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
13
- * Shared across all logger adapters to avoid duplication.
14
- */
15
- export function formatMessage(message: string, logLevel: number): string {
16
- if (logLevel >= logLevelMap.verbose) {
17
- const timestamp = new Date().toLocaleTimeString('en-US', {
18
- hour12: false,
19
- hour: '2-digit',
20
- minute: '2-digit',
21
- second: '2-digit',
22
- })
23
- return `${styleText('dim', `[${timestamp}]`)} ${message}`
24
- }
25
- return message
26
- }
27
-
28
- type ProgressState = {
29
- /**
30
- * Total number of plugins scheduled for this generation run.
31
- */
32
- totalPlugins: number
33
- /**
34
- * Number of plugins that have finished without error.
35
- */
36
- completedPlugins: number
37
- /**
38
- * Number of plugins that exited with an error.
39
- */
40
- failedPlugins: number
41
- /**
42
- * Total number of files expected to be written.
43
- */
44
- totalFiles: number
45
- /**
46
- * Number of files written so far.
47
- */
48
- processedFiles: number
49
- /**
50
- * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
51
- */
52
- hrStart: [number, number]
53
- }
54
-
55
- /**
56
- * Build the progress summary line shown by the clack logger.
57
- * Returns null when there is nothing to display.
58
- */
59
- export function buildProgressLine(state: ProgressState): string | null {
60
- const parts: Array<string> = []
61
- const duration = formatHrtime(state.hrStart)
62
-
63
- if (state.totalPlugins > 0) {
64
- const pluginStr =
65
- state.failedPlugins > 0
66
- ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`
67
- : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`
68
- parts.push(pluginStr)
69
- }
70
-
71
- if (state.totalFiles > 0) {
72
- parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)
73
- }
74
-
75
- if (parts.length === 0) {
76
- return null
77
- }
78
-
79
- parts.push(`${styleText('green', duration)} elapsed`)
80
- return parts.join(styleText('dim', ' | '))
81
- }
82
-
83
- /**
84
- * Creates the per-run progress counters used by the clack logger.
85
- */
86
- export function createProgressCounters(): ProgressState {
87
- return {
88
- totalPlugins: 0,
89
- completedPlugins: 0,
90
- failedPlugins: 0,
91
- totalFiles: 0,
92
- processedFiles: 0,
93
- hrStart: process.hrtime(),
94
- }
95
- }
96
-
97
- /**
98
- * Resets the progress counters in place at the start/end of a generation run.
99
- */
100
- export function resetProgressCounters(state: ProgressState): void {
101
- state.totalPlugins = 0
102
- state.completedPlugins = 0
103
- state.failedPlugins = 0
104
- state.totalFiles = 0
105
- state.processedFiles = 0
106
- state.hrStart = process.hrtime()
107
- }
108
-
109
- /**
110
- * Records a finished plugin against the progress counters.
111
- */
112
- export function recordPluginResult(state: ProgressState, success: boolean): void {
113
- if (success) {
114
- state.completedPlugins++
115
- } else {
116
- state.failedPlugins++
117
- }
118
- }
119
-
120
- /**
121
- * Tracks per-hook start times so a logger can report a hook's elapsed duration.
122
- * Used by the plain logger, which keys timing by hook `id`.
123
- */
124
- export type HookTimer = {
125
- start(id: string): void
126
- /**
127
- * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.
128
- */
129
- end(id: string): number | undefined
130
- clear(): void
131
- }
132
-
133
- /**
134
- * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
135
- */
136
- export function createHookTimer(): HookTimer {
137
- const starts = new Map<string, [number, number]>()
138
-
139
- return {
140
- start(id: string): void {
141
- starts.set(id, process.hrtime())
142
- },
143
- end(id: string): number | undefined {
144
- const hrStart = starts.get(id)
145
- if (!hrStart) {
146
- return undefined
147
- }
148
- starts.delete(id)
149
- return getElapsedMs(hrStart)
150
- },
151
- clear(): void {
152
- starts.clear()
153
- },
154
- }
155
- }
156
-
157
- /**
158
- * Join a command and its optional args into a single display string.
159
- *
160
- * @example With args
161
- * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`
162
- */
163
- export function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {
164
- return args?.length ? `${command} ${args.join(' ')}` : command
165
- }
166
-
167
- function detectLogger(): LoggerType {
168
- if (canUseTTY()) {
169
- return 'clack'
170
- }
171
- return 'plain'
172
- }
173
-
174
- const logMapper: Record<LoggerType, Logger> = {
175
- clack: clackLogger,
176
- plain: plainLogger,
177
- }
178
-
179
- /**
180
- * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
181
- * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
182
- */
183
- export function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {
184
- context.on('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {
185
- await reporter.report({ config, diagnostics, filesCreated, status, hrStart }, ctx)
186
- })
187
-
188
- if (reporter.drain) {
189
- context.on('kubb:lifecycle:end', () => reporter.drain?.(ctx))
190
- }
191
- }
192
-
193
- /**
194
- * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
195
- * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This
196
- * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
197
- * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
198
- *
199
- * Loggers and reporters are independent, except for `cli`: it both installs the live logger view
200
- * here and registers as a reporter that prints the per-config summary. The `json` reporter owns
201
- * stdout, so the whole `cli` reporter (live logger and summary) is skipped whenever `json` is
202
- * among the reporters, even if `cli` is also listed.
203
- */
204
- async function setupReporters(context: LoggerContext, { logLevel, reporters }: LoggerOptions & { reporters: ReadonlyArray<Reporter> }): Promise<void> {
205
- const hasJson = reporters.some((reporter) => reporter.name === 'json')
206
- const ctx: ReporterContext = { logLevel }
207
-
208
- for (const reporter of reporters) {
209
- if (reporter.name === 'cli') {
210
- if (hasJson) {
211
- continue
212
- }
213
- const type = detectLogger()
214
- const logger = logMapper[type]
215
- if (!logger) {
216
- throw new Error(`Unknown adapter type: ${type}`)
217
- }
218
- await logger.install(context, { logLevel })
219
- }
220
-
221
- installReporter(context, reporter, ctx)
222
- }
223
- }
224
-
225
- export default setupReporters
226
-
227
- /**
228
- * Picks the reporters whose `name` matches one of `names`, in the order the names are given.
229
- * The config carries every available reporter, and the host selects which to activate by name
230
- * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are
231
- * skipped.
232
- */
233
- export function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {
234
- const seen = new Set<string>()
235
- const selected: Array<Reporter> = []
236
-
237
- for (const name of names) {
238
- if (seen.has(name)) {
239
- continue
240
- }
241
- seen.add(name)
242
-
243
- const reporter = reporters.find((candidate) => candidate.name === name)
244
- if (reporter) {
245
- selected.push(reporter)
246
- }
247
- }
248
-
249
- return selected
250
- }
@@ -1,399 +0,0 @@
1
- import { hash } from 'node:crypto'
2
- import { existsSync } from 'node:fs'
3
- import path from 'node:path'
4
- import process from 'node:process'
5
- import { styleText } from 'node:util'
6
- import * as clack from '@clack/prompts'
7
- import type { AsyncEventEmitter } from '@internals/utils'
8
- import { AsyncEventEmitter as AsyncEventEmitterClass, detectTool, formatters, linters, toError } from '@internals/utils'
9
- import {
10
- type CLIOptions,
11
- cliReporter,
12
- type Config,
13
- createKubb,
14
- type Diagnostic,
15
- Diagnostics,
16
- type KubbHooks,
17
- logLevel as logLevelMap,
18
- type ProblemDiagnostic,
19
- type ReporterName,
20
- } from '@kubb/core'
21
- import { version } from '../../../package.json'
22
- import { KUBB_NPM_PACKAGE_URL } from '../../constants.ts'
23
- import { Telemetry } from '../../Telemetry.ts'
24
- import setupReporters, { selectReporters } from '../../loggers/utils.ts'
25
- import { executeHooks, getConfigs, runHook, startWatcher } from './utils.ts'
26
-
27
- type GenerateProps = {
28
- input?: string
29
- config: Config
30
- hooks: AsyncEventEmitter<KubbHooks>
31
- logLevel: number
32
- }
33
-
34
- type ToolMap = typeof formatters | typeof linters
35
-
36
- type RunToolPassOptions = {
37
- toolValue: string
38
- detect: () => Promise<string | null>
39
- toolMap: ToolMap
40
- toolLabel: string
41
- successPrefix: string
42
- noToolMessage: string
43
- configName: string | undefined
44
- outputPath: string
45
- logLevel: number
46
- hooks: AsyncEventEmitter<KubbHooks>
47
- onStart: () => Promise<void>
48
- onEnd: () => Promise<void>
49
- }
50
-
51
- /**
52
- * Registers a one-shot `kubb:hook:end` listener for `hookId` before the caller emits `kubb:hook:start`,
53
- * so a synchronous emitter cannot fire end before the listener is attached.
54
- */
55
- function waitForHookEnd(
56
- hooks: AsyncEventEmitter<KubbHooks>,
57
- hookId: string,
58
- onSuccess: () => Promise<void> | void,
59
- fallbackErrorMessage: string,
60
- ): Promise<void> {
61
- return new Promise<void>((resolve, reject) => {
62
- const handler = (ctx: { id?: string; command: string; args?: ReadonlyArray<string>; success: boolean; error: Error | null }) => {
63
- if (ctx.id !== hookId) return
64
- hooks.off('kubb:hook:end', handler)
65
- if (!ctx.success) {
66
- reject(ctx.error ?? new Error(fallbackErrorMessage))
67
- return
68
- }
69
- Promise.resolve(onSuccess()).then(resolve).catch(reject)
70
- }
71
- hooks.on('kubb:hook:end', handler)
72
- })
73
- }
74
-
75
- async function runToolPass({
76
- toolValue,
77
- detect,
78
- toolMap,
79
- toolLabel,
80
- successPrefix,
81
- noToolMessage,
82
- configName,
83
- outputPath,
84
- logLevel,
85
- hooks,
86
- onStart,
87
- onEnd,
88
- }: RunToolPassOptions) {
89
- await onStart()
90
-
91
- let resolvedTool = toolValue
92
- if (resolvedTool === 'auto') {
93
- const detected = await detect()
94
- if (!detected) {
95
- await hooks.emit('kubb:warn', { message: noToolMessage })
96
- } else {
97
- resolvedTool = detected
98
- await hooks.emit('kubb:info', { message: `Auto-detected ${toolLabel}: ${styleText('dim', resolvedTool)}` })
99
- }
100
- }
101
-
102
- let toolError: Error | undefined
103
-
104
- // Nothing to lint or format when the output dir was never written. Skip so the tool
105
- // (e.g. oxlint with --no-ignore) doesn't fail with "No files found to lint".
106
- if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in toolMap && existsSync(outputPath)) {
107
- const toolConfig = toolMap[resolvedTool as keyof ToolMap]
108
- const hookId = hash('sha256', [configName, resolvedTool].filter(Boolean).join('-'), 'hex')
109
-
110
- const successMessage = [
111
- `${successPrefix} with ${styleText('dim', resolvedTool)}`,
112
- logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,
113
- 'successfully',
114
- ]
115
- .filter(Boolean)
116
- .join(' ')
117
-
118
- try {
119
- const hookArgs = toolConfig.args(outputPath)
120
- const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')
121
- const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit('kubb:success', { message: successMessage }), toolConfig.errorMessage)
122
-
123
- await hooks.emit('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })
124
-
125
- runHook({
126
- id: hookId,
127
- command: toolConfig.command,
128
- args: hookArgs,
129
- commandWithArgs,
130
- hooks,
131
- }).catch(() => {})
132
-
133
- await hookEndPromise
134
- } catch (caughtError) {
135
- // Don't render here. The caller turns this into a coded diagnostic and emits it through
136
- // `Diagnostics.emit`, so format/lint/hook failures render like every other diagnostic.
137
- toolError = toError(caughtError)
138
- }
139
- }
140
-
141
- await onEnd()
142
-
143
- if (toolError) {
144
- throw toolError
145
- }
146
- }
147
-
148
- async function generate(options: GenerateProps): Promise<boolean> {
149
- const { input, hooks, logLevel } = options
150
-
151
- const hrStart = process.hrtime()
152
- const inputPath = input ?? (options.config.input && 'path' in options.config.input ? options.config.input.path : undefined)
153
-
154
- const config: Config = {
155
- ...options.config,
156
- input: inputPath ? { ...options.config.input, path: inputPath } : options.config.input,
157
- ...options.config.output,
158
- } satisfies Config
159
-
160
- const kubb = createKubb(config, { hooks })
161
-
162
- await hooks.emit('kubb:generation:start', { config })
163
- await hooks.emit('kubb:info', { message: config.name ? `Setup generation ${styleText('bold', config.name)}` : 'Setup generation', info: inputPath })
164
-
165
- await kubb.setup()
166
-
167
- await hooks.emit('kubb:info', { message: config.name ? `Build generation ${styleText('bold', config.name)}` : 'Build generation', info: inputPath })
168
-
169
- const { files, diagnostics, driver } = await kubb.safeBuild()
170
-
171
- await hooks.emit('kubb:info', { message: 'Load summary' })
172
-
173
- const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))
174
-
175
- const reportTelemetry = (status: 'success' | 'failed') =>
176
- Telemetry.send(Telemetry.build({ command: 'generate', kubbVersion: version, plugins: telemetryPlugins, hrStart, filesCreated: files.length, status }))
177
-
178
- // Render every problem, not just on failure, so warnings and info surface too.
179
- // `performance` diagnostics feed the summary, not the log.
180
- for (const diagnostic of diagnostics) {
181
- if (!Diagnostics.isProblem(diagnostic)) {
182
- continue
183
- }
184
- const unknown = Diagnostics.narrow(diagnostic, Diagnostics.code.unknown)
185
- if (unknown) {
186
- await hooks.emit('kubb:error', { error: unknown.cause ?? new Error(unknown.message) })
187
- } else {
188
- await Diagnostics.emit(hooks, diagnostic)
189
- }
190
- }
191
-
192
- // Only an error-severity diagnostic fails the run. Warnings and info do not.
193
- if (Diagnostics.hasError(diagnostics)) {
194
- await hooks.emit('kubb:generation:end', { config, storage: kubb.storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart })
195
-
196
- await reportTelemetry('failed')
197
- return false
198
- }
199
-
200
- const outputPath = path.resolve(config.root, config.output.path)
201
-
202
- // The build succeeded. The formatter, linter, and post-generate hooks run after it. Their
203
- // failures used to only emit `kubb:error`, so they never reached the summary, the json report,
204
- // or the exit code. Collect them as coded diagnostics here.
205
- const outputDiagnostics: Array<Diagnostic> = []
206
-
207
- const toolPasses = [
208
- config.output.format && {
209
- code: Diagnostics.code.formatFailed,
210
- toolValue: config.output.format,
211
- detect: () => detectTool(['oxfmt', 'biome', 'prettier'] as const),
212
- toolMap: formatters,
213
- toolLabel: 'formatter',
214
- successPrefix: 'Formatting',
215
- noToolMessage: 'No formatter found (oxfmt, biome, or prettier). Skipping formatting.',
216
- onStart: () => hooks.emit('kubb:format:start'),
217
- onEnd: () => hooks.emit('kubb:format:end'),
218
- },
219
- config.output.lint && {
220
- code: Diagnostics.code.lintFailed,
221
- toolValue: config.output.lint,
222
- detect: () => detectTool(['oxlint', 'biome', 'eslint'] as const),
223
- toolMap: linters,
224
- toolLabel: 'linter',
225
- successPrefix: 'Linting',
226
- noToolMessage: 'No linter found (oxlint, biome, or eslint). Skipping linting.',
227
- onStart: () => hooks.emit('kubb:lint:start'),
228
- onEnd: () => hooks.emit('kubb:lint:end'),
229
- },
230
- ].filter(Boolean) as Array<{ code: ProblemDiagnostic['code'] } & Omit<RunToolPassOptions, 'configName' | 'outputPath' | 'logLevel' | 'hooks'>>
231
-
232
- for (const { code, ...pass } of toolPasses) {
233
- try {
234
- await runToolPass({ ...pass, configName: config.name, outputPath, logLevel, hooks })
235
- } catch (caughtError) {
236
- const diagnostic = outputDiagnostic(code, pass.toolLabel, caughtError)
237
- outputDiagnostics.push(diagnostic)
238
- await Diagnostics.emit(hooks, diagnostic)
239
- }
240
- }
241
-
242
- if (config.hooks) {
243
- await hooks.emit('kubb:hooks:start')
244
- // `runHook` reports a failed `done` hook via `kubb:hook:end` rather than throwing, so listen
245
- // for it across this pass and collect each failure.
246
- const hookFailures: Array<Error> = []
247
- const onHookEnd = (ctx: { success: boolean; error: Error | null }) => {
248
- if (!ctx.success) hookFailures.push(ctx.error ?? new Error('Post-generate hook failed'))
249
- }
250
- hooks.on('kubb:hook:end', onHookEnd)
251
- try {
252
- await executeHooks({ configHooks: config.hooks, hooks })
253
- } finally {
254
- hooks.off('kubb:hook:end', onHookEnd)
255
- }
256
- for (const error of hookFailures) {
257
- const diagnostic = outputDiagnostic(Diagnostics.code.hookFailed, 'Post-generate hook', error)
258
- outputDiagnostics.push(diagnostic)
259
- await Diagnostics.emit(hooks, diagnostic)
260
- }
261
- await hooks.emit('kubb:hooks:end')
262
- }
263
-
264
- const finalDiagnostics = [...diagnostics, ...outputDiagnostics]
265
- const failed = Diagnostics.hasError(outputDiagnostics)
266
-
267
- if (!failed) {
268
- await hooks.emit('kubb:success', { message: 'Generation succeeded', info: inputPath })
269
- }
270
-
271
- await hooks.emit('kubb:generation:end', {
272
- config,
273
- storage: kubb.storage,
274
- diagnostics: finalDiagnostics,
275
- filesCreated: files.length,
276
- status: failed ? 'failed' : 'success',
277
- hrStart,
278
- })
279
-
280
- await reportTelemetry(failed ? 'failed' : 'success')
281
- return !failed
282
- }
283
-
284
- /**
285
- * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).
286
- */
287
- function outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {
288
- const error = toError(caughtError)
289
- return {
290
- code,
291
- severity: 'error',
292
- message: `${label} failed: ${error.message}`,
293
- help: 'Check that the tool is installed and that the command and its config are correct.',
294
- location: { kind: 'config' },
295
- cause: error,
296
- }
297
- }
298
-
299
- type GenerateCommandOptions = {
300
- input?: string
301
- configPath?: string
302
- logLevel: string
303
- watch: boolean
304
- reporters?: Array<ReporterName>
305
- }
306
-
307
- async function checkForUpdate(hooks: AsyncEventEmitter<KubbHooks>): Promise<void> {
308
- try {
309
- const res = await fetch(KUBB_NPM_PACKAGE_URL)
310
- const data = (await res.json()) as { version: string }
311
- if (data.version && version < data.version) {
312
- await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))
313
- }
314
- } catch {
315
- // Ignore network errors
316
- }
317
- }
318
-
319
- /**
320
- * Runs the full Kubb generation lifecycle for the given CLI options.
321
- * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),
322
- * checks for a newer version, and calls `generate` for each config entry.
323
- */
324
- export async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters }: GenerateCommandOptions): Promise<void> {
325
- const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info
326
- const hooks = new AsyncEventEmitterClass<KubbHooks>()
327
-
328
- // Load the config first so `config.reporters` can pick the reporters. A failure here has no
329
- // reporter installed yet, so fall back to the default `cli` reporter to surface it.
330
- let configs: Array<Config>
331
- let resolvedConfigPath: string
332
- try {
333
- const loaded = await getConfigs({
334
- configPath,
335
- input,
336
- watch,
337
- logLevel: logLevelKey as CLIOptions['logLevel'],
338
- })
339
- configs = loaded.configs
340
- resolvedConfigPath = loaded.configPath
341
- } catch (error) {
342
- await setupReporters(hooks, { logLevel, reporters: [cliReporter] })
343
- await hooks.emit('kubb:error', { error: toError(error) })
344
- process.exit(1)
345
- }
346
-
347
- // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config
348
- // always carries the available reporters (defineConfig registers the built-ins).
349
- const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']
350
- const available = configs[0]?.reporters ?? []
351
- const reporters = selectReporters(available, requestedNames)
352
- await setupReporters(hooks, { logLevel, reporters })
353
-
354
- await hooks.emit('kubb:lifecycle:start', { version })
355
-
356
- await checkForUpdate(hooks)
357
-
358
- try {
359
- const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)
360
-
361
- await hooks.emit('kubb:info', { message: 'Config loaded', info: relativeConfigPath })
362
- await hooks.emit('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })
363
-
364
- let anyFailed = false
365
- for (const config of configs) {
366
- if (config.input && 'path' in config.input && watch) {
367
- await startWatcher(
368
- [input || config.input.path],
369
- async (paths) => {
370
- // Don't removeAll(), that would also drop logger and lifecycle listeners.
371
- // Plugin listeners are already disposed by safeBuild's
372
- // setupResult.dispose() in its finally block, so re-running generate()
373
- // on the same hooks emitter is safe.
374
- await generate({ input, config, logLevel, hooks })
375
- clack.log.step(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))
376
- },
377
- { info: (msg) => clack.log.info(msg), error: (msg) => clack.log.error(msg) },
378
- )
379
- } else {
380
- try {
381
- const succeeded = await generate({ input, config, logLevel, hooks })
382
- if (!succeeded) anyFailed = true
383
- } catch (configError) {
384
- await hooks.emit('kubb:error', { error: toError(configError) })
385
- anyFailed = true
386
- }
387
- }
388
- }
389
-
390
- await hooks.emit('kubb:lifecycle:end')
391
-
392
- if (anyFailed) {
393
- process.exit(1)
394
- }
395
- } catch (error) {
396
- await hooks.emit('kubb:error', { error: toError(error) })
397
- process.exit(1)
398
- }
399
- }