@kubb/cli 5.0.0-beta.2 → 5.0.0-beta.21

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 (151) hide show
  1. package/README.md +177 -26
  2. package/dist/agent-B1y251-b.cjs +70 -0
  3. package/dist/agent-B1y251-b.cjs.map +1 -0
  4. package/dist/agent-jGZu4zRF.js +68 -0
  5. package/dist/agent-jGZu4zRF.js.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-BvFE5Tac.js} +1 -0
  7. package/dist/constants-B2JTeRBb.js +42 -0
  8. package/dist/constants-B2JTeRBb.js.map +1 -0
  9. package/dist/constants-BINTA5VZ.cjs +77 -0
  10. package/dist/constants-BINTA5VZ.cjs.map +1 -0
  11. package/dist/constants-BYGmiFs0.cjs +139 -0
  12. package/dist/constants-BYGmiFs0.cjs.map +1 -0
  13. package/dist/constants-DSJ-Xrbv.js +116 -0
  14. package/dist/constants-DSJ-Xrbv.js.map +1 -0
  15. package/dist/define-Bdn8j5VM.cjs.map +1 -1
  16. package/dist/{define-Ctii4bel.js → define-m_fp-Aqm.js} +2 -2
  17. package/dist/{define-Ctii4bel.js.map → define-m_fp-Aqm.js.map} +1 -1
  18. package/dist/{errors-CjPmyZHy.js → errors-CINO1EIv.js} +2 -2
  19. package/dist/{errors-CjPmyZHy.js.map → errors-CINO1EIv.js.map} +1 -1
  20. package/dist/errors-CLCjoSg0.cjs.map +1 -1
  21. package/dist/{generate-DL_7a7Wd.cjs → generate-CszBbEx_.cjs} +10 -4
  22. package/dist/generate-CszBbEx_.cjs.map +1 -0
  23. package/dist/{generate-B3PZ6Dp-.js → generate-Dqk3rinP.js} +12 -6
  24. package/dist/generate-Dqk3rinP.js.map +1 -0
  25. package/dist/index.cjs +20 -11
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +22 -13
  29. package/dist/index.js.map +1 -1
  30. package/dist/init-BSfLyes_.js +53 -0
  31. package/dist/init-BSfLyes_.js.map +1 -0
  32. package/dist/init-JrYOUBes.cjs +53 -0
  33. package/dist/init-JrYOUBes.cjs.map +1 -0
  34. package/dist/mcp-BiLUSMgD.js +39 -0
  35. package/dist/mcp-BiLUSMgD.js.map +1 -0
  36. package/dist/mcp-DY_TKMoS.cjs +39 -0
  37. package/dist/mcp-DY_TKMoS.cjs.map +1 -0
  38. package/dist/package-C_LGzz8A.js +6 -0
  39. package/dist/package-C_LGzz8A.js.map +1 -0
  40. package/dist/{package-D8wlStAg.cjs → package-CyNXMTr8.cjs} +2 -2
  41. package/dist/package-CyNXMTr8.cjs.map +1 -0
  42. package/dist/run-B11-UaUs.cjs +33 -0
  43. package/dist/run-B11-UaUs.cjs.map +1 -0
  44. package/dist/{init-eNRlotJK.js → run-BNqMQygv.js} +107 -149
  45. package/dist/run-BNqMQygv.js.map +1 -0
  46. package/dist/{init-CZ5Xq2Hd.cjs → run-BnGfi7Cp.cjs} +105 -147
  47. package/dist/run-BnGfi7Cp.cjs.map +1 -0
  48. package/dist/{generate-Dt_r0ELY.js → run-BryUpjjc.js} +484 -410
  49. package/dist/run-BryUpjjc.js.map +1 -0
  50. package/dist/{agent-Ev5hU5hH.js → run-BzpYYOQs.js} +53 -44
  51. package/dist/run-BzpYYOQs.js.map +1 -0
  52. package/dist/run-CCZ24VKk.js +51 -0
  53. package/dist/run-CCZ24VKk.js.map +1 -0
  54. package/dist/run-CQbj3ley.cjs +52 -0
  55. package/dist/run-CQbj3ley.cjs.map +1 -0
  56. package/dist/{generate-B3jl4ukb.cjs → run-CmiuJkLG.cjs} +481 -407
  57. package/dist/run-CmiuJkLG.cjs.map +1 -0
  58. package/dist/{agent-B_pirbeB.cjs → run-DwdAwnLG.cjs} +51 -42
  59. package/dist/run-DwdAwnLG.cjs.map +1 -0
  60. package/dist/run-PSA9X7ci.js +32 -0
  61. package/dist/run-PSA9X7ci.js.map +1 -0
  62. package/dist/shell-475fQKaX.cjs.map +1 -1
  63. package/dist/{shell-DLzN4fRo.js → shell-CN6DNqeC.js} +2 -2
  64. package/dist/{shell-DLzN4fRo.js.map → shell-CN6DNqeC.js.map} +1 -1
  65. package/dist/{telemetry-DN95_2pF.cjs → telemetry-B2iWkY5e.cjs} +5 -7
  66. package/dist/telemetry-B2iWkY5e.cjs.map +1 -0
  67. package/dist/{telemetry-LgT_sdPe.js → telemetry-BkektVz6.js} +6 -8
  68. package/dist/telemetry-BkektVz6.js.map +1 -0
  69. package/dist/validate-8VIogDlj.cjs +26 -0
  70. package/dist/validate-8VIogDlj.cjs.map +1 -0
  71. package/dist/validate-KufVWuQ1.js +26 -0
  72. package/dist/validate-KufVWuQ1.js.map +1 -0
  73. package/package.json +23 -15
  74. package/src/commands/agent/start.ts +10 -7
  75. package/src/commands/agent.ts +3 -1
  76. package/src/commands/generate.ts +5 -3
  77. package/src/commands/init.ts +34 -3
  78. package/src/commands/mcp.ts +28 -4
  79. package/src/commands/validate.ts +6 -4
  80. package/src/constants.ts +2 -58
  81. package/src/index.ts +5 -3
  82. package/src/loggers/clackLogger.ts +72 -81
  83. package/src/loggers/fileSystemLogger.ts +26 -13
  84. package/src/loggers/githubActionsLogger.ts +74 -28
  85. package/src/loggers/plainLogger.ts +55 -30
  86. package/src/loggers/types.ts +6 -0
  87. package/src/loggers/utils.ts +158 -9
  88. package/src/runners/agent/run.ts +113 -0
  89. package/src/runners/agent/utils.ts +98 -0
  90. package/src/runners/generate/run.ts +316 -0
  91. package/src/runners/generate/utils.ts +216 -0
  92. package/src/runners/init/run.ts +212 -0
  93. package/src/{utils/packageManager.ts → runners/init/utils.ts} +10 -0
  94. package/src/runners/mcp/run.ts +37 -0
  95. package/src/runners/validate/run.ts +63 -0
  96. package/src/{utils/telemetry.ts → telemetry.ts} +12 -5
  97. package/dist/agent-0Nk--lcr.cjs +0 -58
  98. package/dist/agent-0Nk--lcr.cjs.map +0 -1
  99. package/dist/agent-B_pirbeB.cjs.map +0 -1
  100. package/dist/agent-DKeVuiUC.js +0 -56
  101. package/dist/agent-DKeVuiUC.js.map +0 -1
  102. package/dist/agent-Ev5hU5hH.js.map +0 -1
  103. package/dist/constants-CnDXa1R6.cjs +0 -148
  104. package/dist/constants-CnDXa1R6.cjs.map +0 -1
  105. package/dist/constants-aL3CP_Wq.js +0 -95
  106. package/dist/constants-aL3CP_Wq.js.map +0 -1
  107. package/dist/generate-B3PZ6Dp-.js.map +0 -1
  108. package/dist/generate-B3jl4ukb.cjs.map +0 -1
  109. package/dist/generate-DL_7a7Wd.cjs.map +0 -1
  110. package/dist/generate-Dt_r0ELY.js.map +0 -1
  111. package/dist/init-Bj94Nvt8.js +0 -25
  112. package/dist/init-Bj94Nvt8.js.map +0 -1
  113. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  114. package/dist/init-CyN1oyTF.cjs +0 -25
  115. package/dist/init-CyN1oyTF.cjs.map +0 -1
  116. package/dist/init-eNRlotJK.js.map +0 -1
  117. package/dist/mcp-BzW703d7.js +0 -16
  118. package/dist/mcp-BzW703d7.js.map +0 -1
  119. package/dist/mcp-CLcDV4Jm.cjs +0 -41
  120. package/dist/mcp-CLcDV4Jm.cjs.map +0 -1
  121. package/dist/mcp-D7EIR9fR.js +0 -40
  122. package/dist/mcp-D7EIR9fR.js.map +0 -1
  123. package/dist/mcp-ZY-ONTOp.cjs +0 -16
  124. package/dist/mcp-ZY-ONTOp.cjs.map +0 -1
  125. package/dist/package-D8wlStAg.cjs.map +0 -1
  126. package/dist/package-Yo-9_m5C.js +0 -6
  127. package/dist/package-Yo-9_m5C.js.map +0 -1
  128. package/dist/telemetry-DN95_2pF.cjs.map +0 -1
  129. package/dist/telemetry-LgT_sdPe.js.map +0 -1
  130. package/dist/validate-Dplr99xO.js +0 -25
  131. package/dist/validate-Dplr99xO.js.map +0 -1
  132. package/dist/validate-_8mBa63G.cjs +0 -25
  133. package/dist/validate-_8mBa63G.cjs.map +0 -1
  134. package/dist/validate-kLJoT_hi.js +0 -33
  135. package/dist/validate-kLJoT_hi.js.map +0 -1
  136. package/dist/validate-yKKzqEZ5.cjs +0 -34
  137. package/dist/validate-yKKzqEZ5.cjs.map +0 -1
  138. package/src/runners/agent.ts +0 -149
  139. package/src/runners/generate.ts +0 -333
  140. package/src/runners/init.ts +0 -296
  141. package/src/runners/mcp.ts +0 -45
  142. package/src/runners/validate.ts +0 -39
  143. package/src/types.ts +0 -11
  144. package/src/utils/Writables.ts +0 -17
  145. package/src/utils/executeHooks.ts +0 -45
  146. package/src/utils/flags.ts +0 -9
  147. package/src/utils/getConfig.ts +0 -10
  148. package/src/utils/getCosmiConfig.ts +0 -80
  149. package/src/utils/getSummary.ts +0 -68
  150. package/src/utils/runHook.ts +0 -91
  151. package/src/utils/watcher.ts +0 -19
