@kubb/cli 5.0.0-beta.75 → 5.0.0-beta.9

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-C5F4itrc.js +68 -0
  3. package/dist/agent-C5F4itrc.js.map +1 -0
  4. package/dist/agent-d-lmeOr1.cjs +70 -0
  5. package/dist/agent-d-lmeOr1.cjs.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-YPtfjsg4.js → generate-BhfRufgh.js} +12 -6
  22. package/dist/generate-BhfRufgh.js.map +1 -0
  23. package/dist/{generate-DDCwNQNo.cjs → generate-BvuSxNYj.cjs} +10 -4
  24. package/dist/generate-BvuSxNYj.cjs.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-DOSXtcyb.js +53 -0
  31. package/dist/init-DOSXtcyb.js.map +1 -0
  32. package/dist/init-bKtEOvhK.cjs +53 -0
  33. package/dist/init-bKtEOvhK.cjs.map +1 -0
  34. package/dist/mcp-CKkbG0kp.cjs +39 -0
  35. package/dist/mcp-CKkbG0kp.cjs.map +1 -0
  36. package/dist/mcp-DzOfqX_j.js +39 -0
  37. package/dist/mcp-DzOfqX_j.js.map +1 -0
  38. package/dist/package-BgAYWN7y.js +6 -0
  39. package/dist/package-BgAYWN7y.js.map +1 -0
  40. package/dist/{package-D5arPDnh.cjs → package-DHGhrRW-.cjs} +2 -2
  41. package/dist/package-DHGhrRW-.cjs.map +1 -0
  42. package/dist/{generate-K8MJ9aQF.cjs → run-BObDb2qe.cjs} +319 -334
  43. package/dist/run-BObDb2qe.cjs.map +1 -0
  44. package/dist/{agent-Ev5hU5hH.js → run-BzpYYOQs.js} +53 -44
  45. package/dist/run-BzpYYOQs.js.map +1 -0
  46. package/dist/run-CCZ24VKk.js +51 -0
  47. package/dist/run-CCZ24VKk.js.map +1 -0
  48. package/dist/{init-eNRlotJK.js → run-CF97BWVa.js} +102 -147
  49. package/dist/run-CF97BWVa.js.map +1 -0
  50. package/dist/run-CQbj3ley.cjs +52 -0
  51. package/dist/run-CQbj3ley.cjs.map +1 -0
  52. package/dist/run-D0hmRpHy.js +49 -0
  53. package/dist/run-D0hmRpHy.js.map +1 -0
  54. package/dist/{agent-B_pirbeB.cjs → run-DwdAwnLG.cjs} +51 -42
  55. package/dist/run-DwdAwnLG.cjs.map +1 -0
  56. package/dist/run-Lr0Ctnu0.cjs +50 -0
  57. package/dist/run-Lr0Ctnu0.cjs.map +1 -0
  58. package/dist/{generate-Cg8yufrw.js → run-P6D8TnXf.js} +322 -337
  59. package/dist/run-P6D8TnXf.js.map +1 -0
  60. package/dist/{init-CZ5Xq2Hd.cjs → run-YsoCk5we.cjs} +100 -145
  61. package/dist/run-YsoCk5we.cjs.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-Bj8vbvPt.cjs +26 -0
  70. package/dist/validate-Bj8vbvPt.cjs.map +1 -0
  71. package/dist/validate-bHUrnYBv.js +26 -0
  72. package/dist/validate-bHUrnYBv.js.map +1 -0
  73. package/package.json +22 -14
  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 +45 -43
  83. package/src/loggers/fileSystemLogger.ts +26 -13
  84. package/src/loggers/githubActionsLogger.ts +13 -25
  85. package/src/loggers/plainLogger.ts +12 -23
  86. package/src/loggers/types.ts +6 -0
  87. package/src/loggers/utils.ts +155 -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 +276 -0
  91. package/src/runners/generate/utils.ts +209 -0
  92. package/src/runners/init/run.ts +211 -0
  93. package/src/{utils/packageManager.ts → runners/init/utils.ts} +10 -0
  94. package/src/runners/mcp/run.ts +55 -0
  95. package/src/runners/validate/run.ts +63 -0
  96. package/src/{utils/telemetry.ts → telemetry.ts} +12 -5
  97. package/dist/agent-BEgI2HXH.cjs +0 -58
  98. package/dist/agent-BEgI2HXH.cjs.map +0 -1
  99. package/dist/agent-B_pirbeB.cjs.map +0 -1
  100. package/dist/agent-CTdJEHEs.js +0 -56
  101. package/dist/agent-CTdJEHEs.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-Cg8yufrw.js.map +0 -1
  108. package/dist/generate-DDCwNQNo.cjs.map +0 -1
  109. package/dist/generate-K8MJ9aQF.cjs.map +0 -1
  110. package/dist/generate-YPtfjsg4.js.map +0 -1
  111. package/dist/init-Bu95ML_u.cjs +0 -25
  112. package/dist/init-Bu95ML_u.cjs.map +0 -1
  113. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  114. package/dist/init-eNRlotJK.js.map +0 -1
  115. package/dist/init-ooJeOBGt.js +0 -25
  116. package/dist/init-ooJeOBGt.js.map +0 -1
  117. package/dist/mcp-C-d5N1wZ.js +0 -16
  118. package/dist/mcp-C-d5N1wZ.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-Dpu8vzzj.cjs +0 -16
  124. package/dist/mcp-Dpu8vzzj.cjs.map +0 -1
  125. package/dist/package-D5arPDnh.cjs.map +0 -1
  126. package/dist/package-DqZsMLZ9.js +0 -6
  127. package/dist/package-DqZsMLZ9.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-CIR3_lZI.js +0 -25
  131. package/dist/validate-CIR3_lZI.js.map +0 -1
  132. package/dist/validate-DcqUb4DM.cjs +0 -25
  133. package/dist/validate-DcqUb4DM.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
