@kubb/cli 5.0.0-beta.4 → 5.0.0-beta.40

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 (155) hide show
  1. package/README.md +198 -36
  2. package/dist/agent-DQerNyd8.cjs +70 -0
  3. package/dist/agent-DQerNyd8.cjs.map +1 -0
  4. package/dist/agent-ZKJkTTGN.js +68 -0
  5. package/dist/agent-ZKJkTTGN.js.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-CRm0XQPb.js} +1 -0
  7. package/dist/constants-84a47qA-.js +35 -0
  8. package/dist/constants-84a47qA-.js.map +1 -0
  9. package/dist/constants-AHhyFH15.cjs +139 -0
  10. package/dist/constants-AHhyFH15.cjs.map +1 -0
  11. package/dist/constants-BtmponZ3.cjs +58 -0
  12. package/dist/constants-BtmponZ3.cjs.map +1 -0
  13. package/dist/constants-C94RKp3A.js +116 -0
  14. package/dist/constants-C94RKp3A.js.map +1 -0
  15. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  16. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  17. package/dist/{define-Ctii4bel.js → define-DNG1U8ha.js} +2 -2
  18. package/dist/{define-Ctii4bel.js.map → define-DNG1U8ha.js.map} +1 -1
  19. package/dist/{errors-CjPmyZHy.js → errors-CoxrNXaA.js} +2 -2
  20. package/dist/{errors-CjPmyZHy.js.map → errors-CoxrNXaA.js.map} +1 -1
  21. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  22. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  23. package/dist/generate-40x9PP4o.js +77 -0
  24. package/dist/generate-40x9PP4o.js.map +1 -0
  25. package/dist/generate-DQLvFw4z.cjs +76 -0
  26. package/dist/generate-DQLvFw4z.cjs.map +1 -0
  27. package/dist/index.cjs +23 -14
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +23 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/init-CT9RChdK.js +53 -0
  33. package/dist/init-CT9RChdK.js.map +1 -0
  34. package/dist/init-sEaUN7Dj.cjs +53 -0
  35. package/dist/init-sEaUN7Dj.cjs.map +1 -0
  36. package/dist/mcp-Siyb6fTT.cjs +39 -0
  37. package/dist/mcp-Siyb6fTT.cjs.map +1 -0
  38. package/dist/mcp-cjPrOeot.js +39 -0
  39. package/dist/mcp-cjPrOeot.js.map +1 -0
  40. package/dist/{package-BapVyQ-w.cjs → package-BJ6qam2Y.cjs} +2 -2
  41. package/dist/package-BJ6qam2Y.cjs.map +1 -0
  42. package/dist/package-CR5vEK4K.js +6 -0
  43. package/dist/package-CR5vEK4K.js.map +1 -0
  44. package/dist/{agent-sdYBBgrd.js → run-BQ3Qj0xB.js} +46 -43
  45. package/dist/run-BQ3Qj0xB.js.map +1 -0
  46. package/dist/run-BQzoaxjR.js +32 -0
  47. package/dist/run-BQzoaxjR.js.map +1 -0
  48. package/dist/run-CGf0KEts.js +51 -0
  49. package/dist/run-CGf0KEts.js.map +1 -0
  50. package/dist/{generate-CNrRLY4n.js → run-CHZKHTv0.js} +832 -828
  51. package/dist/run-CHZKHTv0.js.map +1 -0
  52. package/dist/{init-CZ5Xq2Hd.cjs → run-C_NMctua.cjs} +107 -149
  53. package/dist/run-C_NMctua.cjs.map +1 -0
  54. package/dist/{generate-B1Pa2ho-.cjs → run-CcQawFNK.cjs} +784 -780
  55. package/dist/run-CcQawFNK.cjs.map +1 -0
  56. package/dist/run-CkTpemme.cjs +52 -0
  57. package/dist/run-CkTpemme.cjs.map +1 -0
  58. package/dist/run-Cl4SrSob.cjs +33 -0
  59. package/dist/run-Cl4SrSob.cjs.map +1 -0
  60. package/dist/{agent-B4cAAab2.cjs → run-D-s2LdlW.cjs} +46 -43
  61. package/dist/run-D-s2LdlW.cjs.map +1 -0
  62. package/dist/{init-eNRlotJK.js → run-D8dCWepS.js} +107 -149
  63. package/dist/run-D8dCWepS.js.map +1 -0
  64. package/dist/{shell-DLzN4fRo.js → shell-BrqyJdB7.js} +2 -2
  65. package/dist/{shell-DLzN4fRo.js.map → shell-BrqyJdB7.js.map} +1 -1
  66. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  67. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  68. package/dist/validate-8pgfxUTy.js +26 -0
  69. package/dist/validate-8pgfxUTy.js.map +1 -0
  70. package/dist/validate-CstV7Pc2.cjs +26 -0
  71. package/dist/validate-CstV7Pc2.cjs.map +1 -0
  72. package/package.json +16 -15
  73. package/src/commands/agent/start.ts +10 -7
  74. package/src/commands/agent.ts +3 -1
  75. package/src/commands/generate.ts +21 -13
  76. package/src/commands/init.ts +34 -3
  77. package/src/commands/mcp.ts +28 -4
  78. package/src/commands/validate.ts +6 -4
  79. package/src/constants.ts +3 -74
  80. package/src/index.ts +6 -4
  81. package/src/loggers/clackLogger.ts +143 -181
  82. package/src/loggers/githubActionsLogger.ts +119 -121
  83. package/src/loggers/plainLogger.ts +50 -100
  84. package/src/loggers/types.ts +6 -0
  85. package/src/loggers/utils.ts +190 -18
  86. package/src/runners/agent/run.ts +113 -0
  87. package/src/runners/agent/utils.ts +98 -0
  88. package/src/runners/generate/run.ts +411 -0
  89. package/src/runners/generate/utils.ts +222 -0
  90. package/src/runners/init/run.ts +212 -0
  91. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  92. package/src/runners/mcp/run.ts +37 -0
  93. package/src/runners/validate/run.ts +63 -0
  94. package/dist/agent-B4cAAab2.cjs.map +0 -1
  95. package/dist/agent-CR6Z96og.js +0 -56
  96. package/dist/agent-CR6Z96og.js.map +0 -1
  97. package/dist/agent-Dmxzqg4d.cjs +0 -58
  98. package/dist/agent-Dmxzqg4d.cjs.map +0 -1
  99. package/dist/agent-sdYBBgrd.js.map +0 -1
  100. package/dist/constants-CnDXa1R6.cjs +0 -148
  101. package/dist/constants-CnDXa1R6.cjs.map +0 -1
  102. package/dist/constants-aL3CP_Wq.js +0 -95
  103. package/dist/constants-aL3CP_Wq.js.map +0 -1
  104. package/dist/generate-B1Pa2ho-.cjs.map +0 -1
  105. package/dist/generate-BDGOOsBM.cjs +0 -65
  106. package/dist/generate-BDGOOsBM.cjs.map +0 -1
  107. package/dist/generate-CNrRLY4n.js.map +0 -1
  108. package/dist/generate-DuhxPLGr.js +0 -66
  109. package/dist/generate-DuhxPLGr.js.map +0 -1
  110. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  111. package/dist/init-CnZXHrbq.js +0 -25
  112. package/dist/init-CnZXHrbq.js.map +0 -1
  113. package/dist/init-NYJSZJSb.cjs +0 -25
  114. package/dist/init-NYJSZJSb.cjs.map +0 -1
  115. package/dist/init-eNRlotJK.js.map +0 -1
  116. package/dist/mcp-CYOgxB82.cjs +0 -47
  117. package/dist/mcp-CYOgxB82.cjs.map +0 -1
  118. package/dist/mcp-CdFWyrwi.cjs +0 -16
  119. package/dist/mcp-CdFWyrwi.cjs.map +0 -1
  120. package/dist/mcp-DhSxuDMD.js +0 -16
  121. package/dist/mcp-DhSxuDMD.js.map +0 -1
  122. package/dist/mcp-DmJm3TrU.js +0 -46
  123. package/dist/mcp-DmJm3TrU.js.map +0 -1
  124. package/dist/package-BapVyQ-w.cjs.map +0 -1
  125. package/dist/package-DyJE-qNq.js +0 -6
  126. package/dist/package-DyJE-qNq.js.map +0 -1
  127. package/dist/telemetry-DN95_2pF.cjs +0 -282
  128. package/dist/telemetry-DN95_2pF.cjs.map +0 -1
  129. package/dist/telemetry-LgT_sdPe.js +0 -245
  130. package/dist/telemetry-LgT_sdPe.js.map +0 -1
  131. package/dist/validate-C6npXzel.cjs +0 -25
  132. package/dist/validate-C6npXzel.cjs.map +0 -1
  133. package/dist/validate-kLJoT_hi.js +0 -33
  134. package/dist/validate-kLJoT_hi.js.map +0 -1
  135. package/dist/validate-n38Rh-Y7.js +0 -25
  136. package/dist/validate-n38Rh-Y7.js.map +0 -1
  137. package/dist/validate-yKKzqEZ5.cjs +0 -34
  138. package/dist/validate-yKKzqEZ5.cjs.map +0 -1
  139. package/src/loggers/fileSystemLogger.ts +0 -138
  140. package/src/runners/agent.ts +0 -155
  141. package/src/runners/generate.ts +0 -333
  142. package/src/runners/init.ts +0 -296
  143. package/src/runners/mcp.ts +0 -51
  144. package/src/runners/validate.ts +0 -39
  145. package/src/types.ts +0 -11
  146. package/src/utils/Writables.ts +0 -17
  147. package/src/utils/executeHooks.ts +0 -45
  148. package/src/utils/flags.ts +0 -9
  149. package/src/utils/getConfig.ts +0 -10
  150. package/src/utils/getCosmiConfig.ts +0 -80
  151. package/src/utils/getSummary.ts +0 -68
  152. package/src/utils/runHook.ts +0 -91
  153. package/src/utils/telemetry.ts +0 -273
  154. package/src/utils/watcher.ts +0 -19
  155. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