@@ -1,9 +1,9 @@
1
1
  import { relative } from 'node:path'
2
- import { formatMs, toCause } from '@internals/utils'
2
+ import process from 'node:process'
3
+ import { formatMs, getElapsedMs, toCause } from '@internals/utils'
3
4
  import { defineLogger, logLevel as logLevelMap } from '@kubb/core'
4
5
  import { SUMMARY_SEPARATOR } from '../constants.ts'
5
- import { getSummary } from '../utils/getSummary.ts'
6
- import { runHook } from '../utils/runHook.ts'
6
+ import { getSummary } from './utils.ts'
7
7
  import { formatCommandWithArgs, formatMessage } from './utils.ts'
8
8
 
9
9
  /**
@@ -13,6 +13,7 @@ export const plainLogger = defineLogger({
13
13
  name: 'plain',
14
14
  install(context, options) {
15
15
  const logLevel = options?.logLevel ?? logLevelMap.info
16
+ const hookStarts = new Map<string, [number, number]>()
16
17
 
17
18
  function getMessage(message: string): string {
18
19
  return formatMessage(message, logLevel)
@@ -73,8 +74,16 @@ export const plainLogger = defineLogger({
73
74
  }
74
75
  })
75
76
 
76
- context.on('kubb:lifecycle:start', () => {
77
- console.log('Kubb CLI 🧩')
77
+ context.on('kubb:lifecycle:start', ({ version }) => {
78
+ console.log(`Kubb CLI v${version}`)
79
+ })
80
+
81
+ context.on('kubb:version:new', ({ currentVersion, latestVersion }) => {
82
+ if (logLevel <= logLevelMap.silent) {
83
+ return
84
+ }
85
+
86
+ console.log(getMessage(`Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`))
78
87
  })
79
88
 
80
89
  context.on('kubb:config:start', () => {
@@ -133,14 +142,14 @@ export const plainLogger = defineLogger({
133
142
  console.log(text)
134
143
  })
135
144
 
136
- context.on('kubb:file:processing:update', ({ file, config }) => {
145
+ context.on('kubb:files:processing:update', ({ files }) => {
137
146
  if (logLevel <= logLevelMap.silent) {
138
147
  return
139
148
  }
140
149
 
141
- const text = getMessage(`Writing ${relative(config.root, file.path)}`)
142
-
143
- console.log(text)
150
+ for (const { file, config } of files) {
151
+ console.log(getMessage(`Writing ${relative(config.root, file.path)}`))
152
+ }
144
153
  })
145
154
 
146
155
  context.on('kubb:files:processing:end', () => {
@@ -199,41 +208,52 @@ export const plainLogger = defineLogger({
199
208
  console.log(text)
200
209
  })
201
210
 
202
- context.on('kubb:hook:start', async ({ id, command, args }) => {
203
- const commandWithArgs = formatCommandWithArgs(command, args)
204
- const text = getMessage(`Hook ${commandWithArgs} started`)
211
+ context.on('kubb:hooks:start', () => {
212
+ if (logLevel <= logLevelMap.silent) {
213
+ return
214
+ }
215
+
216
+ console.log(getMessage('Hooks started'))
217
+ })
205
218
 
206
- if (logLevel > logLevelMap.silent) {
207
- console.log(text)
219
+ context.on('kubb:hooks:end', () => {
220
+ if (logLevel <= logLevelMap.silent) {
221
+ return
208
222
  }
209
223
 
210
- // Skip hook execution if no id is provided (e.g., during benchmarks or tests)
211
- if (!id) {
224
+ console.log(getMessage('Hooks completed'))
225
+ })
226
+
227
+ context.on('kubb:hook:start', ({ id, command, args }) => {
228
+ if (logLevel <= logLevelMap.silent) {
212
229
  return
213
230
  }
214
231
 
215
- await runHook({
216
- id,
217
- command,
218
- args,
219
- commandWithArgs,
220
- context,
221
- sink: {
222
- onStdout: logLevel > logLevelMap.silent ? (s) => console.log(s) : undefined,
223
- onStderr: logLevel > logLevelMap.silent ? (s) => console.error(s) : undefined,
224
- },
225
- })
232
+ if (id) {
233
+ hookStarts.set(id, process.hrtime())
234
+ }
235
+
236
+ const commandWithArgs = formatCommandWithArgs(command, args)
237
+ console.log(getMessage(`Hook ${commandWithArgs} started`))
226
238
  })
227
239
 
228
- context.on('kubb:hook:end', ({ command, args }) => {
240
+ context.on('kubb:hook:end', ({ id, command, args, success, error }) => {
229
241
  if (logLevel <= logLevelMap.silent) {
230
242
  return
231
243
  }
232
244
 
245
+ const hrStart = id ? hookStarts.get(id) : undefined
246
+ if (id) hookStarts.delete(id)
247
+ const durationStr = hrStart ? ` in ${formatMs(getElapsedMs(hrStart))}` : ''
248
+
233
249
  const commandWithArgs = formatCommandWithArgs(command, args)
234
- const text = getMessage(`Hook ${commandWithArgs} completed`)
235
250
 
236
- console.log(text)
251
+ if (success) {
252
+ console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`))
253
+ } else {
254
+ const reason = error?.message ? ` (${error.message})` : ''
255
+ console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`))
256
+ }
237
257
  })
238
258
 
239
259
  context.on('kubb:generation:summary', ({ config, pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {
@@ -250,5 +270,10 @@ export const plainLogger = defineLogger({
250
270
  console.log(summary.join('\n'))
251
271
  console.log(SUMMARY_SEPARATOR)
252
272
  })
273
+
274
+ return (_commandWithArgs: string, _hookId: string) => ({
275
+ onStdout: logLevel > logLevelMap.silent ? (s: string) => console.log(s) : undefined,
276
+ onStderr: logLevel > logLevelMap.silent ? (s: string) => console.error(s) : undefined,
277
+ })
253
278
  },
254
279
  })
@@ -1 +1,7 @@
1
+ /**
2
+ * Logger adapter selected by `setupLogger` based on the runtime environment.
3
+ * - `'clack'`: TTY-aware output with spinners and progress bars.
4
+ * - `'github-actions'`: CI output using `::group::` annotations.
5
+ * - `'plain'`: Plain `console.log` output for non-TTY environments.
6
+ */
1
7
  export type LoggerType = 'clack' | 'github-actions' | 'plain'