package/src/constants.ts CHANGED
@@ -1,9 +1,4 @@
1
- /**
2
- * Default filename for the Kubb configuration file.
3
- *
4
- * Used by the `init` command when scaffolding new projects and by the `agent` default config.
5
- */
6
- export const KUBB_CONFIG_FILENAME = 'kubb.config.ts' as const
1
+ import { KUBB_CONFIG_FILENAME } from '@internals/shared'
7
2
 
8
3
  /**
9
4
  * NPM registry endpoint used to check for @kubb/cli updates.
@@ -45,60 +40,9 @@ export const agentDefaults = {
45
40
  host: 'localhost',
46
41
  configFile: KUBB_CONFIG_FILENAME,
47
42
  retryTimeout: '30000',
48
- studioUrl: 'https://studio.kubb.dev',
43
+ studioUrl: 'https://kubb.studio',
49
44
  /**
50
45
  * Relative path from the @kubb/agent package root to the server entry.
51
46
  */
52
47
  serverEntryPath: '.output/server/index.mjs',
53
48
  } as const
54
-
55
- /**
56
- * Default values used during interactive `init` scaffolding.
57
- */
58
- export const initDefaults = {
59
- inputPath: './openapi.yaml',
60
- outputPath: './src/gen',
61
- plugins: ['plugin-ts'],
62
- } as const
63
-
64
- /**
65
- * Maps each plugin value to the default config snippet inserted by `init`.
66
- * The `satisfies` constraint ensures all values remain plain strings while
67
- * `as const` keeps the object deeply immutable.
68
- */
69
- export const pluginDefaultConfigs = {
70
- 'plugin-ts': `pluginTs({
71
- output: { path: 'models' },
72
- })`,
73
- 'plugin-client': `pluginClient({
74
- output: { path: 'clients' },
75
- })`,
76
- 'plugin-react-query': `pluginReactQuery({
77
- output: { path: 'hooks' },
78
- })`,
79
- 'plugin-vue-query': `pluginVueQuery({
80
- output: { path: 'hooks' },
81
- })`,
82
- 'plugin-zod': `pluginZod({
83
- output: { path: 'zod' },
84
- })`,
85
- 'plugin-faker': `pluginFaker({
86
- output: { path: 'mocks' },
87
- })`,
88
- 'plugin-msw': `pluginMsw({
89
- output: { path: 'msw' },
90
- })`,
91
- 'plugin-cypress': `pluginCypress({
92
- output: { path: 'cypress' },
93
- })`,
94
- 'plugin-mcp': `pluginMcp({
95
- output: { path: 'mcp' },
96
- })`,
97
- 'plugin-redoc': `pluginRedoc({
98
- output: { path: 'redoc' },
99
- })`,
100
- } as const satisfies Record<string, string>
101
-
102
- /**
103
- * Color palette used by randomCliColor() for deterministic plugin name coloring.
104
- */
package/src/index.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { styleText } from 'node:util'
2
- import { createCLI } from '@internals/utils'
2
+ import { createCLI, isFlag } from '@internals/utils'
3
3
  import { version } from '../package.json'
