@kubb/cli 5.0.0-beta.3 → 5.0.0-beta.30
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/README.md +177 -26
- package/dist/agent-CPKt8QQU.js +68 -0
- package/dist/agent-CPKt8QQU.js.map +1 -0
- package/dist/agent-lxTI4Krn.cjs +70 -0
- package/dist/agent-lxTI4Krn.cjs.map +1 -0
- package/dist/{chunk--u3MIqq1.js → chunk-BvFE5Tac.js} +1 -0
- package/dist/constants-B2JTeRBb.js +42 -0
- package/dist/constants-B2JTeRBb.js.map +1 -0
- package/dist/constants-BINTA5VZ.cjs +77 -0
- package/dist/constants-BINTA5VZ.cjs.map +1 -0
- package/dist/constants-BYGmiFs0.cjs +139 -0
- package/dist/constants-BYGmiFs0.cjs.map +1 -0
- package/dist/constants-DSJ-Xrbv.js +116 -0
- package/dist/constants-DSJ-Xrbv.js.map +1 -0
- package/dist/define-Bdn8j5VM.cjs.map +1 -1
- package/dist/{define-Ctii4bel.js → define-m_fp-Aqm.js} +2 -2
- package/dist/{define-Ctii4bel.js.map → define-m_fp-Aqm.js.map} +1 -1
- package/dist/{errors-CjPmyZHy.js → errors-CINO1EIv.js} +2 -2
- package/dist/{errors-CjPmyZHy.js.map → errors-CINO1EIv.js.map} +1 -1
- package/dist/errors-CLCjoSg0.cjs.map +1 -1
- package/dist/{generate-BzCMyyNN.cjs → generate-DgTJz23F.cjs} +10 -4
- package/dist/generate-DgTJz23F.cjs.map +1 -0
- package/dist/{generate-CTdVvIaP.js → generate-qCPyPiD6.js} +12 -6
- package/dist/generate-qCPyPiD6.js.map +1 -0
- package/dist/index.cjs +20 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +22 -13
- package/dist/index.js.map +1 -1
- package/dist/init-CM61rK5A.cjs +53 -0
- package/dist/init-CM61rK5A.cjs.map +1 -0
- package/dist/init-_-CN-ASE.js +53 -0
- package/dist/init-_-CN-ASE.js.map +1 -0
- package/dist/mcp-1ld_vD4n.js +39 -0
- package/dist/mcp-1ld_vD4n.js.map +1 -0
- package/dist/mcp-IMkVgOtF.cjs +39 -0
- package/dist/mcp-IMkVgOtF.cjs.map +1 -0
- package/dist/package-BDL80yHv.js +6 -0
- package/dist/package-BDL80yHv.js.map +1 -0
- package/dist/{package-DcmDg_mw.cjs → package-CHmy7tzG.cjs} +2 -2
- package/dist/package-CHmy7tzG.cjs.map +1 -0
- package/dist/run-B11-UaUs.cjs +33 -0
- package/dist/run-B11-UaUs.cjs.map +1 -0
- package/dist/{init-eNRlotJK.js → run-BNqMQygv.js} +107 -149
- package/dist/run-BNqMQygv.js.map +1 -0
- package/dist/{init-CZ5Xq2Hd.cjs → run-BnGfi7Cp.cjs} +105 -147
- package/dist/run-BnGfi7Cp.cjs.map +1 -0
- package/dist/{generate-BL-Kp5GY.js → run-BonExv0-.js} +561 -493
- package/dist/run-BonExv0-.js.map +1 -0
- package/dist/{agent-sdYBBgrd.js → run-BzpYYOQs.js} +46 -43
- package/dist/run-BzpYYOQs.js.map +1 -0
- package/dist/run-CCZ24VKk.js +51 -0
- package/dist/run-CCZ24VKk.js.map +1 -0
- package/dist/run-CQbj3ley.cjs +52 -0
- package/dist/run-CQbj3ley.cjs.map +1 -0
- package/dist/{agent-B4cAAab2.cjs → run-DwdAwnLG.cjs} +44 -41
- package/dist/run-DwdAwnLG.cjs.map +1 -0
- package/dist/run-PSA9X7ci.js +32 -0
- package/dist/run-PSA9X7ci.js.map +1 -0
- package/dist/{generate-DMqdAYqy.cjs → run-e1Pda1tW.cjs} +558 -490
- package/dist/run-e1Pda1tW.cjs.map +1 -0
- package/dist/shell-475fQKaX.cjs.map +1 -1
- package/dist/{shell-DLzN4fRo.js → shell-CN6DNqeC.js} +2 -2
- package/dist/{shell-DLzN4fRo.js.map → shell-CN6DNqeC.js.map} +1 -1
- package/dist/{telemetry-DN95_2pF.cjs → telemetry-B2iWkY5e.cjs} +5 -7
- package/dist/telemetry-B2iWkY5e.cjs.map +1 -0
- package/dist/{telemetry-LgT_sdPe.js → telemetry-BkektVz6.js} +6 -8
- package/dist/telemetry-BkektVz6.js.map +1 -0
- package/dist/validate-26X6uBG3.js +26 -0
- package/dist/validate-26X6uBG3.js.map +1 -0
- package/dist/validate-BAEo4Dcd.cjs +26 -0
- package/dist/validate-BAEo4Dcd.cjs.map +1 -0
- package/package.json +14 -14
- package/src/commands/agent/start.ts +10 -7
- package/src/commands/agent.ts +3 -1
- package/src/commands/generate.ts +5 -3
- 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 +2 -58
- package/src/index.ts +5 -3
- package/src/loggers/clackLogger.ts +85 -118
- package/src/loggers/fileSystemLogger.ts +28 -15
- package/src/loggers/githubActionsLogger.ts +87 -96
- package/src/loggers/plainLogger.ts +48 -81
- package/src/loggers/types.ts +6 -0
- package/src/loggers/utils.ts +235 -11
- package/src/runners/agent/run.ts +113 -0
- package/src/runners/agent/utils.ts +98 -0
- package/src/runners/generate/run.ts +321 -0
- package/src/runners/generate/utils.ts +225 -0
- package/src/runners/init/run.ts +212 -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/src/{utils/telemetry.ts → telemetry.ts} +27 -20
- package/dist/agent-B4cAAab2.cjs.map +0 -1
- package/dist/agent-BFACosbG.cjs +0 -58
- package/dist/agent-BFACosbG.cjs.map +0 -1
- package/dist/agent-s7TqqoTg.js +0 -56
- package/dist/agent-s7TqqoTg.js.map +0 -1
- package/dist/agent-sdYBBgrd.js.map +0 -1
- package/dist/constants-CnDXa1R6.cjs +0 -148
- package/dist/constants-CnDXa1R6.cjs.map +0 -1
- package/dist/constants-aL3CP_Wq.js +0 -95
- package/dist/constants-aL3CP_Wq.js.map +0 -1
- package/dist/generate-BL-Kp5GY.js.map +0 -1
- package/dist/generate-BzCMyyNN.cjs.map +0 -1
- package/dist/generate-CTdVvIaP.js.map +0 -1
- package/dist/generate-DMqdAYqy.cjs.map +0 -1
- package/dist/init-BHMGbly9.cjs +0 -25
- package/dist/init-BHMGbly9.cjs.map +0 -1
- package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
- package/dist/init-eNRlotJK.js.map +0 -1
- package/dist/init-qgpg-iRW.js +0 -25
- package/dist/init-qgpg-iRW.js.map +0 -1
- package/dist/mcp-BRp-2Rdc.js +0 -16
- package/dist/mcp-BRp-2Rdc.js.map +0 -1
- package/dist/mcp-CYOgxB82.cjs +0 -47
- package/dist/mcp-CYOgxB82.cjs.map +0 -1
- package/dist/mcp-DmJm3TrU.js +0 -46
- package/dist/mcp-DmJm3TrU.js.map +0 -1
- package/dist/mcp-N3mRyVuO.cjs +0 -16
- package/dist/mcp-N3mRyVuO.cjs.map +0 -1
- package/dist/package-DcmDg_mw.cjs.map +0 -1
- package/dist/package-DtuyzAVW.js +0 -6
- package/dist/package-DtuyzAVW.js.map +0 -1
- package/dist/telemetry-DN95_2pF.cjs.map +0 -1
- package/dist/telemetry-LgT_sdPe.js.map +0 -1
- package/dist/validate-CJpTOzKA.js +0 -25
- package/dist/validate-CJpTOzKA.js.map +0 -1
- package/dist/validate-DyTbv7Bc.cjs +0 -25
- package/dist/validate-DyTbv7Bc.cjs.map +0 -1
- package/dist/validate-kLJoT_hi.js +0 -33
- package/dist/validate-kLJoT_hi.js.map +0 -1
- package/dist/validate-yKKzqEZ5.cjs +0 -34
- package/dist/validate-yKKzqEZ5.cjs.map +0 -1
- 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 -80
- package/src/utils/getSummary.ts +0 -68
- package/src/utils/runHook.ts +0 -91
- package/src/utils/watcher.ts +0 -19
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { styleText } from 'node:util'
|
|
5
|
+
import * as clack from '@clack/prompts'
|
|
6
|
+
import type { AsyncEventEmitter } from '@internals/utils'
|
|
7
|
+
import { AsyncEventEmitter as AsyncEventEmitterClass, detectFormatter, detectLinter, executeIfOnline, formatters, linters, toError } from '@internals/utils'
|
|
8
|
+
import { type CLIOptions, type Config, createKubb, isInputPath, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'
|
|
9
|
+
import { version } from '../../../package.json'
|
|
10
|
+
import { KUBB_NPM_PACKAGE_URL } from '../../constants.ts'
|
|
11
|
+
import { setupLogger, type HookSinkFactory } from '../../loggers/utils.ts'
|
|
12
|
+
import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
|
|
13
|
+
import { executeHooks, getConfigs, runHook, startWatcher } from './utils.ts'
|
|
14
|
+
|
|
15
|
+
type GenerateProps = {
|
|
16
|
+
input?: string
|
|
17
|
+
config: Config
|
|
18
|
+
hooks: AsyncEventEmitter<KubbHooks>
|
|
19
|
+
logLevel: number
|
|
20
|
+
makeSink?: HookSinkFactory | null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type ToolMap = typeof formatters | typeof linters
|
|
24
|
+
|
|
25
|
+
type RunToolPassOptions = {
|
|
26
|
+
toolValue: string
|
|
27
|
+
detect: () => Promise<string | null>
|
|
28
|
+
toolMap: ToolMap
|
|
29
|
+
toolLabel: string
|
|
30
|
+
successPrefix: string
|
|
31
|
+
noToolMessage: string
|
|
32
|
+
configName: string | undefined
|
|
33
|
+
outputPath: string
|
|
34
|
+
logLevel: number
|
|
35
|
+
hooks: AsyncEventEmitter<KubbHooks>
|
|
36
|
+
makeSink?: HookSinkFactory | null
|
|
37
|
+
onStart: () => Promise<void>
|
|
38
|
+
onEnd: () => Promise<void>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
|
|
43
|
+
* avoiding the race where a synchronous emitter fires end before the listener is attached.
|
|
44
|
+
*/
|
|
45
|
+
function waitForHookEnd(
|
|
46
|
+
hooks: AsyncEventEmitter<KubbHooks>,
|
|
47
|
+
hookId: string,
|
|
48
|
+
onSuccess: () => Promise<void> | void,
|
|
49
|
+
fallbackErrorMessage: string,
|
|
50
|
+
): Promise<void> {
|
|
51
|
+
return new Promise<void>((resolve, reject) => {
|
|
52
|
+
const handler = (ctx: { id?: string; command: string; args?: ReadonlyArray<string>; success: boolean; error: Error | null }) => {
|
|
53
|
+
if (ctx.id !== hookId) return
|
|
54
|
+
hooks.off('kubb:hook:end', handler)
|
|
55
|
+
if (!ctx.success) {
|
|
56
|
+
reject(ctx.error ?? new Error(fallbackErrorMessage))
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
Promise.resolve(onSuccess()).then(resolve).catch(reject)
|
|
60
|
+
}
|
|
61
|
+
hooks.on('kubb:hook:end', handler)
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function runToolPass({
|
|
66
|
+
toolValue,
|
|
67
|
+
detect,
|
|
68
|
+
toolMap,
|
|
69
|
+
toolLabel,
|
|
70
|
+
successPrefix,
|
|
71
|
+
noToolMessage,
|
|
72
|
+
configName,
|
|
73
|
+
outputPath,
|
|
74
|
+
logLevel,
|
|
75
|
+
hooks,
|
|
76
|
+
makeSink,
|
|
77
|
+
onStart,
|
|
78
|
+
onEnd,
|
|
79
|
+
}: RunToolPassOptions) {
|
|
80
|
+
await onStart()
|
|
81
|
+
|
|
82
|
+
let resolvedTool = toolValue
|
|
83
|
+
if (resolvedTool === 'auto') {
|
|
84
|
+
const detected = await detect()
|
|
85
|
+
if (!detected) {
|
|
86
|
+
await hooks.emit('kubb:warn', { message: noToolMessage })
|
|
87
|
+
} else {
|
|
88
|
+
resolvedTool = detected
|
|
89
|
+
await hooks.emit('kubb:info', { message: `Auto-detected ${toolLabel}: ${styleText('dim', resolvedTool)}` })
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let toolError: Error | undefined
|
|
94
|
+
|
|
95
|
+
if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in toolMap) {
|
|
96
|
+
const toolConfig = toolMap[resolvedTool as keyof ToolMap]
|
|
97
|
+
const hookId = createHash('sha256').update([configName, resolvedTool].filter(Boolean).join('-')).digest('hex')
|
|
98
|
+
|
|
99
|
+
const successMessage = [
|
|
100
|
+
`${successPrefix} with ${styleText('dim', resolvedTool)}`,
|
|
101
|
+
logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,
|
|
102
|
+
'successfully',
|
|
103
|
+
]
|
|
104
|
+
.filter(Boolean)
|
|
105
|
+
.join(' ')
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const hookArgs = toolConfig.args(outputPath)
|
|
109
|
+
const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')
|
|
110
|
+
const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit('kubb:success', { message: successMessage }), toolConfig.errorMessage)
|
|
111
|
+
|
|
112
|
+
await hooks.emit('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })
|
|
113
|
+
|
|
114
|
+
const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs, hookId) ?? {}
|
|
115
|
+
|
|
116
|
+
runHook({
|
|
117
|
+
id: hookId,
|
|
118
|
+
command: toolConfig.command,
|
|
119
|
+
args: hookArgs,
|
|
120
|
+
commandWithArgs,
|
|
121
|
+
context: hooks,
|
|
122
|
+
stream,
|
|
123
|
+
sink: { onLine, onStdout, onStderr },
|
|
124
|
+
}).catch(() => {})
|
|
125
|
+
|
|
126
|
+
await hookEndPromise
|
|
127
|
+
} catch (caughtError) {
|
|
128
|
+
const err = toError(caughtError)
|
|
129
|
+
await hooks.emit('kubb:error', { error: err })
|
|
130
|
+
toolError = err
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
await onEnd()
|
|
135
|
+
|
|
136
|
+
if (toolError) {
|
|
137
|
+
throw toolError
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function generate(options: GenerateProps): Promise<boolean> {
|
|
142
|
+
const { input, hooks, logLevel, makeSink } = options
|
|
143
|
+
|
|
144
|
+
const hrStart = process.hrtime()
|
|
145
|
+
const inputPath = input ?? (options.config.input && 'path' in options.config.input ? options.config.input.path : undefined)
|
|
146
|
+
|
|
147
|
+
const config: Config = {
|
|
148
|
+
...options.config,
|
|
149
|
+
input: inputPath ? { ...options.config.input, path: inputPath } : options.config.input,
|
|
150
|
+
...options.config.output,
|
|
151
|
+
} satisfies Config
|
|
152
|
+
|
|
153
|
+
const kubb = createKubb(config, { hooks })
|
|
154
|
+
|
|
155
|
+
await hooks.emit('kubb:generation:start', { config })
|
|
156
|
+
await hooks.emit('kubb:info', { message: config.name ? `Setup generation ${styleText('bold', config.name)}` : 'Setup generation', info: inputPath })
|
|
157
|
+
|
|
158
|
+
await kubb.setup()
|
|
159
|
+
|
|
160
|
+
await hooks.emit('kubb:info', { message: config.name ? `Build generation ${styleText('bold', config.name)}` : 'Build generation', info: inputPath })
|
|
161
|
+
|
|
162
|
+
const { files, failedPlugins, pluginTimings, error, driver } = await kubb.safeBuild()
|
|
163
|
+
|
|
164
|
+
await hooks.emit('kubb:info', { message: 'Load summary' })
|
|
165
|
+
|
|
166
|
+
const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))
|
|
167
|
+
|
|
168
|
+
const reportTelemetry = (status: 'success' | 'failed') =>
|
|
169
|
+
sendTelemetry(buildTelemetryEvent({ command: 'generate', kubbVersion: version, plugins: telemetryPlugins, hrStart, filesCreated: files.length, status }))
|
|
170
|
+
|
|
171
|
+
if (failedPlugins.size > 0 || error) {
|
|
172
|
+
const allErrors = [error, ...Array.from(failedPlugins, (it) => it.error)].filter(Boolean) as Array<Error>
|
|
173
|
+
|
|
174
|
+
for (const err of allErrors) {
|
|
175
|
+
await hooks.emit('kubb:error', { error: err })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
await hooks.emit('kubb:generation:end', { config, storage: kubb.storage })
|
|
179
|
+
await hooks.emit('kubb:generation:summary', {
|
|
180
|
+
config,
|
|
181
|
+
failedPlugins,
|
|
182
|
+
filesCreated: files.length,
|
|
183
|
+
status: 'failed',
|
|
184
|
+
hrStart,
|
|
185
|
+
pluginTimings: logLevel >= logLevelMap.verbose ? pluginTimings : undefined,
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
await reportTelemetry('failed')
|
|
189
|
+
return false
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
await hooks.emit('kubb:success', { message: 'Generation succeeded', info: inputPath })
|
|
193
|
+
await hooks.emit('kubb:generation:end', { config, storage: kubb.storage })
|
|
194
|
+
|
|
195
|
+
const outputPath = path.resolve(config.root, config.output.path)
|
|
196
|
+
|
|
197
|
+
const toolPasses = [
|
|
198
|
+
config.output.format && {
|
|
199
|
+
toolValue: config.output.format,
|
|
200
|
+
detect: detectFormatter,
|
|
201
|
+
toolMap: formatters,
|
|
202
|
+
toolLabel: 'formatter',
|
|
203
|
+
successPrefix: 'Formatting',
|
|
204
|
+
noToolMessage: 'No formatter found (oxfmt, biome, or prettier). Skipping formatting.',
|
|
205
|
+
onStart: () => hooks.emit('kubb:format:start'),
|
|
206
|
+
onEnd: () => hooks.emit('kubb:format:end'),
|
|
207
|
+
},
|
|
208
|
+
config.output.lint && {
|
|
209
|
+
toolValue: config.output.lint,
|
|
210
|
+
detect: detectLinter,
|
|
211
|
+
toolMap: linters,
|
|
212
|
+
toolLabel: 'linter',
|
|
213
|
+
successPrefix: 'Linting',
|
|
214
|
+
noToolMessage: 'No linter found (oxlint, biome, or eslint). Skipping linting.',
|
|
215
|
+
onStart: () => hooks.emit('kubb:lint:start'),
|
|
216
|
+
onEnd: () => hooks.emit('kubb:lint:end'),
|
|
217
|
+
},
|
|
218
|
+
].filter(Boolean) as Array<Omit<RunToolPassOptions, 'configName' | 'outputPath' | 'logLevel' | 'hooks'>>
|
|
219
|
+
|
|
220
|
+
for (const pass of toolPasses) {
|
|
221
|
+
await runToolPass({ ...pass, configName: config.name, outputPath, logLevel, hooks, makeSink })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (config.hooks) {
|
|
225
|
+
await hooks.emit('kubb:hooks:start')
|
|
226
|
+
await executeHooks({ configHooks: config.hooks, hooks, makeSink })
|
|
227
|
+
await hooks.emit('kubb:hooks:end')
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
await hooks.emit('kubb:generation:summary', { config, failedPlugins, filesCreated: files.length, status: 'success', hrStart, pluginTimings })
|
|
231
|
+
|
|
232
|
+
await reportTelemetry('success')
|
|
233
|
+
return true
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
type GenerateCommandOptions = {
|
|
237
|
+
input?: string
|
|
238
|
+
configPath?: string
|
|
239
|
+
logLevel: string
|
|
240
|
+
watch: boolean
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function checkForUpdate(hooks: AsyncEventEmitter<KubbHooks>): Promise<void> {
|
|
244
|
+
await executeIfOnline(async () => {
|
|
245
|
+
try {
|
|
246
|
+
const res = await fetch(KUBB_NPM_PACKAGE_URL)
|
|
247
|
+
const data = (await res.json()) as { version: string }
|
|
248
|
+
if (data.version && version < data.version) {
|
|
249
|
+
await hooks.emit('kubb:version:new', { currentVersion: version, latestVersion: data.version })
|
|
250
|
+
}
|
|
251
|
+
} catch {
|
|
252
|
+
// Ignore network errors
|
|
253
|
+
}
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Runs the full Kubb generation lifecycle for the given CLI options.
|
|
259
|
+
* Sets up the logger, checks for a newer version, loads configs, and calls `generate` for each config entry.
|
|
260
|
+
*/
|
|
261
|
+
export async function run({ input, configPath, logLevel: logLevelKey, watch }: GenerateCommandOptions): Promise<void> {
|
|
262
|
+
const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info
|
|
263
|
+
const hooks = new AsyncEventEmitterClass<KubbHooks>()
|
|
264
|
+
|
|
265
|
+
const makeSink = await setupLogger(hooks, { logLevel })
|
|
266
|
+
|
|
267
|
+
await hooks.emit('kubb:lifecycle:start', { version })
|
|
268
|
+
|
|
269
|
+
await checkForUpdate(hooks)
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
await hooks.emit('kubb:config:start')
|
|
273
|
+
|
|
274
|
+
const { configs, configPath: resolvedConfigPath } = await getConfigs({
|
|
275
|
+
configPath,
|
|
276
|
+
input,
|
|
277
|
+
watch,
|
|
278
|
+
logLevel: logLevelKey as CLIOptions['logLevel'],
|
|
279
|
+
})
|
|
280
|
+
const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)
|
|
281
|
+
|
|
282
|
+
await hooks.emit('kubb:info', { message: 'Config loaded', info: relativeConfigPath })
|
|
283
|
+
await hooks.emit('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })
|
|
284
|
+
await hooks.emit('kubb:config:end', { configs })
|
|
285
|
+
|
|
286
|
+
let anyFailed = false
|
|
287
|
+
for (const config of configs) {
|
|
288
|
+
if (isInputPath(config) && watch) {
|
|
289
|
+
await startWatcher(
|
|
290
|
+
[input || config.input.path],
|
|
291
|
+
async (paths) => {
|
|
292
|
+
// Don't removeAll() — that would also drop logger and lifecycle listeners.
|
|
293
|
+
// Plugin and middleware listeners are already disposed by safeBuild's
|
|
294
|
+
// setupResult.dispose() in its finally block, so re-running generate()
|
|
295
|
+
// on the same hooks emitter is safe.
|
|
296
|
+
await generate({ input, config, logLevel, hooks, makeSink })
|
|
297
|
+
clack.log.step(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))
|
|
298
|
+
},
|
|
299
|
+
{ info: (msg) => clack.log.info(msg), error: (msg) => clack.log.error(msg) },
|
|
300
|
+
)
|
|
301
|
+
} else {
|
|
302
|
+
try {
|
|
303
|
+
const succeeded = await generate({ input, config, logLevel, hooks, makeSink })
|
|
304
|
+
if (!succeeded) anyFailed = true
|
|
305
|
+
} catch (configError) {
|
|
306
|
+
await hooks.emit('kubb:error', { error: toError(configError) })
|
|
307
|
+
anyFailed = true
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
await hooks.emit('kubb:lifecycle:end')
|
|
313
|
+
|
|
314
|
+
if (anyFailed) {
|
|
315
|
+
process.exit(1)
|
|
316
|
+
}
|
|
317
|
+
} catch (error) {
|
|
318
|
+
await hooks.emit('kubb:error', { error: toError(error) })
|
|
319
|
+
process.exit(1)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
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, context: 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
|
+
context: AsyncEventEmitter<KubbHooks>
|
|
148
|
+
stream?: boolean
|
|
149
|
+
sink?: HookSinkOptions
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }: RunHookOptions): Promise<void> {
|
|
153
|
+
const emitEnd = (success: boolean, error: Error | null) => context.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
|
+
const result = await proc
|
|
168
|
+
await context.emit('kubb:debug', { date: new Date(), logs: [result.stdout.trimEnd()] })
|
|
169
|
+
await context.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
|
|
170
|
+
await emitEnd(true, null)
|
|
171
|
+
} catch (err) {
|
|
172
|
+
if (!(err instanceof NonZeroExitError)) {
|
|
173
|
+
const error = toError(err)
|
|
174
|
+
await emitEnd(false, error)
|
|
175
|
+
await context.emit('kubb:error', { error })
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const stderr = err.output?.stderr ?? ''
|
|
180
|
+
const stdout = err.output?.stdout ?? ''
|
|
181
|
+
|
|
182
|
+
await context.emit('kubb:debug', { date: new Date(), logs: [stdout, stderr].filter(Boolean) })
|
|
183
|
+
|
|
184
|
+
if (stderr) sink?.onStderr?.(stderr)
|
|
185
|
+
if (stdout) sink?.onStdout?.(stdout)
|
|
186
|
+
|
|
187
|
+
const error = new Error(`Hook execute failed: ${commandWithArgs}`)
|
|
188
|
+
await emitEnd(false, error)
|
|
189
|
+
await context.emit('kubb:error', { error })
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
type WatcherLog = {
|
|
194
|
+
info: (message: string) => void
|
|
195
|
+
error: (message: string) => void
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Starts a file watcher on the given paths and calls `cb` on any change.
|
|
200
|
+
* Ignores `.git` and `node_modules` directories.
|
|
201
|
+
*/
|
|
202
|
+
export async function startWatcher(
|
|
203
|
+
path: Array<string>,
|
|
204
|
+
cb: (path: Array<string>) => Promise<void>,
|
|
205
|
+
log: WatcherLog = { info: console.log, error: console.log },
|
|
206
|
+
): Promise<void> {
|
|
207
|
+
const { watch } = await import('chokidar')
|
|
208
|
+
const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
|
|
209
|
+
|
|
210
|
+
process.once('SIGINT', () => {
|
|
211
|
+
watcher.close()
|
|
212
|
+
})
|
|
213
|
+
process.once('SIGTERM', () => {
|
|
214
|
+
watcher.close()
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
watcher.on('all', async (type, file) => {
|
|
218
|
+
log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
|
|
219
|
+
try {
|
|
220
|
+
await cb(path)
|
|
221
|
+
} catch (_e) {
|
|
222
|
+
log.error(styleText('red', 'Watcher failed'))
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
}
|