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