4
4
  import { QUIET_FLAGS } from './constants.ts'
5
- import { isFlag } from './utils/flags.ts'
6
- import { isTelemetryDisabled } from './utils/telemetry.ts'
5
+ import { isTelemetryDisabled } from './telemetry.ts'
7
6
 
8
7
  const cli = createCLI()
9
8
 
@@ -11,14 +10,17 @@ function shouldShowTelemetryNotice(argv: Array<string>): boolean {
11
10
  if (isTelemetryDisabled()) {
12
11
  return false
13
12
  }
13
+
14
14
  // Skip when the user is just asking for help or version info
15
15
  if (argv.some((arg) => isFlag(QUIET_FLAGS, arg))) {
16
16
  return false
17
17
  }
18
+
18
19
  // Skip in non-interactive / scripting contexts
19
20
  if (!process.stdout.isTTY) {
20
21
  return false
21
22
  }
23
+
22
24
  return true
23
25
  }
24
26
 
@@ -4,10 +4,27 @@ import { styleText } from 'node:util'
4
4
  import * as clack from '@clack/prompts'
5
5
  import { formatMs, formatMsWithColor, getIntro, toCause } from '@internals/utils'
6
6
  import { defineLogger, logLevel as logLevelMap } from '@kubb/core'
7
- import { getSummary } from '../utils/getSummary.ts'
8
- import { runHook } from '../utils/runHook.ts'
9
- import { ClackWritable } from '../utils/Writables.ts'
7
+ import { getSummary } from './utils.ts'
10
8
  import { buildProgressLine, formatCommandWithArgs, formatMessage } from './utils.ts'
9
+ import { Writable } from 'node:stream'
10
+ import type { WritableOptions } from 'node:stream'
11
+
12
+ /**
13
+ * Node.js `Writable` stream that forwards each chunk to a clack `taskLog` message.
14
+ * Used to pipe hook subprocess output into the clack task log UI.
15
+ */
16
+ class ClackWritable extends Writable {
17
+ taskLog: ReturnType<typeof clack.taskLog>
18
+ constructor(taskLog: ReturnType<typeof clack.taskLog>, opts?: WritableOptions) {
19
+ super(opts)
20
+
21
+ this.taskLog = taskLog
22
+ }
23
+ _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
24
+ this.taskLog.message(`${styleText('dim', chunk.toString())}`)
25
+ callback()
26
+ }
27
+ }
11
28
 