@@ -1,13 +1,60 @@
1
+ import path from 'node:path'
1
2
  import { styleText } from 'node:util'
2
- import { canUseTTY, formatHrtime, isGitHubActions } from '@internals/utils'
3
- import type { Logger, LoggerContext, LoggerOptions } from '@kubb/core'
3
+ import { canUseTTY, formatHrtime, isGitHubActions, randomCliColor } from '@internals/utils'
4
+ import type { Config, Logger, LoggerContext, LoggerOptions, Plugin } from '@kubb/core'
4
5
  import { logLevel as logLevelMap } from '@kubb/core'
6
+ import { SUMMARY_MAX_BAR_LENGTH, SUMMARY_TIME_SCALE_DIVISOR } from '../constants.ts'
5
7
  import { clackLogger } from './clackLogger.ts'
6
8
  import { fileSystemLogger } from './fileSystemLogger.ts'
7
9
  import { githubActionsLogger } from './githubActionsLogger.ts'
8
10
  import { plainLogger } from './plainLogger.ts'
9
11
  import type { LoggerType } from './types.ts'
10
12
 
13
+ /**
14
+ * Output sink for a hook subprocess, controlling how streamed lines and exit output are forwarded.
15
+ */
16
+ type HookOutputSink = {
17
+ /**
18
+ * Called for each streamed stdout line while the hook runs.
19
+ */
20
+ onLine?: (line: string) => void
21
+ /**
22
+ * Called with stderr content after the hook exits with a non-zero code.
23
+ */
24
+ onStderr?: (text: string) => void
25
+ /**
26
+ * Called with stdout content after the hook exits with a non-zero code.
27
+ */
28
+ onStdout?: (text: string) => void
29
+ }
30
+
31
+ /**
32
+ * Output sink combined with stream control for a hook subprocess.
33
+ */
34
+ export type HookSinkOptions = HookOutputSink & {
35
+ /**
36
+ * When `true`, streams process output line-by-line via `onLine`.
37
+ *
38
+ * @default false
39
+ */
40
+ stream?: boolean
41
+ }
42
+
43
+ /**
44
+ * Factory called once per hook command to build the output sink and streaming flag.
45
+ * The function should set up any logger UI (e.g., spinner) and return callbacks that forward subprocess output to it.
46
+ *
47
+ * `hookId` is the same id passed to `kubb:hook:start` / `kubb:hook:end`, letting the logger
48
+ * correlate streamed output with the active UI element (e.g., a clack `taskLog`) it created in the start handler.
49
+ */
50
+ export type HookSinkFactory = (commandWithArgs: string, hookId: string) => HookSinkOptions | null
51
+
52
+ /**
53
+ * Logger variant that may return a {@link HookSinkFactory} from `install`.
54
+ * The factory is forwarded to hook execution so the logger controls subprocess output routing.
55
+ */
56
+ type CLILogger = Logger<LoggerOptions, HookSinkFactory | void>
57
+
11
58
  /**
12
59
  * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
13
60
  * Shared across all logger adapters to avoid duplication.
@@ -26,11 +73,29 @@ export function formatMessage(message: string, logLevel: number): string {
26
73
  }
27
74
 
28
75
  type ProgressState = {
76
+ /**
77
+ * Total number of plugins scheduled for this generation run.
78
+ */
29
79
  totalPlugins: number
