@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.
Files changed (146) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +171 -51
  3. package/dist/constants-BQ8LZB1P.js +23 -0
  4. package/dist/constants-BQ8LZB1P.js.map +1 -0
  5. package/dist/constants-MzEjK668.cjs +40 -0
  6. package/dist/constants-MzEjK668.cjs.map +1 -0
  7. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  8. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  9. package/dist/{define-Ctii4bel.js → define-C63T4jp6.js} +2 -2
  10. package/dist/{define-Ctii4bel.js.map → define-C63T4jp6.js.map} +1 -1
  11. package/dist/{errors-CjPmyZHy.js → errors-BsemQCMn.js} +2 -2
  12. package/dist/{errors-CjPmyZHy.js.map → errors-BsemQCMn.js.map} +1 -1
  13. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  14. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  15. package/dist/generate-CKnn3tQa.js +83 -0
  16. package/dist/generate-CKnn3tQa.js.map +1 -0
  17. package/dist/generate-Q6GMu4L8.cjs +82 -0
  18. package/dist/generate-Q6GMu4L8.cjs.map +1 -0
  19. package/dist/index.cjs +22 -15
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +22 -15
  23. package/dist/index.js.map +1 -1
  24. package/dist/init-C5iCqBwA.cjs +53 -0
  25. package/dist/init-C5iCqBwA.cjs.map +1 -0
  26. package/dist/init-DyOF6CiQ.js +53 -0
  27. package/dist/init-DyOF6CiQ.js.map +1 -0
  28. package/dist/mcp-09FvxYWS.js +39 -0
  29. package/dist/mcp-09FvxYWS.js.map +1 -0
  30. package/dist/mcp-BN5HQYdK.cjs +39 -0
  31. package/dist/mcp-BN5HQYdK.cjs.map +1 -0
  32. package/dist/package-Bm6VUbtL.js +6 -0
  33. package/dist/package-Bm6VUbtL.js.map +1 -0
  34. package/dist/{package-BmYRU2hz.cjs → package-DOVOGEEY.cjs} +2 -2
  35. package/dist/package-DOVOGEEY.cjs.map +1 -0
  36. package/dist/run-BO7phoNN.js +51 -0
  37. package/dist/run-BO7phoNN.js.map +1 -0
  38. package/dist/{init-C5sZulT6.cjs → run-BtjzfTz3.cjs} +155 -85
  39. package/dist/run-BtjzfTz3.cjs.map +1 -0
  40. package/dist/run-BzaKz_nl.js +32 -0
  41. package/dist/run-BzaKz_nl.js.map +1 -0
  42. package/dist/{init-Cag3082g.js → run-C-omuksC.js} +147 -77
  43. package/dist/run-C-omuksC.js.map +1 -0
  44. package/dist/run-CkTpemme.cjs +52 -0
  45. package/dist/run-CkTpemme.cjs.map +1 -0
  46. package/dist/run-Cl4SrSob.cjs +33 -0
  47. package/dist/run-Cl4SrSob.cjs.map +1 -0
  48. package/dist/run-CrvmI4G2.cjs +1520 -0
  49. package/dist/run-CrvmI4G2.cjs.map +1 -0
  50. package/dist/run-DvZ5i2lT.js +1517 -0
  51. package/dist/run-DvZ5i2lT.js.map +1 -0
  52. package/dist/{shell-DLzN4fRo.js → shell-DsgkfUSW.js} +2 -2
  53. package/dist/{shell-DLzN4fRo.js.map → shell-DsgkfUSW.js.map} +1 -1
  54. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  55. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  56. package/dist/validate-5atkOC73.js +26 -0
  57. package/dist/validate-5atkOC73.js.map +1 -0
  58. package/dist/validate-C6KPFEex.cjs +26 -0
  59. package/dist/validate-C6KPFEex.cjs.map +1 -0
  60. package/package.json +14 -24
  61. package/src/commands/generate.ts +27 -13
  62. package/src/commands/init.ts +34 -3
  63. package/src/commands/mcp.ts +28 -4
  64. package/src/commands/validate.ts +6 -4
  65. package/src/constants.ts +1 -86
  66. package/src/index.ts +7 -6
  67. package/src/loggers/clackLogger.ts +137 -178
  68. package/src/loggers/plainLogger.ts +49 -102
  69. package/src/loggers/types.ts +6 -1
  70. package/src/loggers/utils.ts +141 -26
  71. package/src/runners/generate/run.ts +406 -0
  72. package/src/runners/generate/utils.ts +228 -0
  73. package/src/runners/init/run.ts +210 -0
  74. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  75. package/src/runners/mcp/run.ts +37 -0
  76. package/src/runners/validate/run.ts +63 -0
  77. package/dist/agent-BcUEl9yB.js +0 -56
  78. package/dist/agent-BcUEl9yB.js.map +0 -1
  79. package/dist/agent-CS45W0kL.cjs +0 -122
  80. package/dist/agent-CS45W0kL.cjs.map +0 -1
  81. package/dist/agent-CsMvXeqI.cjs +0 -58
  82. package/dist/agent-CsMvXeqI.cjs.map +0 -1
  83. package/dist/agent-IP0eLV3C.js +0 -118
  84. package/dist/agent-IP0eLV3C.js.map +0 -1
  85. package/dist/constants-B4iBDvCe.cjs +0 -148
  86. package/dist/constants-B4iBDvCe.cjs.map +0 -1
  87. package/dist/constants-DmPrkaz8.js +0 -95
  88. package/dist/constants-DmPrkaz8.js.map +0 -1
  89. package/dist/generate-7td_hs73.cjs +0 -65
  90. package/dist/generate-7td_hs73.cjs.map +0 -1
  91. package/dist/generate-BqeFFQGD.js +0 -66
  92. package/dist/generate-BqeFFQGD.js.map +0 -1
  93. package/dist/generate-CUd1dUY5.cjs +0 -1755
  94. package/dist/generate-CUd1dUY5.cjs.map +0 -1
  95. package/dist/generate-DVmGtwWe.js +0 -1752
  96. package/dist/generate-DVmGtwWe.js.map +0 -1
  97. package/dist/init-C5sZulT6.cjs.map +0 -1
  98. package/dist/init-Cag3082g.js.map +0 -1
  99. package/dist/init-CfAn19gC.js +0 -25
  100. package/dist/init-CfAn19gC.js.map +0 -1
  101. package/dist/init-CfsYoyGe.cjs +0 -25
  102. package/dist/init-CfsYoyGe.cjs.map +0 -1
  103. package/dist/mcp-BfORW-mY.cjs +0 -47
  104. package/dist/mcp-BfORW-mY.cjs.map +0 -1
  105. package/dist/mcp-BtOV6acy.js +0 -16
  106. package/dist/mcp-BtOV6acy.js.map +0 -1
  107. package/dist/mcp-CIbuLGMx.cjs +0 -16
  108. package/dist/mcp-CIbuLGMx.cjs.map +0 -1
  109. package/dist/mcp-DtQ5o0On.js +0 -46
  110. package/dist/mcp-DtQ5o0On.js.map +0 -1
  111. package/dist/package-BmYRU2hz.cjs.map +0 -1
  112. package/dist/package-DBU5ii-k.js +0 -6
  113. package/dist/package-DBU5ii-k.js.map +0 -1
  114. package/dist/telemetry-BU25EoI-.cjs +0 -282
  115. package/dist/telemetry-BU25EoI-.cjs.map +0 -1
  116. package/dist/telemetry-CaNU4-Bf.js +0 -245
  117. package/dist/telemetry-CaNU4-Bf.js.map +0 -1
  118. package/dist/validate-CQqM9siF.js +0 -25
  119. package/dist/validate-CQqM9siF.js.map +0 -1
  120. package/dist/validate-DBXLaLIn.cjs +0 -34
  121. package/dist/validate-DBXLaLIn.cjs.map +0 -1
  122. package/dist/validate-DI23zgmL.js +0 -33
  123. package/dist/validate-DI23zgmL.js.map +0 -1
  124. package/dist/validate-DwX4LzYq.cjs +0 -25
  125. package/dist/validate-DwX4LzYq.cjs.map +0 -1
  126. package/src/commands/agent/start.ts +0 -47
  127. package/src/commands/agent.ts +0 -8
  128. package/src/loggers/fileSystemLogger.ts +0 -138
  129. package/src/loggers/githubActionsLogger.ts +0 -379
  130. package/src/runners/agent.ts +0 -155
  131. package/src/runners/generate.ts +0 -333
  132. package/src/runners/init.ts +0 -296
  133. package/src/runners/mcp.ts +0 -51
  134. package/src/runners/validate.ts +0 -39
  135. package/src/types.ts +0 -11
  136. package/src/utils/Writables.ts +0 -17
  137. package/src/utils/executeHooks.ts +0 -45
  138. package/src/utils/flags.ts +0 -9
  139. package/src/utils/getConfig.ts +0 -10
  140. package/src/utils/getCosmiConfig.ts +0 -75
  141. package/src/utils/getSummary.ts +0 -68
  142. package/src/utils/runHook.ts +0 -91
  143. package/src/utils/telemetry.ts +0 -273
  144. package/src/utils/watcher.ts +0 -19
  145. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
  146. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -0,0 +1,1520 @@