@@ -0,0 +1,411 @@
1
+ import { createHash } 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, detectFormatter, detectLinter, executeIfOnline, 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
+ selectReporters,
21
+ Telemetry,
22
+ } from '@kubb/core'
23
+ import { version } from '../../../package.json'
24
+ import { KUBB_NPM_PACKAGE_URL } from '../../constants.ts'
25
+ import setupReporters, { type HookSinkFactory } from '../../loggers/utils.ts'
26
+ import { executeHooks, getConfigs, runHook, startWatcher } from './utils.ts'
27
+
28
+ type GenerateProps = {
29
+ input?: string
30
+ config: Config
31
+ hooks: AsyncEventEmitter<KubbHooks>
32
+ logLevel: number
33
+ makeSink?: HookSinkFactory | null
34
+ }
35
+
36
+ type ToolMap = typeof formatters | typeof linters
37
+
38
+ type RunToolPassOptions = {
39
+ toolValue: string
40
+ detect: () => Promise<string | null>
41
+ toolMap: ToolMap
42
+ toolLabel: string
43
+ successPrefix: string
44
+ noToolMessage: string
45
+ configName: string | undefined
46
+ outputPath: string
47
+ logLevel: number
48
+ hooks: AsyncEventEmitter<KubbHooks>
49
+ makeSink?: HookSinkFactory | null
50
+ onStart: () => Promise<void>
51
+ onEnd: () => Promise<void>
52
+ }
53
+
54
+ /**
55
+ * Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
56
+ * avoiding the race where a synchronous emitter fires end before the listener is attached.
57
+ */
58
+ function waitForHookEnd(
59
+ hooks: AsyncEventEmitter<KubbHooks>,
60
+ hookId: string,
61
+ onSuccess: () => Promise<void> | void,
62
+ fallbackErrorMessage: string,
63
+ ): Promise<void> {
64
+ return new Promise<void>((resolve, reject) => {
65
+ const handler = (ctx: { id?: string; command: string; args?: ReadonlyArray<string>; success: boolean; error: Error | null }) => {
66
+ if (ctx.id !== hookId) return
67
+ hooks.off('kubb:hook:end', handler)
68
+ if (!ctx.success) {
69
+ reject(ctx.error ?? new Error(fallbackErrorMessage))
70
+ return
71
+ }
72
+ Promise.resolve(onSuccess()).then(resolve).catch(reject)
73
+ }
74
+ hooks.on('kubb:hook:end', handler)
75
+ })
76
+ }
77
+
78
+ async function runToolPass({
79
+ toolValue,
80
+ detect,
81
+ toolMap,
82
+ toolLabel,
83
+ successPrefix,
84
+ noToolMessage,
85
+ configName,
86
+ outputPath,
87
+ logLevel,
88
+ hooks,
89
+ makeSink,
90
+ onStart,
91
+ onEnd,
92
+ }: RunToolPassOptions) {
93
+ await onStart()
94
+
95
+ let resolvedTool = toolValue
96
+ if (resolvedTool === 'auto') {
97
+ const detected = await detect()
98
+ if (!detected) {
99
+ await hooks.emit('kubb:warn', { message: noToolMessage })
100
+ } else {
101
+ resolvedTool = detected
102
+ await hooks.emit('kubb:info', { message: `Auto-detected ${toolLabel}: ${styleText('dim', resolvedTool)}` })
103
+ }
104
+ }
105
+
106
+ let toolError: Error | undefined
107
+
108
+ // Nothing to lint or format when the output dir was never written. Skip so the tool
109
+ // (e.g. oxlint with --no-ignore) doesn't fail with "No files found to lint".
110
+ if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in toolMap && existsSync(outputPath)) {
111
+ const toolConfig = toolMap[resolvedTool as keyof ToolMap]
112
+ const hookId = createHash('sha256').update([configName, resolvedTool].filter(Boolean).join('-')).digest('hex')
113
+
114
+ const successMessage = [
115
+ `${successPrefix} with ${styleText('dim', resolvedTool)}`,
116
+ logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,
117
+ 'successfully',
118
+ ]
119
+ .filter(Boolean)
120
+ .join(' ')
121
+
122
+ try {
123
+ const hookArgs = toolConfig.args(outputPath)
124
+ const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')
125
+ const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit('kubb:success', { message: successMessage }), toolConfig.errorMessage)
126
+
127
+ await hooks.emit('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })
128
+
129
+ const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs, hookId) ?? {}
130
+
131
+ runHook({
132
+ id: hookId,
133
+ command: toolConfig.command,
134
+ args: hookArgs,
135
+ commandWithArgs,
136
+ hooks,
137
+ stream,
138
+ sink: { onLine, onStdout, onStderr },
139
+ }).catch(() => {})
140
+
141
+ await hookEndPromise
142
+ } catch (caughtError) {
143
+ // Don't render here. The caller turns this into a coded diagnostic and emits it through
144
+ // `Diagnostics.emit`, so format/lint/hook failures render like every other diagnostic.
145
+ toolError = toError(caughtError)
146
+ }
147
+ }
148
+
149
+ await onEnd()
150
+
151
+ if (toolError) {
152
+ throw toolError
153
+ }
154
+ }
155
+
156
+ async function generate(options: GenerateProps): Promise<boolean> {
157
+ const { input, hooks, logLevel, makeSink } = options
158
+
159
+ const hrStart = process.hrtime()
160
+ const inputPath = input ?? (options.config.input && 'path' in options.config.input ? options.config.input.path : undefined)
161
+
162
+ const config: Config = {
163
+ ...options.config,
164
+ input: inputPath ? { ...options.config.input, path: inputPath } : options.config.input,
165
+ ...options.config.output,
166
+ } satisfies Config
167
+
168
+ const kubb = createKubb(config, { hooks })
169
+
170
+ await hooks.emit('kubb:generation:start', { config })
171
+ await hooks.emit('kubb:info', { message: config.name ? `Setup generation ${styleText('bold', config.name)}` : 'Setup generation', info: inputPath })
172
+
173
+ await kubb.setup()
174
+
175
+ await hooks.emit('kubb:info', { message: config.name ? `Build generation ${styleText('bold', config.name)}` : 'Build generation', info: inputPath })
176
+
177
+ const { files, diagnostics, driver } = await kubb.safeBuild()
178
+
179
+ await hooks.emit('kubb:info', { message: 'Load summary' })
180
+
181
+ const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))
182
+
183
+ const reportTelemetry = (status: 'success' | 'failed') =>
184
+ Telemetry.send(Telemetry.build({ command: 'generate', kubbVersion: version, plugins: telemetryPlugins, hrStart, filesCreated: files.length, status }))
185
+
186
+ // Render every problem, not just on failure, so warnings and info surface too.
187
+ // `performance` diagnostics feed the summary, not the log.
188
+ for (const diagnostic of diagnostics) {
189
+ if (!Diagnostics.isProblem(diagnostic)) {
190
+ continue
191
+ }
192
+ const unknown = Diagnostics.narrow(diagnostic, Diagnostics.code.unknown)
193
+ if (unknown) {
194
+ await hooks.emit('kubb:error', { error: unknown.cause ?? new Error(unknown.message) })
195
+ } else {
196
+ await Diagnostics.emit(hooks, diagnostic)
197
+ }
198
+ }
199
+
200
+ // Only an error-severity diagnostic fails the run. Warnings and info do not.
201
+ if (Diagnostics.hasError(diagnostics)) {
202
+ await hooks.emit('kubb:generation:end', { config, storage: kubb.storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart })
203
+
204
+ await reportTelemetry('failed')
205
+ return false
206
+ }
207
+
208
+ const outputPath = path.resolve(config.root, config.output.path)
209
+
210
+ // The build succeeded. The formatter, linter, and post-generate hooks run after it. Their
211
+ // failures used to only emit `kubb:error`, so they never reached the summary, the json report,
212
+ // or the exit code. Collect them as coded diagnostics here.
213
+ const outputDiagnostics: Array<Diagnostic> = []
214
+
215
+ const toolPasses = [
216
+ config.output.format && {
217
+ code: Diagnostics.code.formatFailed,
218
+ toolValue: config.output.format,
219
+ detect: detectFormatter,
220
+ toolMap: formatters,
221
+ toolLabel: 'formatter',
222
+ successPrefix: 'Formatting',
223
+ noToolMessage: 'No formatter found (oxfmt, biome, or prettier). Skipping formatting.',
224
+ onStart: () => hooks.emit('kubb:format:start'),
225
+ onEnd: () => hooks.emit('kubb:format:end'),
226
+ },
227
+ config.output.lint && {
228
+ code: Diagnostics.code.lintFailed,
229
+ toolValue: config.output.lint,
230
+ detect: detectLinter,
231
+ toolMap: linters,
232
+ toolLabel: 'linter',
233
+ successPrefix: 'Linting',
234
+ noToolMessage: 'No linter found (oxlint, biome, or eslint). Skipping linting.',
235
+ onStart: () => hooks.emit('kubb:lint:start'),
236
+ onEnd: () => hooks.emit('kubb:lint:end'),
237
+ },
238
+ ].filter(Boolean) as Array<{ code: ProblemDiagnostic['code'] } & Omit<RunToolPassOptions, 'configName' | 'outputPath' | 'logLevel' | 'hooks'>>
239
+
240
+ for (const { code, ...pass } of toolPasses) {
241
+ try {
242
+ await runToolPass({ ...pass, configName: config.name, outputPath, logLevel, hooks, makeSink })
243
+ } catch (caughtError) {
244
+ const diagnostic = outputDiagnostic(code, pass.toolLabel, caughtError)
245
+ outputDiagnostics.push(diagnostic)
246
+ await Diagnostics.emit(hooks, diagnostic)
247
+ }
248
+ }
249
+
250
+ if (config.hooks) {
251
+ await hooks.emit('kubb:hooks:start')
252
+ // `runHook` reports a failed `done` hook via `kubb:hook:end` rather than throwing, so listen
253
+ // for it across this pass and collect each failure.
254
+ const hookFailures: Array<Error> = []
255
+ const onHookEnd = (ctx: { success: boolean; error: Error | null }) => {
256
+ if (!ctx.success) hookFailures.push(ctx.error ?? new Error('Post-generate hook failed'))
257
+ }
258
+ hooks.on('kubb:hook:end', onHookEnd)
259
+ try {
260
+ await executeHooks({ configHooks: config.hooks, hooks, makeSink })
261
+ } finally {
262
+ hooks.off('kubb:hook:end', onHookEnd)
263
+ }
264
+ for (const error of hookFailures) {
265
+ const diagnostic = outputDiagnostic(Diagnostics.code.hookFailed, 'Post-generate hook', error)
266
+ outputDiagnostics.push(diagnostic)
267
+ await Diagnostics.emit(hooks, diagnostic)
268
+ }
269
+ await hooks.emit('kubb:hooks:end')
270
+ }
271
+
272
+ const finalDiagnostics = [...diagnostics, ...outputDiagnostics]
273
+ const failed = Diagnostics.hasError(outputDiagnostics)
274
+
275
+ if (!failed) {
276
+ await hooks.emit('kubb:success', { message: 'Generation succeeded', info: inputPath })
277
+ }
278
+
279
+ await hooks.emit('kubb:generation:end', {
280
+ config,
281
+ storage: kubb.storage,
282
+ diagnostics: finalDiagnostics,
283
+ filesCreated: files.length,
284
+ status: failed ? 'failed' : 'success',
285
+ hrStart,
286
+ })
287
+
288
+ await reportTelemetry(failed ? 'failed' : 'success')
289
+ return !failed
290
+ }
291
+
292
+ /**
293
+ * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).
294
+ */
295
+ function outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {
296
+ const error = toError(caughtError)
297
+ return {
298
+ code,
299
+ severity: 'error',
300
+ message: `${label} failed: ${error.message}`,
301
+ help: 'Check that the tool is installed and that the command and its config are correct.',
302
+ location: { kind: 'config' },
303
+ cause: error,
304
+ }
305
+ }
306
+
307
+ type GenerateCommandOptions = {
308
+ input?: string
309
+ configPath?: string
310
+ logLevel: string
311
+ watch: boolean
312
+ reporters?: Array<ReporterName>
313
+ }
314
+
315
+ async function checkForUpdate(hooks: AsyncEventEmitter<KubbHooks>): Promise<void> {
316
+ await executeIfOnline(async () => {
317
+ try {
318
+ const res = await fetch(KUBB_NPM_PACKAGE_URL)
319
+ const data = (await res.json()) as { version: string }
320
+ if (data.version && version < data.version) {
321
+ await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))
322
+ }
323
+ } catch {
324
+ // Ignore network errors
325
+ }
326
+ })
327
+ }
328
+
329
+ /**
330
+ * Runs the full Kubb generation lifecycle for the given CLI options.
331
+ * Loads configs, sets up the selected reporters (CLI `--reporter` overrides `config.reporters`),
332
+ * checks for a newer version, and calls `generate` for each config entry.
333
+ */
334
+ export async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters }: GenerateCommandOptions): Promise<void> {
335
+ const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info
336
+ const hooks = new AsyncEventEmitterClass<KubbHooks>()
337
+
338
+ // Load the config first so `config.reporters` can pick the reporters. A failure here has no
339
+ // reporter installed yet, so fall back to the default `cli` reporter to surface it.
340
+ let configs: Array<Config>
341
+ let resolvedConfigPath: string
342
+ try {
343
+ const loaded = await getConfigs({
344
+ configPath,
345
+ input,
346
+ watch,
347
+ logLevel: logLevelKey as CLIOptions['logLevel'],
348
+ })
349
+ configs = loaded.configs
350
+ resolvedConfigPath = loaded.configPath
351
+ } catch (error) {
352
+ await setupReporters(hooks, { logLevel, reporters: [cliReporter] })
353
+ await hooks.emit('kubb:error', { error: toError(error) })
354
+ process.exit(1)
355
+ }
356
+
357
+ // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config
358
+ // always carries the available reporters (defineConfig registers the built-ins).
359
+ const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']
360
+ const available = configs[0]?.reporters ?? []
361
+ const reporters = selectReporters(available, requestedNames)
362
+ const makeSink = await setupReporters(hooks, { logLevel, reporters })
363
+
364
+ await hooks.emit('kubb:lifecycle:start', { version })
365
+
366
+ await checkForUpdate(hooks)
367
+
368
+ try {
369
+ const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)
370
+
371
+ await hooks.emit('kubb:config:start')
372
+ await hooks.emit('kubb:info', { message: 'Config loaded', info: relativeConfigPath })
373
+ await hooks.emit('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })
374
+ await hooks.emit('kubb:config:end', { configs })
375
+
376
+ let anyFailed = false
377
+ for (const config of configs) {
378
+ if (config.input && 'path' in config.input && watch) {
379
+ await startWatcher(
380
+ [input || config.input.path],
381
+ async (paths) => {
382
+ // Don't removeAll(), that would also drop logger and lifecycle listeners.
383
+ // Plugin and middleware listeners are already disposed by safeBuild's
384
+ // setupResult.dispose() in its finally block, so re-running generate()
385
+ // on the same hooks emitter is safe.
386
+ await generate({ input, config, logLevel, hooks, makeSink })
387
+ clack.log.step(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))
388
+ },
389
+ { info: (msg) => clack.log.info(msg), error: (msg) => clack.log.error(msg) },
390
+ )
391
+ } else {
392
+ try {
393
+ const succeeded = await generate({ input, config, logLevel, hooks, makeSink })
394
+ if (!succeeded) anyFailed = true
395
+ } catch (configError) {
396
+ await hooks.emit('kubb:error', { error: toError(configError) })
397
+ anyFailed = true
398
+ }
399
+ }
400
+ }
401
+
402
+ await hooks.emit('kubb:lifecycle:end')
403
+
404
+ if (anyFailed) {
405
+ process.exit(1)
406
+ }
407
+ } catch (error) {
408
+ await hooks.emit('kubb:error', { error: toError(error) })
409
+ process.exit(1)
410
+ }
411
+ }
@@ -0,0 +1,222 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { styleText } from 'node:util'
3
+ import type { AsyncEventEmitter } from '@internals/utils'
4
+ import { toError, tokenize } from '@internals/utils'
5
+ import type { CLIOptions, Config, KubbHooks, PossibleConfig } from '@kubb/core'
6
+ import { cosmiconfig } from 'cosmiconfig'
7
+ import { createJiti } from 'jiti'
8
+ import { NonZeroExitError, x } from 'tinyexec'
9
+ import type { HookSinkFactory, HookSinkOptions } from '../../loggers/utils.ts'
10
+ import { WATCHER_IGNORED_PATHS } from '../../constants.ts'
11
+
12
+ type CosmiconfigResult = {
13
+ filepath: string
14
+ isEmpty?: boolean
15
+ config: PossibleConfig<CLIOptions>
16
+ }
17
+
18
+ const jiti = createJiti(import.meta.url, {
19
+ jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },
20
+ moduleCache: false,
21
+ })
22
+
23
+ const tsLoader = (configFile: string) => jiti.import(configFile, { default: true })
24
+
25
+ const MODULE_NAME = 'kubb'
26
+
27
+ const BASE_SEARCH_PLACES = [
28
+ 'package.json',
29
+ `.${MODULE_NAME}rc`,
30
+ `.${MODULE_NAME}rc.json`,
31
+ `.${MODULE_NAME}rc.yaml`,
32
+ `.${MODULE_NAME}rc.yml`,
33
+ `.${MODULE_NAME}rc.ts`,
34
+ `.${MODULE_NAME}rc.mts`,
35
+ `.${MODULE_NAME}rc.cts`,
36
+ `.${MODULE_NAME}rc.js`,
37
+ `.${MODULE_NAME}rc.mjs`,
38
+ `.${MODULE_NAME}rc.cjs`,
39
+ `${MODULE_NAME}.config.ts`,
40
+ `${MODULE_NAME}.config.mts`,
41
+ `${MODULE_NAME}.config.cts`,
42
+ `${MODULE_NAME}.config.js`,
43
+ `${MODULE_NAME}.config.mjs`,
44
+ `${MODULE_NAME}.config.cjs`,
45
+ ]
46
+
47
+ const SEARCH_PLACES = ['', '.config/', 'configs/'].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`))
48
+
49
+ async function getCosmiConfig(configFile?: string): Promise<CosmiconfigResult> {
50
+ const explorer = cosmiconfig(MODULE_NAME, {
51
+ cache: false,
52
+ searchPlaces: SEARCH_PLACES,
53
+ loaders: { '.ts': tsLoader, '.mts': tsLoader, '.cts': tsLoader },
54
+ })
55
+
56
+ let result: CosmiconfigResult
57
+ try {
58
+ result = (configFile ? await explorer.load(configFile) : await explorer.search()) as CosmiconfigResult
59
+ } catch (error) {
60
+ throw new Error('Config failed loading', { cause: error })
61
+ }
62
+
63
+ if (!result?.config || result.isEmpty) {
64
+ throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')
65
+ }
66
+
67
+ return result
68
+ }
69
+
70
+ type GetConfigsOptions = {
71
+ /**
72
+ * Explicit path to the Kubb config file. When omitted, cosmiconfig searches from the current directory.
73
+ */
74
+ configPath?: string
75
+ /**
76
+ * Optional OpenAPI input path that overrides `config.input.path` for this run.
77
+ */
78
+ input?: string
79
+ /**
80
+ * Watch flag forwarded to the user's `defineConfig` function.
81
+ */
82
+ watch?: boolean
83
+ /**
84
+ * Log level forwarded to the user's `defineConfig` function.
85
+ */
86
+ logLevel?: CLIOptions['logLevel']
87
+ }
88
+
89
+ type GetConfigsResult = {
90
+ /**
91
+ * Absolute path to the resolved config file.
92
+ */
93
+ configPath: string
94
+ /**
95
+ * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.
96
+ */
97
+ configs: Array<Config>
98
+ }
99
+
100
+ /**
101
+ * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
102
+ * Every config in the result is guaranteed to have a `plugins` array.
103
+ */
104
+ export async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {
105
+ const result = await getCosmiConfig(configPath)
106
+ const cli: CLIOptions = { config: configPath, input, watch, logLevel }
107
+ const resolved = await (typeof result.config === 'function' ? result.config(cli) : result.config)
108
+ const userConfigs = Array.isArray(resolved) ? resolved : [resolved]
109
+
110
+ return {
111
+ configPath: result.filepath,
112
+ configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),
113
+ }
114
+ }
115
+
116
+ type ExecuteHooksOptions = {
117
+ configHooks: NonNullable<Config['hooks']>
118
+ hooks: AsyncEventEmitter<KubbHooks>
119
+ makeSink?: HookSinkFactory | null
120
+ }
121
+
122
+ /**
123
+ * Runs the `done` hooks defined in a Kubb config in sequence.
124
+ */
125
+ export async function executeHooks({ configHooks, hooks, makeSink }: ExecuteHooksOptions): Promise<void> {
126
+ const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)
127
+
128
+ for (const command of commands) {
129
+ const [cmd, ...args] = tokenize(command)
130
+ if (!cmd) continue
131
+
132
+ const hookId = createHash('sha256').update(command).digest('hex')
133
+ const commandWithArgs = [cmd, ...args].join(' ')
134
+
135
+ await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })
136
+
137
+ const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs, hookId) ?? {}
138
+ await runHook({ id: hookId, command: cmd, args, commandWithArgs, hooks, stream, sink: { onLine, onStdout, onStderr } })
139
+ }
140
+ }
141
+
142
+ type RunHookOptions = {
143
+ id: string
144
+ command: string
145
+ args?: ReadonlyArray<string>
146
+ commandWithArgs: string
147
+ hooks: AsyncEventEmitter<KubbHooks>
148
+ stream?: boolean
149
+ sink?: HookSinkOptions
150
+ }
151
+
152
+ export async function runHook({ id, command, args, commandWithArgs, hooks, stream = false, sink }: RunHookOptions): Promise<void> {
153
+ const emitEnd = (success: boolean, error: Error | null) => hooks.emit('kubb:hook:end', { command, args, id, success, error })
154
+
155
+ try {
156
+ const proc = x(command, [...(args ?? [])], {
157
+ nodeOptions: { detached: process.platform !== 'win32' },
158
+ throwOnError: true,
159
+ })
160
+
161
+ if (stream && sink?.onLine) {
162
+ for await (const line of proc) {
163
+ sink.onLine(line)
164
+ }
165
+ }
166
+
167
+ await proc
168
+ await hooks.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
169
+ await emitEnd(true, null)
170
+ } catch (err) {
171
+ if (!(err instanceof NonZeroExitError)) {
172
+ const error = toError(err)
173
+ await emitEnd(false, error)
174
+ return
175
+ }
176
+
177
+ const stderr = err.output?.stderr ?? ''
178
+ const stdout = err.output?.stdout ?? ''
179
+
180
+ if (stderr) sink?.onStderr?.(stderr)
181
+ if (stdout) sink?.onStdout?.(stdout)
182
+
183
+ const error = new Error(`Hook execute failed: ${commandWithArgs}`)
184
+ // Signal the failure via `kubb:hook:end` only. The caller turns it into a coded diagnostic and
185
+ // emits that through `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.
186
+ await emitEnd(false, error)
187
+ }
188
+ }
189
+
190
+ type WatcherLog = {
191
+ info: (message: string) => void
192
+ error: (message: string) => void
193
+ }
194
+
195
+ /**
196
+ * Starts a file watcher on the given paths and calls `cb` on any change.
197
+ * Ignores `.git` and `node_modules` directories.
198
+ */
199
+ export async function startWatcher(
200
+ path: Array<string>,
201
+ cb: (path: Array<string>) => Promise<void>,
202
+ log: WatcherLog = { info: console.log, error: console.log },
203
+ ): Promise<void> {
204
+ const { watch } = await import('chokidar')
205
+ const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
206
+
207
+ process.once('SIGINT', () => {
208
+ watcher.close()
209
+ })
210
+ process.once('SIGTERM', () => {
211
+ watcher.close()
212
+ })
213
+
214
+ watcher.on('all', async (type, file) => {
215
+ log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
216
+ try {
217
+ await cb(path)
218
+ } catch (_e) {
219
+ log.error(styleText('red', 'Watcher failed'))
220
+ }
221
+ })
222
+ }