@kubb/cli 5.0.0-beta.62 → 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 (93) hide show
  1. package/bin/kubb.js +9 -3
  2. package/dist/{Telemetry-DrppRqqW.cjs → Telemetry-CfPP7MYq.cjs} +6 -5
  3. package/dist/Telemetry-CfPP7MYq.cjs.map +1 -0
  4. package/dist/{Telemetry-CVdyJarO.js → Telemetry-uAr3lK_-.js} +4 -3
  5. package/dist/Telemetry-uAr3lK_-.js.map +1 -0
  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-BI0qGM4M.js → generate-DHQnl_F1.js} +4 -4
  15. package/dist/{generate-BI0qGM4M.js.map → generate-DHQnl_F1.js.map} +1 -1
  16. package/dist/{generate-C4BcNMRq.cjs → generate-svfhwhEK.cjs} +4 -4
  17. package/dist/{generate-C4BcNMRq.cjs.map → generate-svfhwhEK.cjs.map} +1 -1
  18. package/dist/index.cjs +13 -8
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +6 -1
  21. package/dist/index.js +13 -8
  22. package/dist/index.js.map +1 -1
  23. package/dist/{init-BzS2oVRl.js → init-B02NN_88.js} +5 -5
  24. package/dist/{init-BzS2oVRl.js.map → init-B02NN_88.js.map} +1 -1
  25. package/dist/{init-DbmOhX2-.cjs → init-Bg_68Ok6.cjs} +5 -5
  26. package/dist/{init-DbmOhX2-.cjs.map → init-Bg_68Ok6.cjs.map} +1 -1
  27. package/dist/{mcp-AyUriTgO.cjs → mcp-DUzIXdRV.cjs} +7 -25
  28. package/dist/mcp-DUzIXdRV.cjs.map +1 -0
  29. package/dist/mcp-ZJQksVUU.js +21 -0
  30. package/dist/mcp-ZJQksVUU.js.map +1 -0
  31. package/dist/package-BoXPsuNH.js +6 -0
  32. package/dist/package-BoXPsuNH.js.map +1 -0
  33. package/dist/{package-DXJ46ia8.cjs → package-Cdu8eJMb.cjs} +2 -2
  34. package/dist/package-Cdu8eJMb.cjs.map +1 -0
  35. package/dist/{run-DpKny2hT.cjs → run-B4rIAnch.cjs} +7 -7
  36. package/dist/run-B4rIAnch.cjs.map +1 -0
  37. package/dist/{run-9ZhHuNZQ.cjs → run-BM1t8CSM.cjs} +10 -10
  38. package/dist/run-BM1t8CSM.cjs.map +1 -0
  39. package/dist/{run-h8NTawHO.js → run-BlFVmIJl.js} +9 -9
  40. package/dist/run-BlFVmIJl.js.map +1 -0
  41. package/dist/{run-BQO_tPlc.cjs → run-CBc896in.cjs} +5 -5
  42. package/dist/{run-BQO_tPlc.cjs.map → run-CBc896in.cjs.map} +1 -1
  43. package/dist/{run-Drs-S6sa.cjs → run-CD3BE8yP.cjs} +70 -70
  44. package/dist/run-CD3BE8yP.cjs.map +1 -0
  45. package/dist/{run-CYnDu3ch.js → run-D_dWNFhX.js} +4 -4
  46. package/dist/{run-CYnDu3ch.js.map → run-D_dWNFhX.js.map} +1 -1
  47. package/dist/{run-C_7kOXnc.js → run-DkW2VQBq.js} +68 -68
  48. package/dist/run-DkW2VQBq.js.map +1 -0
  49. package/dist/{run-BG7Giryi.js → run-DzYeru-0.js} +3 -3
  50. package/dist/run-DzYeru-0.js.map +1 -0
  51. package/dist/{tools-_Xp8-_zy.cjs → tools-CZT9wSA6.cjs} +2 -2
  52. package/dist/{tools-_Xp8-_zy.cjs.map → tools-CZT9wSA6.cjs.map} +1 -1
  53. package/dist/{tools-BU99bhi8.js → tools-D0UogMU3.js} +2 -2
  54. package/dist/{tools-BU99bhi8.js.map → tools-D0UogMU3.js.map} +1 -1
  55. package/dist/{validate-CfdPbbz_.cjs → validate-B3EwltHu.cjs} +5 -5
  56. package/dist/{validate-CfdPbbz_.cjs.map → validate-B3EwltHu.cjs.map} +1 -1
  57. package/dist/{validate-jZWMwN4r.js → validate-DXYcZCm_.js} +5 -5
  58. package/dist/{validate-jZWMwN4r.js.map → validate-DXYcZCm_.js.map} +1 -1
  59. package/package.json +7 -8
  60. package/dist/Telemetry-CVdyJarO.js.map +0 -1
  61. package/dist/Telemetry-DrppRqqW.cjs.map +0 -1
  62. package/dist/mcp-AyUriTgO.cjs.map +0 -1
  63. package/dist/mcp-BY4D1lHt.js +0 -39
  64. package/dist/mcp-BY4D1lHt.js.map +0 -1
  65. package/dist/package-BSv0yWfQ.js +0 -6
  66. package/dist/package-BSv0yWfQ.js.map +0 -1
  67. package/dist/package-DXJ46ia8.cjs.map +0 -1
  68. package/dist/run-9ZhHuNZQ.cjs.map +0 -1
  69. package/dist/run-BG7Giryi.js.map +0 -1
  70. package/dist/run-C_7kOXnc.js.map +0 -1
  71. package/dist/run-DpKny2hT.cjs.map +0 -1
  72. package/dist/run-Drs-S6sa.cjs.map +0 -1
  73. package/dist/run-h8NTawHO.js.map +0 -1
  74. package/src/Telemetry.ts +0 -297
  75. package/src/commands/generate.ts +0 -65
  76. package/src/commands/init.ts +0 -51
  77. package/src/commands/mcp.ts +0 -36
  78. package/src/commands/validate.ts +0 -22
  79. package/src/constants.ts +0 -19
  80. package/src/index.ts +0 -27
  81. package/src/loggers/clackLogger.ts +0 -392
  82. package/src/loggers/defineLogger.ts +0 -59
  83. package/src/loggers/plainLogger.ts +0 -199
  84. package/src/loggers/types.ts +0 -6
  85. package/src/loggers/utils.ts +0 -249
  86. package/src/runners/generate/run.ts +0 -399
  87. package/src/runners/generate/utils.ts +0 -229
  88. package/src/runners/init/run.ts +0 -210
  89. package/src/runners/init/utils.ts +0 -39
  90. package/src/runners/mcp/run.ts +0 -37
  91. package/src/runners/validate/run.ts +0 -63
  92. /package/dist/{chunk-Bx3C2hgW.cjs → rolldown-runtime-Bx3C2hgW.cjs} +0 -0
  93. /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -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 can't 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 selected reporters (CLI `--reporter` overrides `config.reporters`),
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
- }
@@ -1,229 +0,0 @@
1
- import { hash } from 'node:crypto'
2
- import { styleText } from 'node:util'
3
- import { createModuleLoader } from '@internals/shared'
4
- import type { AsyncEventEmitter } from '@internals/utils'
5
- import { toError } from '@internals/utils'
6
- import type { CLIOptions, Config, KubbHooks, PossibleConfig } from '@kubb/core'
7
- import { cosmiconfig } from 'cosmiconfig'
8
- import { NonZeroExitError, x } from 'tinyexec'
9
- import { WATCHER_IGNORED_PATHS } from '../../constants.ts'
10
-
11
- type CosmiconfigResult = {
12
- filepath: string
13
- isEmpty?: boolean
14
- config: PossibleConfig<CLIOptions>
15
- }
16
-
17
- const loader = createModuleLoader()
18
-
19
- const tsLoader = (configFile: string) => loader.load(configFile, { default: true })
20
-
21
- const MODULE_NAME = 'kubb'
22
-
23
- const BASE_SEARCH_PLACES = [
24
- 'package.json',
25
- `.${MODULE_NAME}rc`,
26
- `.${MODULE_NAME}rc.json`,
27
- `.${MODULE_NAME}rc.yaml`,
28
- `.${MODULE_NAME}rc.yml`,
29
- `.${MODULE_NAME}rc.ts`,
30
- `.${MODULE_NAME}rc.mts`,
31
- `.${MODULE_NAME}rc.cts`,
32
- `.${MODULE_NAME}rc.js`,
33
- `.${MODULE_NAME}rc.mjs`,
34
- `.${MODULE_NAME}rc.cjs`,
35
- `${MODULE_NAME}.config.ts`,
36
- `${MODULE_NAME}.config.mts`,
37
- `${MODULE_NAME}.config.cts`,
38
- `${MODULE_NAME}.config.js`,
39
- `${MODULE_NAME}.config.mjs`,
40
- `${MODULE_NAME}.config.cjs`,
41
- ]
42
-
43
- const SEARCH_PLACES = ['', '.config/', 'configs/'].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`))
44
-
45
- async function getCosmiConfig(configFile?: string): Promise<CosmiconfigResult> {
46
- const explorer = cosmiconfig(MODULE_NAME, {
47
- cache: false,
48
- searchPlaces: SEARCH_PLACES,
49
- loaders: { '.ts': tsLoader, '.mts': tsLoader, '.cts': tsLoader },
50
- })
51
-
52
- let result: CosmiconfigResult
53
- try {
54
- result = (configFile ? await explorer.load(configFile) : await explorer.search()) as CosmiconfigResult
55
- } catch (error) {
56
- throw new Error('Config failed loading', { cause: error })
57
- }
58
-
59
- if (!result?.config || result.isEmpty) {
60
- throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')
61
- }
62
-
63
- return result
64
- }
65
-
66
- type GetConfigsOptions = {
67
- /**
68
- * Explicit path to the Kubb config file. When omitted, cosmiconfig searches from the current directory.
69
- */
70
- configPath?: string
71
- /**
72
- * Optional OpenAPI input path that overrides `config.input.path` for this run.
73
- */
74
- input?: string
75
- /**
76
- * Watch flag forwarded to the user's `defineConfig` function.
77
- */
78
- watch?: boolean
79
- /**
80
- * Log level forwarded to the user's `defineConfig` function.
81
- */
82
- logLevel?: CLIOptions['logLevel']
83
- }
84
-
85
- type GetConfigsResult = {
86
- /**
87
- * Absolute path to the resolved config file.
88
- */
89
- configPath: string
90
- /**
91
- * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.
92
- */
93
- configs: Array<Config>
94
- }
95
-
96
- /**
97
- * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
98
- * Every config in the result is guaranteed to have a `plugins` array.
99
- */
100
- export async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {
101
- const result = await getCosmiConfig(configPath)
102
- const cli: CLIOptions = { config: configPath, input, watch, logLevel }
103
- const resolved = await (typeof result.config === 'function' ? result.config(cli) : result.config)
104
- const userConfigs = Array.isArray(resolved) ? resolved : [resolved]
105
-
106
- return {
107
- configPath: result.filepath,
108
- configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),
109
- }
110
- }
111
-
112
- type ExecuteHooksOptions = {
113
- configHooks: NonNullable<Config['hooks']>
114
- hooks: AsyncEventEmitter<KubbHooks>
115
- }
116
-
117
- /**
118
- * Tokenizes a shell command string, respecting single and double quotes.
119
- *
120
- * @example
121
- * ```ts
122
- * tokenize('git commit -m "initial commit"')
123
- * // → ['git', 'commit', '-m', 'initial commit']
124
- * ```
125
- */
126
- function tokenize(command: string): Array<string> {
127
- return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ''))
128
- }
129
-
130
- /**
131
- * Runs the `done` hooks defined in a Kubb config in sequence.
132
- */
133
- export async function executeHooks({ configHooks, hooks }: ExecuteHooksOptions): Promise<void> {
134
- const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)
135
-
136
- for (const command of commands) {
137
- const [cmd, ...args] = tokenize(command)
138
- if (!cmd) continue
139
-
140
- const hookId = hash('sha256', command, 'hex')
141
- const commandWithArgs = [cmd, ...args].join(' ')
142
-
143
- await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })
144
- await runHook({ id: hookId, command: cmd, args, commandWithArgs, hooks })
145
- }
146
- }
147
-
148
- type RunHookOptions = {
149
- id: string
150
- command: string
151
- args?: ReadonlyArray<string>
152
- commandWithArgs: string
153
- hooks: AsyncEventEmitter<KubbHooks>
154
- }
155
-
156
- export async function runHook({ id, command, args, commandWithArgs, hooks }: RunHookOptions): Promise<void> {
157
- const emitEnd = (success: boolean, error: Error | null, output?: { stdout?: string; stderr?: string }) =>
158
- hooks.emit('kubb:hook:end', { command, args, id, success, error, ...output })
159
-
160
- // Only stream line-by-line when a logger is listening, so the non-streaming plain
161
- // logger doesn't pay to iterate the subprocess output.
162
- const stream = hooks.listenerCount('kubb:hook:line') > 0
163
-
164
- try {
165
- const proc = x(command, [...(args ?? [])], {
166
- nodeOptions: { detached: process.platform !== 'win32' },
167
- throwOnError: true,
168
- })
169
-
170
- if (stream) {
171
- for await (const line of proc) {
172
- await hooks.emit('kubb:hook:line', { id, line })
173
- }
174
- }
175
-
176
- await proc
177
- await hooks.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
178
- await emitEnd(true, null)
179
- } catch (err) {
180
- if (!(err instanceof NonZeroExitError)) {
181
- const error = toError(err)
182
- await emitEnd(false, error)
183
- return
184
- }
185
-
186
- const stderr = err.output?.stderr ?? ''
187
- const stdout = err.output?.stdout ?? ''
188
-
189
- const error = new Error(`Hook execute failed: ${commandWithArgs}`)
190
- // Signal the failure via `kubb:hook:end` only, carrying the captured output so the logger can
191
- // render it. The caller turns this into a coded diagnostic and emits that through
192
- // `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.
193
- await emitEnd(false, error, { stdout, stderr })
194
- }
195
- }
196
-
197
- type WatcherLog = {
198
- info: (message: string) => void
199
- error: (message: string) => void
200
- }
201
-
202
- /**
203
- * Starts a file watcher on the given paths and calls `cb` on any change.
204
- * Ignores `.git` and `node_modules` directories.
205
- */
206
- export async function startWatcher(
207
- path: Array<string>,
208
- cb: (path: Array<string>) => Promise<void>,
209
- log: WatcherLog = { info: console.log, error: console.log },
210
- ): Promise<void> {
211
- const { watch } = await import('chokidar')
212
- const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
213
-
214
- process.once('SIGINT', () => {
215
- watcher.close()
216
- })
217
- process.once('SIGTERM', () => {
218
- watcher.close()
219
- })
220
-
221
- watcher.on('all', async (type, file) => {
222
- log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
223
- try {
224
- await cb(path)
225
- } catch (_e) {
226
- log.error(styleText('red', 'Watcher failed'))
227
- }
228
- })
229
- }