12
29
  /**
13
30
  * TTY logger with beautiful UI and progress indicators for local development.
@@ -364,51 +381,15 @@ Run \`npm install -g @kubb/cli\` to update`,
364
381
  clack.outro(text)
365
382
  })
366
383
 
367
- context.on('kubb:hook:start', async ({ id, command, args }) => {
368
- const commandWithArgs = formatCommandWithArgs(command, args)
369
- const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} started`)
370
-
371
- // Skip hook execution if no id is provided (e.g., during benchmarks or tests)
372
- if (!id) {
373
- return
374
- }
375
-
384
+ context.on('kubb:hook:start', ({ command, args }) => {
376
385
  if (logLevel <= logLevelMap.silent) {
377
- await runHook({
378
- id,
379
- command,
380
- args,
381
- commandWithArgs,
382
- context,
383
- sink: {
384
- onStderr: (s) => console.error(s),
385
- onStdout: (s) => console.log(s),
386
- },
387
- })
388
386
  return
389
387
  }
390
388
 
391
- clack.intro(text)
392
-
393
- const logger = clack.taskLog({
394
- title: getMessage(['Executing hook', logLevel >= logLevelMap.info ? styleText('dim', commandWithArgs) : undefined].filter(Boolean).join(' ')),
395
- })
396
-
397
- const writable = new ClackWritable(logger)
389
+ const commandWithArgs = formatCommandWithArgs(command, args)
390
+ const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} started`)
398
391
 
399
- await runHook({
400
- id,
401
- command,
402
- args,
403
- commandWithArgs,
404
- context,
405
- stream: true,
406
- sink: {
407
- onLine: (line) => writable.write(line),
408
- onStderr: (s) => logger.error(s),
409
- onStdout: (s) => logger.message(s),
410
- },
411
- })
392
+ clack.intro(text)
412
393
  })
413
394
 
414
395
  context.on('kubb:hook:end', ({ command, args }) => {
@@ -454,5 +435,26 @@ Run \`npm install -g @kubb/cli\` to update`,
454
435
  context.on('kubb:lifecycle:end', () => {
455
436
  reset()
456
437
  })
438
+
439
+ return (commandWithArgs: string) => {
440
+ if (logLevel <= logLevelMap.silent) {
441
+ return {
442
+ onStdout: (s: string) => console.log(s),
443
+ onStderr: (s: string) => console.error(s),
444
+ }
445
+ }
446
+
447
+ const logger = clack.taskLog({
448
+ title: getMessage(['Executing hook', logLevel >= logLevelMap.info ? styleText('dim', commandWithArgs) : undefined].filter(Boolean).join(' ')),
449
+ })
450
+ const writable = new ClackWritable(logger)
451
+
452
+ return {
453
+ stream: true,
454
+ onLine: (line: string) => writable.write(line),
455
+ onStdout: (s: string) => logger.message(s),
456
+ onStderr: (s: string) => logger.error(s),
457
+ }
458
+ }
457
459
  },
458
460
  })
@@ -4,14 +4,24 @@ import { formatMs, write } from '@internals/utils'
4
4
  import { defineLogger } from '@kubb/core'
5
5
 
6
6
  type CachedEvent = {
7
+ /**
8
+ * Timestamp when this event was captured, used to derive the log filename.
9
+ */
7
10
  date: Date
11
+ /**
12
+ * Accumulated log lines for this event.
13
+ */
8
14
  logs: string[]
15
+ /**
16
+ * Optional override for the output filename inside `.kubb/`. When omitted, the filename is derived from `date`.
17
+ */
9
18
  fileName?: string
10
19
  }
11
20
 
12
21
  /**
13
22
  * FileSystem logger that captures debug events and writes them to `.kubb` directory files.
14
- * Note: Logs write on `lifecycle:end` or process exit. Cached logs may be lost if the process crashes before these events.
23
+ *
24
+ * @note Logs are written on `kubb:lifecycle:end` or process exit. Cached logs may be lost if the process crashes before either event.
15
25
  */