80
+ /**
81
+ * Number of plugins that have finished without error.
82
+ */
30
83
  completedPlugins: number
84
+ /**
85
+ * Number of plugins that exited with an error.
86
+ */
31
87
  failedPlugins: number
88
+ /**
89
+ * Total number of files expected to be written.
90
+ */
32
91
  totalFiles: number
92
+ /**
93
+ * Number of files written so far.
94
+ */
33
95
  processedFiles: number
96
+ /**
97
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
98
+ */
34
99
  hrStart: [number, number]
35
100
  }
36
101
 
@@ -80,27 +145,111 @@ function detectLogger(): LoggerType {
80
145
  return 'plain'
81
146
  }
82
147
 
83
- const logMapper = {
148
+ const logMapper: Record<LoggerType, CLILogger> = {
84
149
  clack: clackLogger,
85
150
  plain: plainLogger,
86
151
  'github-actions': githubActionsLogger,
87
- } as const satisfies Record<LoggerType, Logger>
152
+ }
88
153
 
89
- export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<void> {
154
+ export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<HookSinkFactory | null> {
90
155
  const type = detectLogger()
91
156
 
92
- const logger = logMapper[type] as Logger
157
+ const logger = logMapper[type]
93
158
 
94
159
  if (!logger) {
95
160
  throw new Error(`Unknown adapter type: ${type}`)
96
161
  }
97
162
 
98
- // Install primary logger
99
- const cleanup = await logger.install(context, { logLevel })
163
+ const makeSink = await logger.install(context, { logLevel })
100
164
 
101
165
  if (logLevel >= logLevelMap.debug) {
102
166
  await fileSystemLogger.install(context, { logLevel })
103
167
  }
104
168
 
105
- return cleanup
169
+ return typeof makeSink === 'function' ? makeSink : null
170
+ }
171
+
172
+ type SummaryProps = {
173
+ /**
174
+ * Set of plugins that failed during this generation run, each with its error.
175
+ */
176
+ failedPlugins: Set<{ plugin: Plugin; error: Error }>
177
+ /**
178
+ * Overall generation status used to choose success or failure formatting.
179
+ */
180
+ status: 'success' | 'failed'
181
+ /**
182
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
183
+ */
184
+ hrStart: [number, number]
185
+ /**
186
+ * Total number of files written during this generation run.
187
+ */
188
+ filesCreated: number
189
+ /**
190
+ * Resolved Kubb config for this generation entry, used to read plugin count and output path.
191
+ */
192
+ config: Config
193
+ /**
194
+ * Per-plugin timing map (plugin name → duration in ms). When provided, a timing bar chart is appended.
195
+ */
196
+ pluginTimings?: Map<string, number>
197
+ }
198
+
199
+ /**
200
+ * Builds the generation summary lines rendered in the end-of-run box.
201
+ * Returns an array of styled strings, one per summary row.
202
+ */
203
+ export function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }: SummaryProps): string[] {
204
+ const duration = formatHrtime(hrStart)
205
+
206
+ const pluginsCount = config.plugins?.length ?? 0
207
+ const successCount = pluginsCount - failedPlugins.size
208
+
209
+ const meta = {
210
+ plugins:
211
+ status === 'success'
212
+ ? `${styleText('green', `${successCount} successful`)}, ${pluginsCount} total`
213
+ : `${styleText('green', `${successCount} successful`)}, ${styleText('red', `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
214
+ pluginsFailed: status === 'failed' ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(', ') : undefined,
215
+ filesCreated,
216
+ time: styleText('green', duration),
217
+ output: path.resolve(config.root, config.output.path),
218
+ } as const
219
+
220
+ const labels = {
221
+ plugins: 'Plugins:',
222
+ failed: 'Failed:',
223
+ generated: 'Generated:',
224
+ pluginTimings: 'Plugin Timings:',
225
+ output: 'Output:',
226
+ }
227
+ const maxLength = Math.max(0, ...[...Object.values(labels), ...(pluginTimings ? Array.from(pluginTimings.keys()) : [])].map((s) => s.length))
228
+
229
+ const summaryLines: string[] = []
230
+ summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`)
231
+
232
+ if (meta.pluginsFailed) {
233
+ summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`)
234
+ }
235
+
236
+ summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`)
237
+
238
+ if (pluginTimings && pluginTimings.size > 0) {
239
+ const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1])
240
+
241
+ summaryLines.push(`${labels.pluginTimings}`)
242
+
243
+ sortedTimings.forEach(([name, time]) => {
244
+ const timeStr = time >= 1000 ? `${(time / 1000).toFixed(2)}s` : `${Math.round(time)}ms`
245
+ const barLength = Math.min(Math.ceil(time / SUMMARY_TIME_SCALE_DIVISOR), SUMMARY_MAX_BAR_LENGTH)
246
+ const bar = styleText('dim', '█'.repeat(barLength))
247
+
248
+ summaryLines.push(`${styleText('dim', '•')} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`)
249
+ })
250
+ }
251
+
252
+ summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`)
253
+
254
+ return summaryLines
106
255
  }