1
+ const require_chunk = require("./chunk-Bx3C2hgW.cjs");
2
+ const require_errors = require("./errors-DykI11xo.cjs");
3
+ const require_shell = require("./shell-Lh-vLWwH.cjs");
4
+ const require_package = require("./package-DOVOGEEY.cjs");
5
+ const require_constants = require("./constants-MzEjK668.cjs");
6
+ let node_util = require("node:util");
7
+ let node_events = require("node:events");
8
+ let node_crypto = require("node:crypto");
9
+ let node_child_process = require("node:child_process");
10
+ let node_dns = require("node:dns");
11
+ let node_fs = require("node:fs");
12
+ let node_path = require("node:path");
13
+ node_path = require_chunk.__toESM(node_path, 1);
14
+ let _kubb_core = require("@kubb/core");
15
+ let node_process = require("node:process");
16
+ node_process = require_chunk.__toESM(node_process, 1);
17
+ let _clack_prompts = require("@clack/prompts");
18
+ _clack_prompts = require_chunk.__toESM(_clack_prompts, 1);
19
+ let cosmiconfig = require("cosmiconfig");
20
+ let jiti = require("jiti");
21
+ let tinyexec = require("tinyexec");
22
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
23
+ /**
24
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
25
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
30
+ * emitter.on('build', async (name) => { console.log(name) })
31
+ * await emitter.emit('build', 'petstore') // all listeners awaited
32
+ * ```
33
+ */
34
+ var AsyncEventEmitter = class {
35
+ /**
36
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
37
+ * @default 10
38
+ */
39
+ constructor(maxListener = 10) {
40
+ this.#emitter.setMaxListeners(maxListener);
41
+ }
42
+ #emitter = new node_events.EventEmitter();
43
+ /**
44
+ * Emits `eventName` and awaits all registered listeners sequentially.
45
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * await emitter.emit('build', 'petstore')
50
+ * ```
51
+ */
52
+ emit(eventName, ...eventArgs) {
53
+ const listeners = this.#emitter.listeners(eventName);
54
+ if (listeners.length === 0) return;
55
+ return this.#emitAll(eventName, listeners, eventArgs);
56
+ }
57
+ async #emitAll(eventName, listeners, eventArgs) {
58
+ for (const listener of listeners) try {
59
+ await listener(...eventArgs);
60
+ } catch (err) {
61
+ let serializedArgs;
62
+ try {
63
+ serializedArgs = JSON.stringify(eventArgs);
64
+ } catch {
65
+ serializedArgs = String(eventArgs);
66
+ }
67
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: require_errors.toError(err) });
68
+ }
69
+ }
70
+ /**
71
+ * Registers a persistent listener for `eventName`.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * emitter.on('build', async (name) => { console.log(name) })
76
+ * ```
77
+ */
78
+ on(eventName, handler) {
79
+ this.#emitter.on(eventName, handler);
80
+ }
81
+ /**
82
+ * Registers a one-shot listener that removes itself after the first invocation.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * emitter.onOnce('build', async (name) => { console.log(name) })
87
+ * ```
88
+ */
89
+ onOnce(eventName, handler) {
90
+ const wrapper = (...args) => {
91
+ this.off(eventName, wrapper);
92
+ return handler(...args);
93
+ };
94
+ this.on(eventName, wrapper);
95
+ }
96
+ /**
97
+ * Removes a previously registered listener.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * emitter.off('build', handler)
102
+ * ```
103
+ */
104
+ off(eventName, handler) {
105
+ this.#emitter.off(eventName, handler);
106
+ }
107
+ /**
108
+ * Returns the number of listeners registered for `eventName`.
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * emitter.on('build', handler)
113
+ * emitter.listenerCount('build') // 1
114
+ * ```
115
+ */
116
+ listenerCount(eventName) {
117
+ return this.#emitter.listenerCount(eventName);
118
+ }
119
+ /**
120
+ * Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
121
+ * Set this above the expected listener count when many listeners attach by design.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * emitter.setMaxListeners(40)
126
+ * ```
127
+ */
128
+ setMaxListeners(max) {
129
+ this.#emitter.setMaxListeners(max);
130
+ }
131
+ /**
132
+ * Returns the current per-event listener ceiling.
133
+ */
134
+ getMaxListeners() {
135
+ return this.#emitter.getMaxListeners();
136
+ }
137
+ /**
138
+ * Removes all listeners from every event channel.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * emitter.removeAll()
143
+ * ```
144
+ */
145
+ removeAll() {
146
+ this.#emitter.removeAllListeners();
147
+ }
148
+ };
149
+ //#endregion
150
+ //#region ../../internals/utils/src/time.ts
151
+ /**
152
+ * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
153
+ * Rounds to 2 decimal places for sub-millisecond precision without noise.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * const start = process.hrtime()
158
+ * doWork()
159
+ * getElapsedMs(start) // 42.35
160
+ * ```
161
+ */
162
+ function getElapsedMs(hrStart) {
163
+ const [seconds, nanoseconds] = process.hrtime(hrStart);
164
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
165
+ return Math.round(ms * 100) / 100;
166
+ }
167
+ /**
168
+ * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * formatMs(250) // '250ms'
173
+ * formatMs(1500) // '1.50s'
174
+ * formatMs(90000) // '1m 30.0s'
175
+ * ```
176
+ */
177
+ function formatMs(ms) {
178
+ if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
179
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
180
+ return `${Math.round(ms)}ms`;
181
+ }
182
+ /**
183
+ * Formats the elapsed time since `hrStart` as a human-readable string.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * const start = process.hrtime()
188
+ * doWork()
189
+ * formatHrtime(start) // '1.50s'
190
+ * ```
191
+ */
192
+ function formatHrtime(hrStart) {
193
+ return formatMs(getElapsedMs(hrStart));
194
+ }
195
+ //#endregion
196
+ //#region ../../internals/utils/src/colors.ts
197
+ /**
198
+ * Parses a CSS hex color string (`#RGB`) into its RGB channels.
199
+ * Falls back to `255` for any channel that cannot be parsed.
200
+ */
201
+ function parseHex(color) {
202
+ const int = Number.parseInt(color.replace("#", ""), 16);
203
+ return Number.isNaN(int) ? {
204
+ r: 255,
205
+ g: 255,
206
+ b: 255
207
+ } : {
208
+ r: int >> 16 & 255,
209
+ g: int >> 8 & 255,
210
+ b: int & 255
211
+ };
212
+ }
213
+ /**
214
+ * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
215
+ * for the given hex color.
216
+ */
217
+ function hex(color) {
218
+ const { r, g, b } = parseHex(color);
219
+ return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
220
+ }
221
+ function gradient(colorStops, text) {
222
+ const chars = text.split("");
223
+ return chars.map((char, i) => {
224
+ const t = chars.length <= 1 ? 0 : i / (chars.length - 1);
225
+ const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);
226
+ const lt = t * (colorStops.length - 1) - seg;
227
+ const from = parseHex(colorStops[seg]);
228
+ const to = parseHex(colorStops[seg + 1]);
229
+ return `\x1b[38;2;${Math.round(from.r + (to.r - from.r) * lt)};${Math.round(from.g + (to.g - from.g) * lt)};${Math.round(from.b + (to.b - from.b) * lt)}m${char}\x1b[0m`;
230
+ }).join("");
231
+ }
232
+ /**
233
+ * ANSI color functions for each part of the Kubb mascot illustration.
234
+ */
235
+ const palette = {
236
+ /**
237
+ * Top cap of the skittle.
238
+ */
239
+ lid: hex("#F55A17"),
240
+ /**
241
+ * Upper wood body.
242
+ */
243
+ woodTop: hex("#F5A217"),
244
+ /**
245
+ * Middle wood body.
246
+ */
247
+ woodMid: hex("#F58517"),
248
+ /**
249
+ * Base wood body.
250
+ */
251
+ woodBase: hex("#B45309"),
252
+ /**
253
+ * Eye whites.
254
+ */
255
+ eye: hex("#FFFFFF"),
256
+ /**
257
+ * Highlight accent.
258
+ */
259
+ highlight: hex("#adadc6"),
260
+ /**
261
+ * Cheek blush.
262
+ */
263
+ blush: hex("#FDA4AF")
264
+ };
265
+ /**
266
+ * Generates the Kubb mascot welcome banner as an ANSI-colored string.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))
271
+ * ```
272
+ */
273
+ function getIntro({ title, description, version, areEyesOpen }) {
274
+ const kubbVersion = gradient([
275
+ "#F58517",
276
+ "#F5A217",
277
+ "#F55A17"
278
+ ], `KUBB v${version}`);
279
+ const eyeTop = areEyesOpen ? palette.eye("█▀█") : palette.eye("───");
280
+ const eyeBottom = areEyesOpen ? palette.eye("▀▀▀") : palette.eye("───");
281
+ return `
282
+ ${palette.lid("▄▄▄▄▄▄▄▄▄▄▄▄▄")}
283
+ ${palette.woodTop("█ ")}${palette.highlight("▄▄")}${palette.woodTop(" ")}${palette.highlight("▄▄")}${palette.woodTop(" █")} ${kubbVersion}
284
+ ${palette.woodMid("█ ")}${eyeTop}${palette.woodMid(" ")}${eyeTop}${palette.woodMid(" █")} ${(0, node_util.styleText)("gray", title)}
285
+ ${palette.woodMid("█ ")}${eyeBottom}${palette.woodMid(" ")}${palette.blush("◡")}${palette.woodMid(" ")}${eyeBottom}${palette.woodMid(" █")} ${(0, node_util.styleText)("yellow", "➜")} ${(0, node_util.styleText)("white", description)}
286
+ ${palette.woodBase("▀▀▀▀▀▀▀▀▀▀▀▀▀")}
287
+ `;
288
+ }
289
+ /**
290
+ * Formats a millisecond duration with a threshold-based ANSI color.
291
+ * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * formatMsWithColor(200) // '\x1b[32m200ms\x1b[39m'
296
+ * formatMsWithColor(800) // '\x1b[33m800ms\x1b[39m'
297
+ * formatMsWithColor(1500) // '\x1b[31m1.50s\x1b[39m'
298
+ * ```
299
+ */
300
+ function formatMsWithColor(ms) {
301
+ const formatted = formatMs(ms);
302
+ if (ms <= 500) return (0, node_util.styleText)("green", formatted);
303
+ if (ms <= 1e3) return (0, node_util.styleText)("yellow", formatted);
304
+ return (0, node_util.styleText)("red", formatted);
305
+ }
306
+ //#endregion
307
+ //#region ../../internals/utils/src/env.ts
308
+ /**
309
+ * Returns `true` when the process is running in a CI environment.
310
+ * Covers GitHub Actions, GitLab CI, CircleCI, Travis CI, Jenkins, Bitbucket,
311
+ * TeamCity, Buildkite, and Azure Pipelines.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * if (isCIEnvironment()) {
316
+ * logger.level = 'error'
317
+ * }
318
+ * ```
319
+ */
320
+ function isCIEnvironment() {
321
+ return !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.BITBUCKET_BUILD_NUMBER || process.env.JENKINS_URL || process.env.CIRCLECI || process.env.TRAVIS || process.env.TEAMCITY_VERSION || process.env.BUILDKITE || process.env.TF_BUILD);
322
+ }
323
+ /**
324
+ * Returns `true` when the process has an interactive TTY with a valid terminal
325
+ * width and is not running in CI.
326
+ *
327
+ * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,
328
+ * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`
329
+ * with a negative count and throw a `RangeError`). We therefore require a
330
+ * positive column count before declaring the TTY usable.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * if (canUseTTY()) {
335
+ * renderProgressBar()
336
+ * }
337
+ * ```
338
+ */
339
+ function canUseTTY() {
340
+ return !!process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment();
341
+ }
342
+ //#endregion
343
+ //#region ../../internals/utils/src/formatters.ts
344
+ /**
345
+ * CLI command descriptors for each supported code formatter.
346
+ *
347
+ * Each entry contains the executable `command`, an `args` factory that maps an
348
+ * output path to the correct argument list, and an `errorMessage` shown when
349
+ * the formatter is not found.
350
+ */
351
+ const formatters = {
352
+ prettier: {
353
+ command: "prettier",
354
+ args: (outputPath) => [
355
+ "--ignore-unknown",
356
+ "--write",
357
+ outputPath
358
+ ],
359
+ errorMessage: "Prettier not found"
360
+ },
361
+ biome: {
362
+ command: "biome",
363
+ args: (outputPath) => [
364
+ "format",
365
+ "--write",
366
+ outputPath
367
+ ],
368
+ errorMessage: "Biome not found"
369
+ },
370
+ oxfmt: {
371
+ command: "oxfmt",
372
+ args: (outputPath) => [outputPath],
373
+ errorMessage: "Oxfmt not found"
374
+ }
375
+ };
376
+ async function isFormatterAvailable(formatter) {
377
+ return new Promise((resolve) => {
378
+ const child = (0, node_child_process.spawn)(formatter, ["--version"], { stdio: "ignore" });
379
+ child.on("close", (code) => resolve(code === 0));
380
+ child.on("error", () => resolve(false));
381
+ });
382
+ }
383
+ /**
384
+ * Detects the first available code formatter on the current system.
385
+ *
386
+ * - Checks in preference order: `oxfmt`, `biome`, `prettier`.
387
+ * - Returns `null` when none are found.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * const formatter = await detectFormatter()
392
+ * if (formatter) {
393
+ * console.log(`Using ${formatter} for formatting`)
394
+ * }
395
+ * ```
396
+ */
397
+ async function detectFormatter() {
398
+ const formatterNames = new Set([
399
+ "oxfmt",
400
+ "biome",
401
+ "prettier"
402
+ ]);
403
+ for (const formatter of formatterNames) if (await isFormatterAvailable(formatter)) return formatter;
404
+ return null;
405
+ }
406
+ //#endregion
407
+ //#region ../../internals/utils/src/linters.ts
408
+ /**
409
+ * CLI command descriptors for each supported linter.
410
+ *
411
+ * Each entry contains the executable `command`, an `args` factory that maps an
412
+ * output path to the correct argument list, and an `errorMessage` shown when
413
+ * the linter is not found.
414
+ */
415
+ const linters = {
416
+ eslint: {
417
+ command: "eslint",
418
+ args: (outputPath) => [outputPath, "--fix"],
419
+ errorMessage: "Eslint not found"
420
+ },
421
+ biome: {
422
+ command: "biome",
423
+ args: (outputPath) => [
424
+ "lint",
425
+ "--fix",
426
+ outputPath
427
+ ],
428
+ errorMessage: "Biome not found"
429
+ },
430
+ oxlint: {
431
+ command: "oxlint",
432
+ args: (outputPath) => [
433
+ "--fix",
434
+ "--no-ignore",
435
+ outputPath
436
+ ],
437
+ errorMessage: "Oxlint not found"
438
+ }
439
+ };
440
+ async function isLinterAvailable(linter) {
441
+ return new Promise((resolve) => {
442
+ const child = (0, node_child_process.spawn)(linter, ["--version"], { stdio: "ignore" });
443
+ child.on("close", (code) => resolve(code === 0));
444
+ child.on("error", () => resolve(false));
445
+ });
446
+ }
447
+ /**
448
+ * Detects the first available linter on the current system.
449
+ *
450
+ * - Checks in preference order: `oxlint`, `biome`, `eslint`.
451
+ * - Returns `null` when none are found.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const linter = await detectLinter()
456
+ * if (linter) {
457
+ * console.log(`Using ${linter} for linting`)
458
+ * }
459
+ * ```
460
+ */
461
+ async function detectLinter() {
462
+ const linterNames = new Set([
463
+ "oxlint",
464
+ "biome",
465
+ "eslint"
466
+ ]);
467
+ for (const linter of linterNames) if (await isLinterAvailable(linter)) return linter;
468
+ return null;
469
+ }
470
+ //#endregion
471
+ //#region ../../internals/utils/src/network.ts
472
+ /**
473
+ * Well-known stable domains used as DNS probes to check internet connectivity.
474
+ */
475
+ const TEST_DOMAINS = [
476
+ "dns.google.com",
477
+ "cloudflare.com",
478
+ "one.one.one.one"
479
+ ];
480
+ /**
481
+ * Returns `true` when the system has internet connectivity.
482
+ * Probes DNS resolution against well-known stable domains.
483
+ *
484
+ * @example
485
+ * ```ts
486
+ * if (await isOnline()) {
487
+ * await fetchLatestVersion()
488
+ * }
489
+ * ```
490
+ */
491
+ async function isOnline() {
492
+ for (const domain of TEST_DOMAINS) try {
493
+ await node_dns.promises.resolve(domain);
494
+ return true;
495
+ } catch {}
496
+ return false;
497
+ }
498
+ /**
499
+ * Executes `fn` only when the system is online. Returns `null` when offline or on error.
500
+ *
501
+ * @example
502
+ * ```ts
503
+ * const version = await executeIfOnline(() => fetchLatestVersion('kubb'))
504
+ * // null when offline
505
+ * ```
506
+ */
507
+ async function executeIfOnline(fn) {
508
+ if (!await isOnline()) return null;
509
+ try {
510
+ return await fn();
511
+ } catch {
512
+ return null;
513
+ }
514
+ }
515
+ //#endregion
516
+ //#region src/loggers/clackLogger.ts
517
+ /**
518
+ * TTY logger with beautiful UI and progress indicators for local development.
519
+ */
520
+ const clackLogger = (0, _kubb_core.defineLogger)({
521
+ name: "clack",
522
+ install(context, options) {
523
+ const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
524
+ const state = {
525
+ ...createProgressCounters(),
526
+ spinner: _clack_prompts.spinner(),
527
+ isSpinning: false,
528
+ runningPlugins: /* @__PURE__ */ new Set(),
529
+ activeProgress: /* @__PURE__ */ new Map(),
530
+ activeHookLogs: /* @__PURE__ */ new Map()
531
+ };
532
+ function stopActiveProgress() {
533
+ for (const [, active] of state.activeProgress) {
534
+ if (active.interval) clearInterval(active.interval);
535
+ active.progressBar?.stop();
536
+ }
537
+ state.activeProgress.clear();
538
+ }
539
+ function reset() {
540
+ stopActiveProgress();
541
+ resetProgressCounters(state);
542
+ state.spinner = _clack_prompts.spinner();
543
+ state.isSpinning = false;
544
+ state.runningPlugins.clear();
545
+ state.activeHookLogs.clear();
546
+ }
547
+ function pluginProgressText() {
548
+ const running = [...state.runningPlugins].map((name) => (0, node_util.styleText)("bold", name));
549
+ return getMessage(running.length > 0 ? `Generating ${running.join(", ")}` : "Generating plugins");
550
+ }
551
+ function showProgressStep() {
552
+ if (logLevel <= _kubb_core.logLevel.silent) return;
553
+ const line = buildProgressLine(state);
554
+ if (line) _clack_prompts.log.step(getMessage(line));
555
+ }
556
+ function getMessage(message) {
557
+ return formatMessage(message, logLevel);
558
+ }
559
+ function onStep(event, message) {
560
+ context.on(event, () => {
561
+ if (logLevel <= _kubb_core.logLevel.silent) return;
562
+ _clack_prompts.log.step(getMessage(message));
563
+ });
564
+ }
565
+ function startSpinner(text) {
566
+ state.spinner.start(text);
567
+ state.isSpinning = true;
568
+ }
569
+ function stopSpinner(text) {
570
+ if (!state.isSpinning) return;
571
+ state.spinner.stop(text);
572
+ state.isSpinning = false;
573
+ }
574
+ context.on("kubb:info", ({ message, info = "" }) => {
575
+ if (logLevel <= _kubb_core.logLevel.silent) return;
576
+ const text = getMessage([
577
+ (0, node_util.styleText)("blue", "ℹ"),
578
+ message,
579
+ info ? (0, node_util.styleText)("dim", info) : void 0
580
+ ].filter(Boolean).join(" "));
581
+ if (state.isSpinning) {
582
+ state.spinner.message(text);
583
+ return;
584
+ }
585
+ _clack_prompts.log.info(text);
586
+ });
587
+ context.on("kubb:success", ({ message, info = "" }) => {
588
+ if (logLevel <= _kubb_core.logLevel.silent) return;
589
+ const text = getMessage([
590
+ (0, node_util.styleText)("blue", "✓"),
591
+ message,
592
+ logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", info) : void 0
593
+ ].filter(Boolean).join(" "));
594
+ if (state.isSpinning) {
595
+ stopSpinner(text);
596
+ return;
597
+ }
598
+ _clack_prompts.log.success(text);
599
+ });
600
+ context.on("kubb:warn", ({ message, info }) => {
601
+ if (logLevel < _kubb_core.logLevel.warn) return;
602
+ const text = getMessage([
603
+ (0, node_util.styleText)("yellow", "⚠"),
604
+ message,
605
+ logLevel >= _kubb_core.logLevel.info && info ? (0, node_util.styleText)("dim", info) : void 0
606
+ ].filter(Boolean).join(" "));
607
+ _clack_prompts.log.warn(text);
608
+ });
609
+ context.on("kubb:error", ({ error }) => {
610
+ const caused = require_errors.toCause(error);
611
+ const text = [(0, node_util.styleText)("red", "✗"), error.message].join(" ");
612
+ if (state.isSpinning) {
613
+ stopSpinner(getMessage(text));
614
+ return;
615
+ }
616
+ _clack_prompts.log.error(getMessage(text));
617
+ if (logLevel >= _kubb_core.logLevel.verbose && error.stack) {
618
+ const frames = error.stack.split("\n").slice(1, 4);
619
+ for (const frame of frames) _clack_prompts.log.message(getMessage((0, node_util.styleText)("dim", frame.trim())));
620
+ if (caused?.stack) {
621
+ _clack_prompts.log.message((0, node_util.styleText)("dim", `└─ caused by ${caused.message}`));
622
+ const frames = caused.stack.split("\n").slice(1, 4);
623
+ for (const frame of frames) _clack_prompts.log.message(getMessage(` ${(0, node_util.styleText)("dim", frame.trim())}`));
624
+ }
625
+ }
626
+ });
627
+ context.on("kubb:diagnostic", ({ diagnostic }) => {
628
+ if (logLevel <= _kubb_core.logLevel.silent && diagnostic.severity !== "error") return;
629
+ stopSpinner();
630
+ stopActiveProgress();
631
+ if (_kubb_core.Diagnostics.isUpdate(diagnostic)) {
632
+ _clack_prompts.box(`\`v${diagnostic.currentVersion}\` → \`v${diagnostic.latestVersion}\`
633
+ Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
634
+ width: "auto",
635
+ formatBorder: (s) => (0, node_util.styleText)("yellow", s),
636
+ rounded: true,
637
+ withGuide: false,
638
+ contentAlign: "center",
639
+ titleAlign: "center"
640
+ });
641
+ return;
642
+ }
643
+ const { symbol, headline, details } = _kubb_core.Diagnostics.format(diagnostic);
644
+ _clack_prompts.log.message([headline, ...details], { symbol });
645
+ });
646
+ context.on("kubb:lifecycle:start", async ({ version }) => {
647
+ console.log(`\n${getIntro({
648
+ title: "The meta framework for code generation",
649
+ description: "Ready to start",
650
+ version,
651
+ areEyesOpen: true
652
+ })}\n`);
653
+ reset();
654
+ });
655
+ context.on("kubb:config:start", () => {
656
+ if (logLevel <= _kubb_core.logLevel.silent) return;
657
+ const text = getMessage("Configuration started");
658
+ _clack_prompts.intro(text);
659
+ startSpinner(getMessage("Configuration loading"));
660
+ });
661
+ context.on("kubb:config:end", () => {
662
+ if (logLevel <= _kubb_core.logLevel.silent) return;
663
+ const text = getMessage("Configuration completed");
664
+ _clack_prompts.outro(text);
665
+ });
666
+ context.on("kubb:generation:start", ({ config }) => {
667
+ reset();
668
+ state.totalPlugins = config.plugins?.length ?? 0;
669
+ if (logLevel <= _kubb_core.logLevel.silent) return;
670
+ const text = getMessage(["Generation started", config.name ? `for ${(0, node_util.styleText)("dim", config.name)}` : void 0].filter(Boolean).join(" "));
671
+ _clack_prompts.intro(text);
672
+ });
673
+ context.on("kubb:plugin:start", ({ plugin }) => {
674
+ if (logLevel <= _kubb_core.logLevel.silent) return;
675
+ stopSpinner();
676
+ state.runningPlugins.add(plugin.name);
677
+ const active = state.activeProgress.get("plugins");
678
+ if (active) {
679
+ active.progressBar.advance(0, pluginProgressText());
680
+ return;
681
+ }
682
+ const progressBar = _clack_prompts.progress({
683
+ style: "block",
684
+ max: Math.max(state.totalPlugins, 1),
685
+ size: 30
686
+ });
687
+ progressBar.start(pluginProgressText());
688
+ progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText());
689
+ state.activeProgress.set("plugins", { progressBar });
690
+ });
691
+ context.on("kubb:plugin:end", ({ plugin, success }) => {
692
+ stopSpinner();
693
+ const active = state.activeProgress.get("plugins");
694
+ if (!active || logLevel === _kubb_core.logLevel.silent) return;
695
+ state.runningPlugins.delete(plugin.name);
696
+ recordPluginResult(state, success);
697
+ active.progressBar.advance(1, pluginProgressText());
698
+ if (state.runningPlugins.size === 0) {
699
+ active.progressBar.stop(getMessage("Plugins generated"));
700
+ state.activeProgress.delete("plugins");
701
+ showProgressStep();
702
+ }
703
+ });
704
+ context.on("kubb:files:processing:start", ({ files }) => {
705
+ if (logLevel <= _kubb_core.logLevel.silent) return;
706
+ stopSpinner();
707
+ state.totalFiles = files.length;
708
+ state.processedFiles = 0;
709
+ const text = `Writing ${files.length} files`;
710
+ const progressBar = _clack_prompts.progress({
711
+ style: "block",
712
+ max: files.length,
713
+ size: 30
714
+ });
715
+ context.emit("kubb:info", { message: text });
716
+ progressBar.start(getMessage(text));
717
+ state.activeProgress.set("files", { progressBar });
718
+ });
719
+ context.on("kubb:files:processing:update", ({ files }) => {
720
+ if (logLevel <= _kubb_core.logLevel.silent) return;
721
+ stopSpinner();
722
+ const active = state.activeProgress.get("files");
723
+ for (const { file, config } of files) {
724
+ state.processedFiles++;
725
+ if (active) active.progressBar.advance(void 0, `Writing ${(0, node_path.relative)(config.root, file.path)}`);
726
+ }
727
+ });
728
+ context.on("kubb:files:processing:end", () => {
729
+ if (logLevel <= _kubb_core.logLevel.silent) return;
730
+ stopSpinner();
731
+ const text = getMessage("Files written successfully");
732
+ const active = state.activeProgress.get("files");
733
+ if (!active) return;
734
+ active.progressBar.stop(text);
735
+ state.activeProgress.delete("files");
736
+ showProgressStep();
737
+ });
738
+ context.on("kubb:generation:end", ({ config }) => {
739
+ stopSpinner();
740
+ const text = getMessage(config.name ? `Generation completed for ${(0, node_util.styleText)("dim", config.name)}` : "Generation completed");
741
+ _clack_prompts.outro(text);
742
+ });
743
+ onStep("kubb:format:start", "Formatting");
744
+ onStep("kubb:lint:start", "Linting");
745
+ onStep("kubb:hooks:start", "Running hooks");
746
+ context.on("kubb:hook:start", ({ id, command, args }) => {
747
+ if (logLevel <= _kubb_core.logLevel.silent || !id) return;
748
+ stopSpinner();
749
+ const title = getMessage(`Running ${(0, node_util.styleText)("dim", formatCommandWithArgs(command, args))}`);
750
+ const taskLog = _clack_prompts.taskLog({ title });
751
+ state.activeHookLogs.set(id, {
752
+ taskLog,
753
+ hrStart: node_process.default.hrtime()
754
+ });
755
+ });
756
+ if (logLevel > _kubb_core.logLevel.silent) context.on("kubb:hook:line", ({ id, line }) => {
757
+ state.activeHookLogs.get(id)?.taskLog.message((0, node_util.styleText)("dim", line));
758
+ });
759
+ context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
760
+ if (!id) return;
761
+ if (logLevel <= _kubb_core.logLevel.silent) {
762
+ if (!success) {
763
+ if (stdout) console.log(stdout);
764
+ if (stderr) console.error(stderr);
765
+ }
766
+ return;
767
+ }
768
+ const active = state.activeHookLogs.get(id);
769
+ if (!active) return;
770
+ state.activeHookLogs.delete(id);
771
+ const commandWithArgs = formatCommandWithArgs(command, args);
772
+ const duration = formatMsWithColor(getElapsedMs(active.hrStart));
773
+ if (success) active.taskLog.success(getMessage(`${(0, node_util.styleText)("dim", commandWithArgs)} completed in ${duration}`));
774
+ else {
775
+ const reason = error?.message ? ` (${error.message})` : "";
776
+ active.taskLog.error(getMessage(`${(0, node_util.styleText)("dim", commandWithArgs)} failed${reason}`), { showLog: true });
777
+ }
778
+ });
779
+ context.on("kubb:lifecycle:end", () => {
780
+ reset();
781
+ });
782
+ }
783
+ });
784
+ //#endregion
785
+ //#region src/loggers/plainLogger.ts
786
+ /**
787
+ * Plain console adapter for non-TTY environments with simple `console.log` output.
788
+ */
789
+ const plainLogger = (0, _kubb_core.defineLogger)({
790
+ name: "plain",
791
+ install(context, options) {
792
+ const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
793
+ const hookTimer = createHookTimer();
794
+ function getMessage(message) {
795
+ return formatMessage(message, logLevel);
796
+ }
797
+ function onStep(event, message) {
798
+ context.on(event, () => {
799
+ if (logLevel <= _kubb_core.logLevel.silent) return;
800
+ console.log(getMessage(message));
801
+ });
802
+ }
803
+ context.on("kubb:info", ({ message, info }) => {
804
+ if (logLevel <= _kubb_core.logLevel.silent) return;
805
+ const text = getMessage([
806
+ "ℹ",
807
+ message,
808
+ info
809
+ ].join(" "));
810
+ console.log(text);
811
+ });
812
+ context.on("kubb:success", ({ message, info = "" }) => {
813
+ if (logLevel <= _kubb_core.logLevel.silent) return;
814
+ const text = getMessage([
815
+ "✓",
816
+ message,
817
+ logLevel >= _kubb_core.logLevel.info ? info : void 0
818
+ ].filter(Boolean).join(" "));
819
+ console.log(text);
820
+ });
821
+ context.on("kubb:warn", ({ message, info }) => {
822
+ if (logLevel < _kubb_core.logLevel.warn) return;
823
+ const text = getMessage([
824
+ "⚠",
825
+ message,
826
+ logLevel >= _kubb_core.logLevel.info ? info : void 0
827
+ ].filter(Boolean).join(" "));
828
+ console.log(text);
829
+ });
830
+ context.on("kubb:error", ({ error }) => {
831
+ const caused = require_errors.toCause(error);
832
+ const text = getMessage(["✗", error.message].join(" "));
833
+ console.log(text);
834
+ if (logLevel >= _kubb_core.logLevel.verbose && error.stack) {
835
+ const frames = error.stack.split("\n").slice(1, 4);
836
+ for (const frame of frames) console.log(getMessage(frame.trim()));
837
+ if (caused?.stack) {
838
+ console.log(`└─ caused by ${caused.message}`);
839
+ const frames = caused.stack.split("\n").slice(1, 4);
840
+ for (const frame of frames) console.log(getMessage(` ${frame.trim()}`));
841
+ }
842
+ }
843
+ });
844
+ context.on("kubb:diagnostic", ({ diagnostic }) => {
845
+ if (logLevel <= _kubb_core.logLevel.silent && diagnostic.severity !== "error") return;
846
+ console.log(getMessage(_kubb_core.Diagnostics.formatLines(diagnostic).join("\n")));
847
+ });
848
+ context.on("kubb:lifecycle:start", ({ version }) => {
849
+ console.log(`Kubb CLI v${version}`);
850
+ });
851
+ onStep("kubb:config:start", "Configuration started");
852
+ onStep("kubb:config:end", "Configuration completed");
853
+ context.on("kubb:generation:start", () => {
854
+ const text = getMessage("Generation started");
855
+ console.log(text);
856
+ });
857
+ context.on("kubb:plugin:start", ({ plugin }) => {
858
+ if (logLevel <= _kubb_core.logLevel.silent) return;
859
+ const text = getMessage(`Generating ${plugin.name}`);
860
+ console.log(text);
861
+ });
862
+ context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
863
+ if (logLevel <= _kubb_core.logLevel.silent) return;
864
+ const durationStr = formatMs(duration);
865
+ const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
866
+ console.log(text);
867
+ });
868
+ context.on("kubb:files:processing:start", ({ files }) => {
869
+ if (logLevel <= _kubb_core.logLevel.silent) return;
870
+ const text = getMessage(`Writing ${files.length} files`);
871
+ console.log(text);
872
+ });
873
+ context.on("kubb:files:processing:update", ({ files }) => {
874
+ if (logLevel <= _kubb_core.logLevel.silent) return;
875
+ for (const { file, config } of files) console.log(getMessage(`Writing ${(0, node_path.relative)(config.root, file.path)}`));
876
+ });
877
+ context.on("kubb:files:processing:end", () => {
878
+ if (logLevel <= _kubb_core.logLevel.silent) return;
879
+ const text = getMessage("Files written successfully");
880
+ console.log(text);
881
+ });
882
+ context.on("kubb:generation:end", ({ config }) => {
883
+ const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
884
+ console.log(text);
885
+ });
886
+ onStep("kubb:format:start", "Format started");
887
+ onStep("kubb:format:end", "Format completed");
888
+ onStep("kubb:lint:start", "Lint started");
889
+ onStep("kubb:lint:end", "Lint completed");
890
+ onStep("kubb:hooks:start", "Hooks started");
891
+ onStep("kubb:hooks:end", "Hooks completed");
892
+ context.on("kubb:hook:start", ({ id, command, args }) => {
893
+ if (logLevel <= _kubb_core.logLevel.silent) return;
894
+ if (id) hookTimer.start(id);
895
+ const commandWithArgs = formatCommandWithArgs(command, args);
896
+ console.log(getMessage(`Hook ${commandWithArgs} started`));
897
+ });
898
+ context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
899
+ if (logLevel <= _kubb_core.logLevel.silent) return;
900
+ const ms = id ? hookTimer.end(id) : void 0;
901
+ const durationStr = ms !== void 0 ? ` in ${formatMs(ms)}` : "";
902
+ const commandWithArgs = formatCommandWithArgs(command, args);
903
+ if (success) console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`));
904
+ else {
905
+ if (stdout) console.log(stdout);
906
+ if (stderr) console.error(stderr);
907
+ const reason = error?.message ? ` (${error.message})` : "";
908
+ console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`));
909
+ }
910
+ });
911
+ }
912
+ });
913
+ //#endregion
914
+ //#region src/loggers/utils.ts
915
+ /**
916
+ * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
917
+ * Shared across all logger adapters to avoid duplication.
918
+ */
919
+ function formatMessage(message, logLevel) {
920
+ if (logLevel >= _kubb_core.logLevel.verbose) return `${(0, node_util.styleText)("dim", `[${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
921
+ hour12: false,
922
+ hour: "2-digit",
923
+ minute: "2-digit",
924
+ second: "2-digit"
925
+ })}]`)} ${message}`;
926
+ return message;
927
+ }
928
+ /**
929
+ * Build the progress summary line shown by the clack logger.
930
+ * Returns null when there is nothing to display.
931
+ */
932
+ function buildProgressLine(state) {
933
+ const parts = [];
934
+ const duration = formatHrtime(state.hrStart);
935
+ if (state.totalPlugins > 0) {
936
+ const pluginStr = state.failedPlugins > 0 ? `Plugins ${(0, node_util.styleText)("green", state.completedPlugins.toString())}/${state.totalPlugins} ${(0, node_util.styleText)("red", `(${state.failedPlugins} failed)`)}` : `Plugins ${(0, node_util.styleText)("green", state.completedPlugins.toString())}/${state.totalPlugins}`;
937
+ parts.push(pluginStr);
938
+ }
939
+ if (state.totalFiles > 0) parts.push(`Files ${(0, node_util.styleText)("green", state.processedFiles.toString())}/${state.totalFiles}`);
940
+ if (parts.length === 0) return null;
941
+ parts.push(`${(0, node_util.styleText)("green", duration)} elapsed`);
942
+ return parts.join((0, node_util.styleText)("dim", " | "));
943
+ }
944
+ /**
945
+ * Creates the per-run progress counters used by the clack logger.
946
+ */
947
+ function createProgressCounters() {
948
+ return {
949
+ totalPlugins: 0,
950
+ completedPlugins: 0,
951
+ failedPlugins: 0,
952
+ totalFiles: 0,
953
+ processedFiles: 0,
954
+ hrStart: node_process.default.hrtime()
955
+ };
956
+ }
957
+ /**
958
+ * Resets the progress counters in place at the start/end of a generation run.
959
+ */
960
+ function resetProgressCounters(state) {
961
+ state.totalPlugins = 0;
962
+ state.completedPlugins = 0;
963
+ state.failedPlugins = 0;
964
+ state.totalFiles = 0;
965
+ state.processedFiles = 0;
966
+ state.hrStart = node_process.default.hrtime();
967
+ }
968
+ /**
969
+ * Records a finished plugin against the progress counters.
970
+ */
971
+ function recordPluginResult(state, success) {
972
+ if (success) state.completedPlugins++;
973
+ else state.failedPlugins++;
974
+ }
975
+ /**
976
+ * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
977
+ */
978
+ function createHookTimer() {
979
+ const starts = /* @__PURE__ */ new Map();
980
+ return {
981
+ start(id) {
982
+ starts.set(id, node_process.default.hrtime());
983
+ },
984
+ end(id) {
985
+ const hrStart = starts.get(id);
986
+ if (!hrStart) return;
987
+ starts.delete(id);
988
+ return getElapsedMs(hrStart);
989
+ },
990
+ clear() {
991
+ starts.clear();
992
+ }
993
+ };
994
+ }
995
+ /**
996
+ * Join a command and its optional args into a single display string.
997
+ * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
998
+ */
999
+ function formatCommandWithArgs(command, args) {
1000
+ return args?.length ? `${command} ${args.join(" ")}` : command;
1001
+ }
1002
+ function detectLogger() {
1003
+ if (canUseTTY()) return "clack";
1004
+ return "plain";
1005
+ }
1006
+ const logMapper = {
1007
+ clack: clackLogger,
1008
+ plain: plainLogger
1009
+ };
1010
+ /**
1011
+ * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
1012
+ * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
1013
+ */
1014
+ function installReporter(context, reporter, ctx) {
1015
+ context.on("kubb:generation:end", async ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = node_process.default.hrtime() }) => {
1016
+ await reporter.report({
1017
+ config,
1018
+ diagnostics,
1019
+ filesCreated,
1020
+ status,
1021
+ hrStart
1022
+ }, ctx);
1023
+ });
1024
+ if (reporter.drain) context.on("kubb:lifecycle:end", () => reporter.drain?.(ctx));
1025
+ }
1026
+ /**
1027
+ * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
1028
+ * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`); this
1029
+ * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
1030
+ * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
1031
+ *
1032
+ * Loggers and reporters are independent: the `cli` reporter also activates the env logger summary.
1033
+ * The `json` reporter owns stdout, so the live logger and the `cli` summary are suppressed whenever
1034
+ * `json` is among the reporters, even if `cli` is also listed.
1035
+ */
1036
+ async function setupReporters(context, { logLevel, reporters }) {
1037
+ const hasJson = reporters.some((reporter) => reporter.name === "json");
1038
+ const ctx = { logLevel };
1039
+ for (const reporter of reporters) {
1040
+ if (reporter.name === "cli") {
1041
+ if (hasJson) continue;
1042
+ const type = detectLogger();
1043
+ const logger = logMapper[type];
1044
+ if (!logger) throw new Error(`Unknown adapter type: ${type}`);
1045
+ await logger.install(context, { logLevel });
1046
+ }
1047
+ installReporter(context, reporter, ctx);
1048
+ }
1049
+ }
1050
+ //#endregion
1051
+ //#region src/runners/generate/utils.ts
1052
+ const jiti$1 = (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
1053
+ jsx: {
1054
+ runtime: "automatic",
1055
+ importSource: "@kubb/renderer-jsx"
1056
+ },
1057
+ moduleCache: false
1058
+ });
1059
+ const tsLoader = (configFile) => jiti$1.import(configFile, { default: true });
1060
+ const MODULE_NAME = "kubb";
1061
+ const BASE_SEARCH_PLACES = [
1062
+ "package.json",
1063
+ `.${MODULE_NAME}rc`,
1064
+ `.${MODULE_NAME}rc.json`,
1065
+ `.${MODULE_NAME}rc.yaml`,
1066
+ `.${MODULE_NAME}rc.yml`,
1067
+ `.${MODULE_NAME}rc.ts`,
1068
+ `.${MODULE_NAME}rc.mts`,
1069
+ `.${MODULE_NAME}rc.cts`,
1070
+ `.${MODULE_NAME}rc.js`,
1071
+ `.${MODULE_NAME}rc.mjs`,
1072
+ `.${MODULE_NAME}rc.cjs`,
1073
+ `${MODULE_NAME}.config.ts`,
1074
+ `${MODULE_NAME}.config.mts`,
1075
+ `${MODULE_NAME}.config.cts`,
1076
+ `${MODULE_NAME}.config.js`,
1077
+ `${MODULE_NAME}.config.mjs`,
1078
+ `${MODULE_NAME}.config.cjs`
1079
+ ];
1080
+ const SEARCH_PLACES = [
1081
+ "",
1082
+ ".config/",
1083
+ "configs/"
1084
+ ].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`));
1085
+ async function getCosmiConfig(configFile) {
1086
+ const explorer = (0, cosmiconfig.cosmiconfig)(MODULE_NAME, {
1087
+ cache: false,
1088
+ searchPlaces: SEARCH_PLACES,
1089
+ loaders: {
1090
+ ".ts": tsLoader,
1091
+ ".mts": tsLoader,
1092
+ ".cts": tsLoader
1093
+ }
1094
+ });
1095
+ let result;
1096
+ try {
1097
+ result = configFile ? await explorer.load(configFile) : await explorer.search();
1098
+ } catch (error) {
1099
+ throw new Error("Config failed loading", { cause: error });
1100
+ }
1101
+ if (!result?.config || result.isEmpty) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
1102
+ return result;
1103
+ }
1104
+ /**
1105
+ * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
1106
+ * Every config in the result is guaranteed to have a `plugins` array.
1107
+ */
1108
+ async function getConfigs({ configPath, input, watch, logLevel, noCache }) {
1109
+ const result = await getCosmiConfig(configPath);
1110
+ const cli = {
1111
+ config: configPath,
1112
+ input,
1113
+ watch,
1114
+ logLevel,
1115
+ noCache
1116
+ };
1117
+ const resolved = await (typeof result.config === "function" ? result.config(cli) : result.config);
1118
+ const userConfigs = Array.isArray(resolved) ? resolved : [resolved];
1119
+ return {
1120
+ configPath: result.filepath,
1121
+ configs: userConfigs.map((item) => {
1122
+ const config = {
1123
+ ...item,
1124
+ plugins: item.plugins ?? []
1125
+ };
1126
+ return noCache ? {
1127
+ ...config,
1128
+ cache: void 0
1129
+ } : config;
1130
+ })
1131
+ };
1132
+ }
1133
+ /**
1134
+ * Runs the `done` hooks defined in a Kubb config in sequence.
1135
+ */
1136
+ async function executeHooks({ configHooks, hooks }) {
1137
+ const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
1138
+ for (const command of commands) {
1139
+ const [cmd, ...args] = require_shell.tokenize(command);
1140
+ if (!cmd) continue;
1141
+ const hookId = (0, node_crypto.hash)("sha256", command, "hex");
1142
+ const commandWithArgs = [cmd, ...args].join(" ");
1143
+ await hooks.emit("kubb:hook:start", {
1144
+ id: hookId,
1145
+ command: cmd,
1146
+ args
1147
+ });
1148
+ await runHook({
1149
+ id: hookId,
1150
+ command: cmd,
1151
+ args,
1152
+ commandWithArgs,
1153
+ hooks
1154
+ });
1155
+ }
1156
+ }
1157
+ async function runHook({ id, command, args, commandWithArgs, hooks }) {
1158
+ const emitEnd = (success, error, output) => hooks.emit("kubb:hook:end", {
1159
+ command,
1160
+ args,
1161
+ id,
1162
+ success,
1163
+ error,
1164
+ ...output
1165
+ });
1166
+ const stream = hooks.listenerCount("kubb:hook:line") > 0;
1167
+ try {
1168
+ const proc = (0, tinyexec.x)(command, [...args ?? []], {
1169
+ nodeOptions: { detached: process.platform !== "win32" },
1170
+ throwOnError: true
1171
+ });
1172
+ if (stream) for await (const line of proc) await hooks.emit("kubb:hook:line", {
1173
+ id,
1174
+ line
1175
+ });
1176
+ await proc;
1177
+ await hooks.emit("kubb:success", { message: `${(0, node_util.styleText)("dim", commandWithArgs)} successfully executed` });
1178
+ await emitEnd(true, null);
1179
+ } catch (err) {
1180
+ if (!(err instanceof tinyexec.NonZeroExitError)) {
1181
+ await emitEnd(false, require_errors.toError(err));
1182
+ return;
1183
+ }
1184
+ const stderr = err.output?.stderr ?? "";
1185
+ const stdout = err.output?.stdout ?? "";
1186
+ await emitEnd(false, /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`), {
1187
+ stdout,
1188
+ stderr
1189
+ });
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Starts a file watcher on the given paths and calls `cb` on any change.
1194
+ * Ignores `.git` and `node_modules` directories.
1195
+ */
1196
+ async function startWatcher(path, cb, log = {
1197
+ info: console.log,
1198
+ error: console.log
1199
+ }) {
1200
+ const { watch } = await import("chokidar");
1201
+ const watcher = watch(path, {
1202
+ ignorePermissionErrors: true,
1203
+ ignored: require_constants.WATCHER_IGNORED_PATHS
1204
+ });
1205
+ process.once("SIGINT", () => {
1206
+ watcher.close();
1207
+ });
1208
+ process.once("SIGTERM", () => {
1209
+ watcher.close();
1210
+ });
1211
+ watcher.on("all", async (type, file) => {
1212
+ log.info((0, node_util.styleText)("yellow", (0, node_util.styleText)("bold", `Change detected: ${type} ${file}`)));
1213
+ try {
1214
+ await cb(path);
1215
+ } catch (_e) {
1216
+ log.error((0, node_util.styleText)("red", "Watcher failed"));
1217
+ }
1218
+ });
1219
+ }
1220
+ //#endregion
1221
+ //#region src/runners/generate/run.ts
1222
+ /**
1223
+ * Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
1224
+ * avoiding the race where a synchronous emitter fires end before the listener is attached.
1225
+ */
1226
+ function waitForHookEnd(hooks, hookId, onSuccess, fallbackErrorMessage) {
1227
+ return new Promise((resolve, reject) => {
1228
+ const handler = (ctx) => {
1229
+ if (ctx.id !== hookId) return;
1230
+ hooks.off("kubb:hook:end", handler);
1231
+ if (!ctx.success) {
1232
+ reject(ctx.error ?? new Error(fallbackErrorMessage));
1233
+ return;
1234
+ }
1235
+ Promise.resolve(onSuccess()).then(resolve).catch(reject);
1236
+ };
1237
+ hooks.on("kubb:hook:end", handler);
1238
+ });
1239
+ }
1240
+ async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel, hooks, onStart, onEnd }) {
1241
+ await onStart();
1242
+ let resolvedTool = toolValue;
1243
+ if (resolvedTool === "auto") {
1244
+ const detected = await detect();
1245
+ if (!detected) await hooks.emit("kubb:warn", { message: noToolMessage });
1246
+ else {
1247
+ resolvedTool = detected;
1248
+ await hooks.emit("kubb:info", { message: `Auto-detected ${toolLabel}: ${(0, node_util.styleText)("dim", resolvedTool)}` });
1249
+ }
1250
+ }
1251
+ let toolError;
1252
+ if (resolvedTool && resolvedTool !== "auto" && resolvedTool in toolMap && (0, node_fs.existsSync)(outputPath)) {
1253
+ const toolConfig = toolMap[resolvedTool];
1254
+ const hookId = (0, node_crypto.hash)("sha256", [configName, resolvedTool].filter(Boolean).join("-"), "hex");
1255
+ const successMessage = [
1256
+ `${successPrefix} with ${(0, node_util.styleText)("dim", resolvedTool)}`,
1257
+ logLevel >= _kubb_core.logLevel.info ? `on ${(0, node_util.styleText)("dim", outputPath)}` : void 0,
1258
+ "successfully"
1259
+ ].filter(Boolean).join(" ");
1260
+ try {
1261
+ const hookArgs = toolConfig.args(outputPath);
1262
+ const commandWithArgs = [toolConfig.command, ...hookArgs].join(" ");
1263
+ const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit("kubb:success", { message: successMessage }), toolConfig.errorMessage);
1264
+ await hooks.emit("kubb:hook:start", {
1265
+ id: hookId,
1266
+ command: toolConfig.command,
1267
+ args: hookArgs
1268
+ });
1269
+ runHook({
1270
+ id: hookId,
1271
+ command: toolConfig.command,
1272
+ args: hookArgs,
1273
+ commandWithArgs,
1274
+ hooks
1275
+ }).catch(() => {});
1276
+ await hookEndPromise;
1277
+ } catch (caughtError) {
1278
+ toolError = require_errors.toError(caughtError);
1279
+ }
1280
+ }
1281
+ await onEnd();
1282
+ if (toolError) throw toolError;
1283
+ }
1284
+ async function generate(options) {
1285
+ const { input, hooks, logLevel } = options;
1286
+ const hrStart = node_process.default.hrtime();
1287
+ const inputPath = input ?? (options.config.input && "path" in options.config.input ? options.config.input.path : void 0);
1288
+ const config = {
1289
+ ...options.config,
1290
+ input: inputPath ? {
1291
+ ...options.config.input,
1292
+ path: inputPath
1293
+ } : options.config.input,
1294
+ ...options.config.output
1295
+ };
1296
+ const kubb = (0, _kubb_core.createKubb)(config, { hooks });
1297
+ await hooks.emit("kubb:generation:start", { config });
1298
+ await hooks.emit("kubb:info", {
1299
+ message: config.name ? `Setup generation ${(0, node_util.styleText)("bold", config.name)}` : "Setup generation",
1300
+ info: inputPath
1301
+ });
1302
+ await kubb.setup();
1303
+ await hooks.emit("kubb:info", {
1304
+ message: config.name ? `Build generation ${(0, node_util.styleText)("bold", config.name)}` : "Build generation",
1305
+ info: inputPath
1306
+ });
1307
+ const { files, diagnostics, driver } = await kubb.safeBuild();
1308
+ await hooks.emit("kubb:info", { message: "Load summary" });
1309
+ const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({
1310
+ name: p.name,
1311
+ options: p.options
1312
+ }));
1313
+ const reportTelemetry = (status) => _kubb_core.Telemetry.send(_kubb_core.Telemetry.build({
1314
+ command: "generate",
1315
+ kubbVersion: require_package.version,
1316
+ plugins: telemetryPlugins,
1317
+ hrStart,
1318
+ filesCreated: files.length,
1319
+ status
1320
+ }));
1321
+ for (const diagnostic of diagnostics) {
1322
+ if (!_kubb_core.Diagnostics.isProblem(diagnostic)) continue;
1323
+ const unknown = _kubb_core.Diagnostics.narrow(diagnostic, _kubb_core.Diagnostics.code.unknown);
1324
+ if (unknown) await hooks.emit("kubb:error", { error: unknown.cause ?? new Error(unknown.message) });
1325
+ else await _kubb_core.Diagnostics.emit(hooks, diagnostic);
1326
+ }
1327
+ if (_kubb_core.Diagnostics.hasError(diagnostics)) {
1328
+ await hooks.emit("kubb:generation:end", {
1329
+ config,
1330
+ storage: kubb.storage,
1331
+ diagnostics,
1332
+ filesCreated: files.length,
1333
+ status: "failed",
1334
+ hrStart
1335
+ });
1336
+ await reportTelemetry("failed");
1337
+ return false;
1338
+ }
1339
+ const outputPath = node_path.default.resolve(config.root, config.output.path);
1340
+ const outputDiagnostics = [];
1341
+ const toolPasses = [config.output.format && {
1342
+ code: _kubb_core.Diagnostics.code.formatFailed,
1343
+ toolValue: config.output.format,
1344
+ detect: detectFormatter,
1345
+ toolMap: formatters,
1346
+ toolLabel: "formatter",
1347
+ successPrefix: "Formatting",
1348
+ noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting.",
1349
+ onStart: () => hooks.emit("kubb:format:start"),
1350
+ onEnd: () => hooks.emit("kubb:format:end")
1351
+ }, config.output.lint && {
1352
+ code: _kubb_core.Diagnostics.code.lintFailed,
1353
+ toolValue: config.output.lint,
1354
+ detect: detectLinter,
1355
+ toolMap: linters,
1356
+ toolLabel: "linter",
1357
+ successPrefix: "Linting",
1358
+ noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting.",
1359
+ onStart: () => hooks.emit("kubb:lint:start"),
1360
+ onEnd: () => hooks.emit("kubb:lint:end")
1361
+ }].filter(Boolean);
1362
+ for (const { code, ...pass } of toolPasses) try {
1363
+ await runToolPass({
1364
+ ...pass,
1365
+ configName: config.name,
1366
+ outputPath,
1367
+ logLevel,
1368
+ hooks
1369
+ });
1370
+ } catch (caughtError) {
1371
+ const diagnostic = outputDiagnostic(code, pass.toolLabel, caughtError);
1372
+ outputDiagnostics.push(diagnostic);
1373
+ await _kubb_core.Diagnostics.emit(hooks, diagnostic);
1374
+ }
1375
+ if (config.hooks) {
1376
+ await hooks.emit("kubb:hooks:start");
1377
+ const hookFailures = [];
1378
+ const onHookEnd = (ctx) => {
1379
+ if (!ctx.success) hookFailures.push(ctx.error ?? /* @__PURE__ */ new Error("Post-generate hook failed"));
1380
+ };
1381
+ hooks.on("kubb:hook:end", onHookEnd);
1382
+ try {
1383
+ await executeHooks({
1384
+ configHooks: config.hooks,
1385
+ hooks
1386
+ });
1387
+ } finally {
1388
+ hooks.off("kubb:hook:end", onHookEnd);
1389
+ }
1390
+ for (const error of hookFailures) {
1391
+ const diagnostic = outputDiagnostic(_kubb_core.Diagnostics.code.hookFailed, "Post-generate hook", error);
1392
+ outputDiagnostics.push(diagnostic);
1393
+ await _kubb_core.Diagnostics.emit(hooks, diagnostic);
1394
+ }
1395
+ await hooks.emit("kubb:hooks:end");
1396
+ }
1397
+ const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
1398
+ const failed = _kubb_core.Diagnostics.hasError(outputDiagnostics);
1399
+ if (!failed) await hooks.emit("kubb:success", {
1400
+ message: "Generation succeeded",
1401
+ info: inputPath
1402
+ });
1403
+ await hooks.emit("kubb:generation:end", {
1404
+ config,
1405
+ storage: kubb.storage,
1406
+ diagnostics: finalDiagnostics,
1407
+ filesCreated: files.length,
1408
+ status: failed ? "failed" : "success",
1409
+ hrStart
1410
+ });
1411
+ await reportTelemetry(failed ? "failed" : "success");
1412
+ return !failed;
1413
+ }
1414
+ /**
1415
+ * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).
1416
+ */
1417
+ function outputDiagnostic(code, label, caughtError) {
1418
+ const error = require_errors.toError(caughtError);
1419
+ return {
1420
+ code,
1421
+ severity: "error",
1422
+ message: `${label} failed: ${error.message}`,
1423
+ help: "Check that the tool is installed and that the command and its config are correct.",
1424
+ location: { kind: "config" },
1425
+ cause: error
1426
+ };
1427
+ }
1428
+ async function checkForUpdate(hooks) {
1429
+ await executeIfOnline(async () => {
1430
+ try {
1431
+ const data = await (await fetch(require_constants.KUBB_NPM_PACKAGE_URL)).json();
1432
+ if (data.version && require_package.version < data.version) await _kubb_core.Diagnostics.emit(hooks, _kubb_core.Diagnostics.update({
1433
+ currentVersion: require_package.version,
1434
+ latestVersion: data.version
1435
+ }));
1436
+ } catch {}
1437
+ });
1438
+ }
1439
+ /**
1440
+ * Runs the full Kubb generation lifecycle for the given CLI options.
1441
+ * Loads configs, sets up the selected reporters (CLI `--reporter` overrides `config.reporters`),
1442
+ * checks for a newer version, and calls `generate` for each config entry.
1443
+ */
1444
+ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, noCache }) {
1445
+ const logLevel = _kubb_core.logLevel[logLevelKey] ?? _kubb_core.logLevel.info;
1446
+ const hooks = new AsyncEventEmitter();
1447
+ let configs;
1448
+ let resolvedConfigPath;
1449
+ try {
1450
+ const loaded = await getConfigs({
1451
+ configPath,
1452
+ input,
1453
+ watch,
1454
+ logLevel: logLevelKey,
1455
+ noCache
1456
+ });
1457
+ configs = loaded.configs;
1458
+ resolvedConfigPath = loaded.configPath;
1459
+ } catch (error) {
1460
+ await setupReporters(hooks, {
1461
+ logLevel,
1462
+ reporters: [_kubb_core.cliReporter]
1463
+ });
1464
+ await hooks.emit("kubb:error", { error: require_errors.toError(error) });
1465
+ node_process.default.exit(1);
1466
+ }
1467
+ const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
1468
+ await setupReporters(hooks, {
1469
+ logLevel,
1470
+ reporters: (0, _kubb_core.selectReporters)(configs[0]?.reporters ?? [], requestedNames)
1471
+ });
1472
+ await hooks.emit("kubb:lifecycle:start", { version: require_package.version });
1473
+ await checkForUpdate(hooks);
1474
+ try {
1475
+ const relativeConfigPath = node_path.default.relative(node_process.default.cwd(), resolvedConfigPath);
1476
+ await hooks.emit("kubb:config:start");
1477
+ await hooks.emit("kubb:info", {
1478
+ message: "Config loaded",
1479
+ info: relativeConfigPath
1480
+ });
1481
+ await hooks.emit("kubb:success", {
1482
+ message: "Config loaded successfully",
1483
+ info: relativeConfigPath
1484
+ });
1485
+ await hooks.emit("kubb:config:end", { configs });
1486
+ let anyFailed = false;
1487
+ for (const config of configs) if (config.input && "path" in config.input && watch) await startWatcher([input || config.input.path], async (paths) => {
1488
+ await generate({
1489
+ input,
1490
+ config,
1491
+ logLevel,
1492
+ hooks
1493
+ });
1494
+ _clack_prompts.log.step((0, node_util.styleText)("yellow", `Watching for changes in ${paths.join(" and ")}`));
1495
+ }, {
1496
+ info: (msg) => _clack_prompts.log.info(msg),
1497
+ error: (msg) => _clack_prompts.log.error(msg)
1498
+ });
1499
+ else try {
1500
+ if (!await generate({
1501
+ input,
1502
+ config,
1503
+ logLevel,
1504
+ hooks
1505
+ })) anyFailed = true;
1506
+ } catch (configError) {
1507
+ await hooks.emit("kubb:error", { error: require_errors.toError(configError) });
1508
+ anyFailed = true;
1509
+ }
1510
+ await hooks.emit("kubb:lifecycle:end");
1511
+ if (anyFailed) node_process.default.exit(1);
1512
+ } catch (error) {
1513
+ await hooks.emit("kubb:error", { error: require_errors.toError(error) });
1514
+ node_process.default.exit(1);
1515
+ }
1516
+ }
1517
+ //#endregion
1518
+ exports.run = run;
1519
+
1520
+ //# sourceMappingURL=run-CrvmI4G2.cjs.map