16
26
  export const fileSystemLogger = defineLogger({
17
27
  name: 'filesystem',
@@ -42,13 +52,15 @@ export const fileSystemLogger = defineLogger({
42
52
  }
43
53
 
44
54
  if (log.logs.length > 0) {
45
- const timestamp = log.date.toLocaleString()
46
- files[pathName].push(`[${timestamp}]\n${log.logs.join('\n')}`)
55
+ const prefix = `[${log.date.toLocaleString()}] `
56
+ const indent = ' '.repeat(prefix.length)
57
+ const [first, ...rest] = log.logs
58
+ files[pathName].push([prefix + first, ...rest.map((line) => indent + line)].join('\n'))
47
59
  }
48
60
  }
49
61
 
50
62
  for (const [fileName, logs] of Object.entries(files)) {
51
- await write(fileName, logs.join('\n\n'))
63
+ await write(fileName, logs.join('\n'))
52
64
  }
53
65
 
54
66
  return Object.keys(files)
@@ -57,21 +69,21 @@ export const fileSystemLogger = defineLogger({
57
69
  context.on('kubb:info', ({ message, info }) => {
58
70
  state.cachedLogs.add({
59
71
  date: new Date(),
60
- logs: [`ℹ ${message} ${info}`],
72
+ logs: [`ℹ ${[message, info].filter(Boolean).join(' ')}`],
61
73
  })
62
74
  })
63
75
 
64
76
  context.on('kubb:success', ({ message, info }) => {
65
77
  state.cachedLogs.add({
66
78
  date: new Date(),
67
- logs: [`✓ ${message} ${info}`],
79
+ logs: [`✓ ${[message, info].filter(Boolean).join(' ')}`],
68
80
  })
69
81
  })
70
82
 
71
83
  context.on('kubb:warn', ({ message, info }) => {
72
84
  state.cachedLogs.add({
73
85
  date: new Date(),
74
- logs: [`⚠ ${message} ${info}`],
86
+ logs: [`⚠ ${[message, info].filter(Boolean).join(' ')}`],
75
87
  })
76
88
  })
77
89
 
@@ -82,17 +94,18 @@ export const fileSystemLogger = defineLogger({
82
94
  })
83
95
  })
84
96
 
85
- context.on('kubb:debug', (message) => {
97
+ context.on('kubb:debug', ({ date, fileName, logs }) => {
86
98
  state.cachedLogs.add({
87
- date: new Date(),
88
- logs: message.logs,
99
+ date,
100
+ fileName,
101
+ logs,
89
102
  })
90
103
  })
91
104
 
92
105
  context.on('kubb:plugin:start', ({ plugin }) => {
93
106
  state.cachedLogs.add({
94
107
  date: new Date(),
95
- logs: [`Generating ${plugin.name}`],
108
+ logs: [`► Generating ${plugin.name}`],
96
109
  })
97
110
  })
98
111
 
@@ -101,14 +114,14 @@ export const fileSystemLogger = defineLogger({
101
114
 
102
115
  state.cachedLogs.add({
103
116
  date: new Date(),
104
- logs: [success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`],
117
+ logs: [success ? `✓ ${plugin.name} completed in ${durationStr}` : `✗ ${plugin.name} failed in ${durationStr}`],
105
118
  })
106
119
  })
107
120
 
108
121
  context.on('kubb:files:processing:start', ({ files }) => {
109
122
  state.cachedLogs.add({
110
123
  date: new Date(),
111
- logs: [`Start ${files.length} writing:`, ...files.map((file) => file.path)],
124
+ logs: [`► Writing ${files.length} files`, ...files.map((file) => ` ${file.path}`)],
112
125
  })
113
126
  })
114
127
 
@@ -1,7 +1,6 @@
1
1
  import { styleText } from 'node:util'
2
2
  import { formatHrtime, formatMs, formatMsWithColor, toCause } from '@internals/utils'
3
3
  import { type Config, defineLogger, logLevel as logLevelMap } from '@kubb/core'
4
- import { runHook } from '../utils/runHook.ts'
5
4
  import { buildProgressLine, formatCommandWithArgs, formatMessage } from './utils.ts'
6
5
 
7
6
  /**
@@ -307,34 +306,18 @@ export const githubActionsLogger = defineLogger({
307
306
  }
308
307
  })
309
308
 
310
- context.on('kubb:hook:start', async ({ id, command, args }) => {
309
+ context.on('kubb:hook:start', ({ command, args }) => {
310
+ if (logLevel <= logLevelMap.silent) {
311
+ return
312
+ }
313
+
311
314
  const commandWithArgs = formatCommandWithArgs(command, args)
312
315
  const text = getMessage(`Hook ${styleText('dim', commandWithArgs)} started`)
313
316
 
314
- if (logLevel > logLevelMap.silent) {
315
- if (state.currentConfigs.length === 1) {
316
- openGroup(`Hook ${commandWithArgs}`)
317
- }
318
- console.log(text)
319
- }
320
-
321
- // Skip hook execution if no id is provided (e.g., during benchmarks or tests)
322
- if (!id) {
323
- return
317
+ if (state.currentConfigs.length === 1) {
318
+ openGroup(`Hook ${commandWithArgs}`)
324
319
  }
325
-
326
- await runHook({
327
- id,
328
- command,
329
- args,
330
- commandWithArgs,
331
- context,
332
- sink: {
333
- // GHA formats errors with the ::error:: annotation
334
- onStdout: logLevel > logLevelMap.silent ? (s) => console.log(s) : undefined,
335
- onStderr: logLevel > logLevelMap.silent ? (s) => console.error(`::error::${s}`) : undefined,
336
- },
337
- })
320
+ console.log(text)
338
321
  })
339
322
 
340
323
  context.on('kubb:hook:end', ({ command, args }) => {
@@ -375,5 +358,10 @@ export const githubActionsLogger = defineLogger({
375
358
  context.on('kubb:lifecycle:end', () => {
376
359
  reset()
377
360
  })
361
+
362
+ return (_commandWithArgs: string) => ({
363
+ onStdout: logLevel > logLevelMap.silent ? (s: string) => console.log(s) : undefined,
364
+ onStderr: logLevel > logLevelMap.silent ? (s: string) => console.error(`::error::${s}`) : undefined,
365
+ })
378
366
  },
379
367
  })
@@ -2,8 +2,7 @@ import { relative } from 'node:path'
2
2
  import { formatMs, toCause } from '@internals/utils'
3
3
  import { defineLogger, logLevel as logLevelMap } from '@kubb/core'
4
4
  import { SUMMARY_SEPARATOR } from '../constants.ts'
5
- import { getSummary } from '../utils/getSummary.ts'
6
- import { runHook } from '../utils/runHook.ts'
5
+ import { getSummary } from './utils.ts'
7
6
  import { formatCommandWithArgs, formatMessage } from './utils.ts'
8
7
 
9
8
  /**
@@ -199,30 +198,15 @@ export const plainLogger = defineLogger({
199
198
  console.log(text)
200
199
  })
201
200
 
202
- context.on('kubb:hook:start', async ({ id, command, args }) => {
203
- const commandWithArgs = formatCommandWithArgs(command, args)
204
- const text = getMessage(`Hook ${commandWithArgs} started`)
205
-
206
- if (logLevel > logLevelMap.silent) {
207
- console.log(text)
208
- }
209
-
210
- // Skip hook execution if no id is provided (e.g., during benchmarks or tests)
211
- if (!id) {
201
+ context.on('kubb:hook:start', ({ command, args }) => {
202
+ if (logLevel <= logLevelMap.silent) {
212
203
  return
213
204
  }
214
205
 
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
- })
206
+ const commandWithArgs = formatCommandWithArgs(command, args)
207
+ const text = getMessage(`Hook ${commandWithArgs} started`)
208
+
209
+ console.log(text)
226
210
  })
227
211
 
228
212
  context.on('kubb:hook:end', ({ command, args }) => {
@@ -250,5 +234,10 @@ export const plainLogger = defineLogger({
250
234
  console.log(summary.join('\n'))
251
235
  console.log(SUMMARY_SEPARATOR)
252
236
  })
237
+
238
+ return (_commandWithArgs: string) => ({
239
+ onStdout: logLevel > logLevelMap.silent ? (s: string) => console.log(s) : undefined,
240
+ onStderr: logLevel > logLevelMap.silent ? (s: string) => console.error(s) : undefined,
241
+ })
253
242
  },
254
243
  })
@@ -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,57 @@
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
+ export type HookSinkFactory = (commandWithArgs: string) => HookSinkOptions | undefined
48
+
49
+ /**
50
+ * Logger variant that may return a {@link HookSinkFactory} from `install`.
51
+ * The factory is forwarded to hook execution so the logger controls subprocess output routing.
52
+ */
53
+ type CLILogger = Logger<LoggerOptions, HookSinkFactory | void>
54
+
11
55
  /**
12
56
  * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
13
57
  * Shared across all logger adapters to avoid duplication.
@@ -26,11 +70,29 @@ export function formatMessage(message: string, logLevel: number): string {
26
70
  }
27
71
 
28
72
  type ProgressState = {
73
+ /**
74
+ * Total number of plugins scheduled for this generation run.
75
+ */
29
76
  totalPlugins: number
77
+ /**
78
+ * Number of plugins that have finished without error.
79
+ */
30
80
  completedPlugins: number
81
+ /**
82
+ * Number of plugins that exited with an error.
83
+ */
31
84
  failedPlugins: number
85
+ /**
86
+ * Total number of files expected to be written.
87
+ */
32
88
  totalFiles: number
89
+ /**
90
+ * Number of files written so far.
91
+ */
33
92
  processedFiles: number
93
+ /**
94
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
95
+ */
34
96
  hrStart: [number, number]
35
97
  }
36
98
 
@@ -80,27 +142,111 @@ function detectLogger(): LoggerType {
80
142
  return 'plain'
81
143
  }
82
144
 
83
- const logMapper = {
145
+ const logMapper: Record<LoggerType, CLILogger> = {
84
146
  clack: clackLogger,
85
147
  plain: plainLogger,
86
148
  'github-actions': githubActionsLogger,
87
- } as const satisfies Record<LoggerType, Logger>
149
+ }
88
150
 
89
- export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<void> {
151
+ export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<HookSinkFactory | undefined> {
90
152
  const type = detectLogger()
91
153
 
92
- const logger = logMapper[type] as Logger
154
+ const logger = logMapper[type]
93
155
 
94
156
  if (!logger) {
95
157
  throw new Error(`Unknown adapter type: ${type}`)
96
158
  }
97
159
 
98
- // Install primary logger
99
- const cleanup = await logger.install(context, { logLevel })
160
+ const makeSink = await logger.install(context, { logLevel })
100
161
 
101
162
  if (logLevel >= logLevelMap.debug) {
102
163
  await fileSystemLogger.install(context, { logLevel })
103
164
  }
104
165
 
105
- return cleanup
166
+ return typeof makeSink === 'function' ? makeSink : undefined
167
+ }
168
+
169
+ type SummaryProps = {
170
+ /**
171
+ * Set of plugins that failed during this generation run, each with its error.
172
+ */
173
+ failedPlugins: Set<{ plugin: Plugin; error: Error }>
174
+ /**
175
+ * Overall generation status used to choose success or failure formatting.
176
+ */
177
+ status: 'success' | 'failed'
178
+ /**
179
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
180
+ */
181
+ hrStart: [number, number]
182
+ /**
183
+ * Total number of files written during this generation run.
184
+ */
185
+ filesCreated: number
186
+ /**
187
+ * Resolved Kubb config for this generation entry, used to read plugin count and output path.
188
+ */
189
+ config: Config
190
+ /**
191
+ * Per-plugin timing map (plugin name → duration in ms). When provided, a timing bar chart is appended.
192
+ */
193
+ pluginTimings?: Map<string, number>
194
+ }
195
+
196
+ /**
197
+ * Builds the generation summary lines rendered in the end-of-run box.
198
+ * Returns an array of styled strings, one per summary row.
199
+ */
200
+ export function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }: SummaryProps): string[] {
201
+ const duration = formatHrtime(hrStart)
202
+
203
+ const pluginsCount = config.plugins?.length ?? 0
204
+ const successCount = pluginsCount - failedPlugins.size
205
+
206
+ const meta = {
207
+ plugins:
208
+ status === 'success'
209
+ ? `${styleText('green', `${successCount} successful`)}, ${pluginsCount} total`
210
+ : `${styleText('green', `${successCount} successful`)}, ${styleText('red', `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
211
+ pluginsFailed: status === 'failed' ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(', ') : undefined,
212
+ filesCreated,
213
+ time: styleText('green', duration),
214
+ output: path.resolve(config.root, config.output.path),
215
+ } as const
216
+
217
+ const labels = {
218
+ plugins: 'Plugins:',
219
+ failed: 'Failed:',
220
+ generated: 'Generated:',
221
+ pluginTimings: 'Plugin Timings:',
222
+ output: 'Output:',
223
+ }
224
+ const maxLength = Math.max(0, ...[...Object.values(labels), ...(pluginTimings ? Array.from(pluginTimings.keys()) : [])].map((s) => s.length))
225
+
226
+ const summaryLines: string[] = []
227
+ summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`)
228
+
229
+ if (meta.pluginsFailed) {
230
+ summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`)
231
+ }
232
+
233
+ summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`)
234
+
235
+ if (pluginTimings && pluginTimings.size > 0) {
236
+ const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1])
237
+
238
+ summaryLines.push(`${labels.pluginTimings}`)
239
+
240
+ sortedTimings.forEach(([name, time]) => {
241
+ const timeStr = time >= 1000 ? `${(time / 1000).toFixed(2)}s` : `${Math.round(time)}ms`
242
+ const barLength = Math.min(Math.ceil(time / SUMMARY_TIME_SCALE_DIVISOR), SUMMARY_MAX_BAR_LENGTH)
243
+ const bar = styleText('dim', '█'.repeat(barLength))
244
+
245
+ summaryLines.push(`${styleText('dim', '•')} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`)
246
+ })
247
+ }
248
+
249
+ summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`)
250
+
251
+ return summaryLines
106
252
  }