@@ -0,0 +1,113 @@
1
+ import { createRequire } from 'node:module'
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 { spawnAsync, getErrorMessage } from '@internals/utils'
7
+ import { agentDefaults } from '../../constants.ts'
8
+ import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
9
+ import { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'
10
+
11
+ type AgentStartOptions = {
12
+ /**
13
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
14
+ */
15
+ port: string | undefined
16
+ /**
17
+ * Hostname the HTTP server binds to.
18
+ *
19
+ * @default 'localhost'
20
+ */
21
+ host: string
22
+ /**
23
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
24
+ */
25
+ configPath: string | undefined
26
+ /**
27
+ * Grants the agent permission to write generated files to the filesystem.
28
+ */
29
+ allowWrite: boolean
30
+ /**
31
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
32
+ */
33
+ allowAll: boolean
34
+ /**
35
+ * Current `@kubb/cli` version string, used for the telemetry payload.
36
+ */
37
+ version: string
38
+ }
39
+
40
+ /**
41
+ * Spawns the Kubb Agent HTTP server as a Node.js subprocess.
42
+ * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.
43
+ */
44
+ export async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {
45
+ const hrStart = process.hrtime()
46
+ const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'agent', kubbVersion: version, hrStart, status }))
47
+
48
+ try {
49
+ // Load .env file into process.env using Node.js built-in (v20.12.0+)
50
+ try {
51
+ process.loadEnvFile()
52
+ } catch {
53
+ // .env file may not exist; ignore
54
+ }
55
+
56
+ // Resolve the @kubb/agent package path — createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)
57
+ const require = createRequire(import.meta.url)
58
+ let agentPkgPath: string
59
+ try {
60
+ agentPkgPath = require.resolve('@kubb/agent/package.json')
61
+ } catch (_e) {
62
+ console.error(styleText('red', 'The @kubb/agent package is not installed.'))
63
+ console.error('')
64
+ console.error('Install it with:')
65
+ console.error(styleText('cyan', ' npm install @kubb/agent'))
66
+ console.error(styleText('cyan', ' # or'))
67
+ console.error(styleText('cyan', ' pnpm install @kubb/agent'))
68
+ console.error('')
69
+ process.exit(1)
70
+ }
71
+ const agentDir = path.dirname(agentPkgPath)
72
+ const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)
73
+
74
+ const resolvedEnv = resolveAgentStartEnvironment({
75
+ port,
76
+ host,
77
+ configPath,
78
+ allowWrite,
79
+ allowAll,
80
+ })
81
+ const numericPort = Number(resolvedEnv.port)
82
+
83
+ if (!Number.isInteger(numericPort) || numericPort <= 0) {
84
+ throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`)
85
+ }
86
+
87
+ clack.log.step(styleText('cyan', 'Starting agent server...'))
88
+ clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))
89
+ clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))
90
+ clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))
91
+ if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {
92
+ clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))
93
+ }
94
+
95
+ if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {
96
+ clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))
97
+ process.exit(1)
98
+ }
99
+
100
+ // Spawns the server as a detached background process so the CLI can exit independently.
101
+ await spawnAsync('node', [serverPath], {
102
+ env: resolvedEnv.env,
103
+ cwd: process.cwd(),
104
+ })
105
+
106
+ await report('success')
107
+ } catch (error) {
108
+ await report('failed')
109
+ clack.log.error(styleText('red', 'Failed to start agent server'))
110
+ clack.log.error(getErrorMessage(error))
111
+ process.exit(1)
112
+ }
113
+ }
@@ -0,0 +1,98 @@
1
+ import net from 'node:net'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { agentDefaults } from '../../constants.ts'
5
+
6
+ type AgentStartEnvironmentInput = {
7
+ /**
8
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
9
+ */
10
+ port: string | undefined
11
+ /**
12
+ * Hostname the HTTP server binds to.
13
+ */
14
+ host: string
15
+ /**
16
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
17
+ */
18
+ configPath: string | undefined
19
+ /**
20
+ * Grants the agent permission to write generated files to the filesystem.
21
+ */
22
+ allowWrite: boolean
23
+ /**
24
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
25
+ */
26
+ allowAll: boolean
27
+ }
28
+
29
+ type ResolvedAgentStartEnvironment = {
30
+ /**
31
+ * Final port string after merging CLI flag, `PORT` env var, and the default.
32
+ */
33
+ port: string
34
+ /**
35
+ * Final hostname after merging CLI flag, `HOST` env var, and the default.
36
+ */
37
+ host: string
38
+ /**
39
+ * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.
40
+ */
41
+ allowWrite: boolean
42
+ /**
43
+ * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.
44
+ */
45
+ allowAll: boolean
46
+ /**
47
+ * Absolute path to the Kubb config file passed to the agent subprocess.
48
+ */
49
+ agentConfigPath: string
50
+ /**
51
+ * Merged `process.env` object with all resolved agent environment variables applied.
52
+ */
53
+ env: NodeJS.ProcessEnv
54
+ }
55
+
56
+ /**
57
+ * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
58
+ */
59
+ export function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {
60
+ const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port
61
+ const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)
62
+ const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'
63
+ const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'
64
+ const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()
65
+ const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)
66
+
67
+ return {
68
+ port: resolvedPort,
69
+ host: resolvedHost,
70
+ allowWrite: resolvedAllowWrite,
71
+ allowAll: resolvedAllowAll,
72
+ agentConfigPath,
73
+ env: {
74
+ ...process.env,
75
+ PORT: resolvedPort,
76
+ HOST: resolvedHost,
77
+ KUBB_AGENT_ROOT: agentRoot,
78
+ KUBB_AGENT_CONFIG: agentConfigPath,
79
+ KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
80
+ KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
81
+ KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,
82
+ KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,
83
+ KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,
84
+ },
85
+ }
86
+ }
87
+
88
+ export function isPortAvailable(port: number, host: string): Promise<boolean> {
89
+ return new Promise((resolve) => {
90
+ const server = net.createServer()
91
+ server.once('error', () => resolve(false))
92
+ server.once('listening', () => {
93
+ server.close()
94
+ resolve(true)
95
+ })
96
+ server.listen(port, host)
97
+ })
98
+ }