@kubb/cli 5.0.0-beta.11 → 5.0.0-beta.110

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 (138) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +55 -86
  3. package/bin/kubb.js +9 -3
  4. package/dist/Telemetry-7z2tIqPm.js +282 -0
  5. package/dist/Telemetry-7z2tIqPm.js.map +1 -0
  6. package/dist/{telemetry-B2iWkY5e.cjs → Telemetry-DQOmn6aR.cjs} +167 -116
  7. package/dist/Telemetry-DQOmn6aR.cjs.map +1 -0
  8. package/dist/{errors-CINO1EIv.js → errors-CMvLO2NE.js} +3 -15
  9. package/dist/{errors-CINO1EIv.js.map → errors-CMvLO2NE.js.map} +1 -1
  10. package/dist/{errors-CLCjoSg0.cjs → errors-CZtH2dKk.cjs} +2 -20
  11. package/dist/{errors-CLCjoSg0.cjs.map → errors-CZtH2dKk.cjs.map} +1 -1
  12. package/dist/generate-BcwqjrM8.cjs +95 -0
  13. package/dist/generate-BcwqjrM8.cjs.map +1 -0
  14. package/dist/generate-CYWEueP4.js +95 -0
  15. package/dist/generate-CYWEueP4.js.map +1 -0
  16. package/dist/index.cjs +33 -261
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +6 -2
  19. package/dist/index.js +34 -262
  20. package/dist/index.js.map +1 -1
  21. package/dist/{init-DDBAAtNw.cjs → init-Ne4iWip6.cjs} +12 -13
  22. package/dist/init-Ne4iWip6.cjs.map +1 -0
  23. package/dist/{init-DalNYdKX.js → init-hCGd9LYk.js} +13 -13
  24. package/dist/init-hCGd9LYk.js.map +1 -0
  25. package/dist/mcp-C0rylVMu.js +21 -0
  26. package/dist/mcp-C0rylVMu.js.map +1 -0
  27. package/dist/mcp-t1zn9jKu.cjs +20 -0
  28. package/dist/mcp-t1zn9jKu.cjs.map +1 -0
  29. package/dist/package-BkVXQDrR.js +6 -0
  30. package/dist/package-BkVXQDrR.js.map +1 -0
  31. package/dist/{package-Dwr7GtJx.cjs → package-RKlBi2yq.cjs} +2 -2
  32. package/dist/package-RKlBi2yq.cjs.map +1 -0
  33. package/dist/{chunk-BvFE5Tac.js → rolldown-runtime-C0LytTxp.js} +0 -1
  34. package/dist/{chunk-ByKO4r7w.cjs → rolldown-runtime-qbf5tadS.cjs} +1 -1
  35. package/dist/{run-CQbj3ley.cjs → run-31OgOcxn.cjs} +9 -15
  36. package/dist/run-31OgOcxn.cjs.map +1 -0
  37. package/dist/run-Beh-ji9Y.js +1248 -0
  38. package/dist/run-Beh-ji9Y.js.map +1 -0
  39. package/dist/run-BlWEfHq_.cjs +315 -0
  40. package/dist/run-BlWEfHq_.cjs.map +1 -0
  41. package/dist/{run-CCZ24VKk.js → run-CaOjZRiQ.js} +7 -13
  42. package/dist/run-CaOjZRiQ.js.map +1 -0
  43. package/dist/{run-CF97BWVa.js → run-Cea4Wfyp.js} +157 -90
  44. package/dist/run-Cea4Wfyp.js.map +1 -0
  45. package/dist/run-DAHp52w3.js +33 -0
  46. package/dist/run-DAHp52w3.js.map +1 -0
  47. package/dist/run-DEVBHfNr.cjs +34 -0
  48. package/dist/run-DEVBHfNr.cjs.map +1 -0
  49. package/dist/run-YzBa37Vx.cjs +1251 -0
  50. package/dist/run-YzBa37Vx.cjs.map +1 -0
  51. package/dist/tools-DH1a7ZJH.js +152 -0
  52. package/dist/tools-DH1a7ZJH.js.map +1 -0
  53. package/dist/tools-bwKAf_r-.cjs +175 -0
  54. package/dist/tools-bwKAf_r-.cjs.map +1 -0
  55. package/dist/{validate-D5HeJjHB.cjs → validate-CpZJI3k7.cjs} +10 -12
  56. package/dist/validate-CpZJI3k7.cjs.map +1 -0
  57. package/dist/validate-D0qXVHbv.js +25 -0
  58. package/dist/validate-D0qXVHbv.js.map +1 -0
  59. package/package.json +15 -28
  60. package/dist/agent-DB8Fr0U8.cjs +0 -70
  61. package/dist/agent-DB8Fr0U8.cjs.map +0 -1
  62. package/dist/agent-DcsBatCv.js +0 -68
  63. package/dist/agent-DcsBatCv.js.map +0 -1
  64. package/dist/constants-B2JTeRBb.js +0 -42
  65. package/dist/constants-B2JTeRBb.js.map +0 -1
  66. package/dist/constants-BINTA5VZ.cjs +0 -77
  67. package/dist/constants-BINTA5VZ.cjs.map +0 -1
  68. package/dist/constants-BYGmiFs0.cjs +0 -139
  69. package/dist/constants-BYGmiFs0.cjs.map +0 -1
  70. package/dist/constants-DSJ-Xrbv.js +0 -116
  71. package/dist/constants-DSJ-Xrbv.js.map +0 -1
  72. package/dist/define-Bdn8j5VM.cjs +0 -54
  73. package/dist/define-Bdn8j5VM.cjs.map +0 -1
  74. package/dist/define-m_fp-Aqm.js +0 -43
  75. package/dist/define-m_fp-Aqm.js.map +0 -1
  76. package/dist/generate-DVe4vPXT.cjs +0 -71
  77. package/dist/generate-DVe4vPXT.cjs.map +0 -1
  78. package/dist/generate-dhgVXAZM.js +0 -72
  79. package/dist/generate-dhgVXAZM.js.map +0 -1
  80. package/dist/init-DDBAAtNw.cjs.map +0 -1
  81. package/dist/init-DalNYdKX.js.map +0 -1
  82. package/dist/mcp-CjLC0gfa.cjs +0 -39
  83. package/dist/mcp-CjLC0gfa.cjs.map +0 -1
  84. package/dist/mcp-qo6oTY1b.js +0 -39
  85. package/dist/mcp-qo6oTY1b.js.map +0 -1
  86. package/dist/package-BS53bjcw.js +0 -6
  87. package/dist/package-BS53bjcw.js.map +0 -1
  88. package/dist/package-Dwr7GtJx.cjs.map +0 -1
  89. package/dist/run-BzpYYOQs.js +0 -121
  90. package/dist/run-BzpYYOQs.js.map +0 -1
  91. package/dist/run-CCZ24VKk.js.map +0 -1
  92. package/dist/run-CF97BWVa.js.map +0 -1
  93. package/dist/run-CQbj3ley.cjs.map +0 -1
  94. package/dist/run-CdRxfPGM.js +0 -1736
  95. package/dist/run-CdRxfPGM.js.map +0 -1
  96. package/dist/run-CqN9CaCO.cjs +0 -1739
  97. package/dist/run-CqN9CaCO.cjs.map +0 -1
  98. package/dist/run-D0hmRpHy.js +0 -49
  99. package/dist/run-D0hmRpHy.js.map +0 -1
  100. package/dist/run-DwdAwnLG.cjs +0 -125
  101. package/dist/run-DwdAwnLG.cjs.map +0 -1
  102. package/dist/run-Lr0Ctnu0.cjs +0 -50
  103. package/dist/run-Lr0Ctnu0.cjs.map +0 -1
  104. package/dist/run-YsoCk5we.cjs +0 -248
  105. package/dist/run-YsoCk5we.cjs.map +0 -1
  106. package/dist/shell-475fQKaX.cjs +0 -62
  107. package/dist/shell-475fQKaX.cjs.map +0 -1
  108. package/dist/shell-CN6DNqeC.js +0 -51
  109. package/dist/shell-CN6DNqeC.js.map +0 -1
  110. package/dist/telemetry-B2iWkY5e.cjs.map +0 -1
  111. package/dist/telemetry-BkektVz6.js +0 -243
  112. package/dist/telemetry-BkektVz6.js.map +0 -1
  113. package/dist/validate-C00u0BgS.js +0 -26
  114. package/dist/validate-C00u0BgS.js.map +0 -1
  115. package/dist/validate-D5HeJjHB.cjs.map +0 -1
  116. package/src/commands/agent/start.ts +0 -50
  117. package/src/commands/agent.ts +0 -10
  118. package/src/commands/generate.ts +0 -59
  119. package/src/commands/init.ts +0 -51
  120. package/src/commands/mcp.ts +0 -36
  121. package/src/commands/validate.ts +0 -22
  122. package/src/constants.ts +0 -48
  123. package/src/index.ts +0 -45
  124. package/src/loggers/clackLogger.ts +0 -460
  125. package/src/loggers/fileSystemLogger.ts +0 -151
  126. package/src/loggers/githubActionsLogger.ts +0 -367
  127. package/src/loggers/plainLogger.ts +0 -243
  128. package/src/loggers/types.ts +0 -7
  129. package/src/loggers/utils.ts +0 -252
  130. package/src/runners/agent/run.ts +0 -113
  131. package/src/runners/agent/utils.ts +0 -98
  132. package/src/runners/generate/run.ts +0 -276
  133. package/src/runners/generate/utils.ts +0 -209
  134. package/src/runners/init/run.ts +0 -211
  135. package/src/runners/init/utils.ts +0 -33
  136. package/src/runners/mcp/run.ts +0 -55
  137. package/src/runners/validate/run.ts +0 -63
  138. package/src/telemetry.ts +0 -280
@@ -0,0 +1,1248 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { c as canUseTTY, i as KUBB_NPM_PACKAGE_URL, o as UPDATE_CHECK_TIMEOUT_MS, r as sendTelemetry, s as WATCHER_IGNORED_PATHS, t as buildTelemetryEvent } from "./Telemetry-7z2tIqPm.js";
3
+ import { n as toError, t as toCause } from "./errors-CMvLO2NE.js";
4
+ import { t as version } from "./package-BkVXQDrR.js";
5
+ import { i as linters, n as detectTool, r as formatters } from "./tools-DH1a7ZJH.js";
6
+ import { styleText } from "node:util";
7
+ import { randomUUID } from "node:crypto";
8
+ import process$1 from "node:process";
9
+ import path, { basename, dirname, relative, resolve } from "node:path";
10
+ import { existsSync } from "node:fs";
11
+ import * as clack from "@clack/prompts";
12
+ import { Diagnostics, Hookable, cliReporter, createKubb, getInputKind, logLevel } from "@kubb/core";
13
+ import { createJiti } from "jiti";
14
+ import { NonZeroExitError, x } from "tinyexec";
15
+ import { loadConfig } from "unconfig";
16
+ import { isGreater, isValid, truncate } from "verkit";
17
+ //#region ../../internals/utils/src/time.ts
18
+ /**
19
+ * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
20
+ * Rounds to 2 decimal places for sub-millisecond precision without noise.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const start = process.hrtime()
25
+ * doWork()
26
+ * getElapsedMs(start) // 42.35
27
+ * ```
28
+ */
29
+ function getElapsedMs(hrStart) {
30
+ const [seconds, nanoseconds] = process.hrtime(hrStart);
31
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
32
+ return Math.round(ms * 100) / 100;
33
+ }
34
+ /**
35
+ * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * formatMs(250) // '250ms'
40
+ * formatMs(1500) // '1.50s'
41
+ * formatMs(90000) // '1m 30.0s'
42
+ * ```
43
+ */
44
+ function formatMs(ms) {
45
+ if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
46
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
47
+ return `${Math.round(ms)}ms`;
48
+ }
49
+ //#endregion
50
+ //#region ../../internals/utils/src/colors.ts
51
+ /**
52
+ * Parses a CSS hex color string (`#RGB`) into its RGB channels.
53
+ * Falls back to `255` for any channel that cannot be parsed.
54
+ */
55
+ function parseHex(color) {
56
+ const int = Number.parseInt(color.replace("#", ""), 16);
57
+ return Number.isNaN(int) ? {
58
+ r: 255,
59
+ g: 255,
60
+ b: 255
61
+ } : {
62
+ r: int >> 16 & 255,
63
+ g: int >> 8 & 255,
64
+ b: int & 255
65
+ };
66
+ }
67
+ /**
68
+ * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
69
+ * for the given hex color.
70
+ */
71
+ function hex(color) {
72
+ const { r, g, b } = parseHex(color);
73
+ return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
74
+ }
75
+ function gradient(colorStops, text) {
76
+ const chars = text.split("");
77
+ return chars.map((char, i) => {
78
+ const t = chars.length <= 1 ? 0 : i / (chars.length - 1);
79
+ const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);
80
+ const lt = t * (colorStops.length - 1) - seg;
81
+ const from = parseHex(colorStops[seg]);
82
+ const to = parseHex(colorStops[seg + 1]);
83
+ 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`;
84
+ }).join("");
85
+ }
86
+ /**
87
+ * ANSI color functions for each part of the Kubb mascot illustration.
88
+ */
89
+ const palette = {
90
+ /**
91
+ * Top cap of the skittle.
92
+ */
93
+ lid: hex("#F55A17"),
94
+ /**
95
+ * Upper wood body.
96
+ */
97
+ woodTop: hex("#F5A217"),
98
+ /**
99
+ * Middle wood body.
100
+ */
101
+ woodMid: hex("#F58517"),
102
+ /**
103
+ * Base wood body.
104
+ */
105
+ woodBase: hex("#B45309"),
106
+ /**
107
+ * Eye whites.
108
+ */
109
+ eye: hex("#FFFFFF"),
110
+ /**
111
+ * Highlight accent.
112
+ */
113
+ highlight: hex("#adadc6"),
114
+ /**
115
+ * Cheek blush.
116
+ */
117
+ blush: hex("#FDA4AF")
118
+ };
119
+ /**
120
+ * Generates the Kubb mascot welcome banner as an ANSI-colored string.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))
125
+ * ```
126
+ */
127
+ function getIntro({ title, description, version, areEyesOpen }) {
128
+ const kubbVersion = gradient([
129
+ "#F58517",
130
+ "#F5A217",
131
+ "#F55A17"
132
+ ], `KUBB v${version}`);
133
+ const eyeTop = areEyesOpen ? palette.eye("█▀█") : palette.eye("───");
134
+ const eyeBottom = areEyesOpen ? palette.eye("▀▀▀") : palette.eye("───");
135
+ return `
136
+ ${palette.lid("▄▄▄▄▄▄▄▄▄▄▄▄▄")}
137
+ ${palette.woodTop("█ ")}${palette.highlight("▄▄")}${palette.woodTop(" ")}${palette.highlight("▄▄")}${palette.woodTop(" █")} ${kubbVersion}
138
+ ${palette.woodMid("█ ")}${eyeTop}${palette.woodMid(" ")}${eyeTop}${palette.woodMid(" █")} ${styleText("gray", title)}
139
+ ${palette.woodMid("█ ")}${eyeBottom}${palette.woodMid(" ")}${palette.blush("◡")}${palette.woodMid(" ")}${eyeBottom}${palette.woodMid(" █")} ${styleText("yellow", "➜")} ${styleText("white", description)}
140
+ ${palette.woodBase("▀▀▀▀▀▀▀▀▀▀▀▀▀")}
141
+ `;
142
+ }
143
+ /**
144
+ * Formats a millisecond duration with a threshold-based ANSI color.
145
+ * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * formatMsWithColor(200) // '\x1b[32m200ms\x1b[39m'
150
+ * formatMsWithColor(800) // '\x1b[33m800ms\x1b[39m'
151
+ * formatMsWithColor(1500) // '\x1b[31m1.50s\x1b[39m'
152
+ * ```
153
+ */
154
+ function formatMsWithColor(ms) {
155
+ const formatted = formatMs(ms);
156
+ if (ms <= 500) return styleText("green", formatted);
157
+ if (ms <= 1e3) return styleText("yellow", formatted);
158
+ return styleText("red", formatted);
159
+ }
160
+ //#endregion
161
+ //#region ../../internals/utils/src/promise.ts
162
+ /**
163
+ * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight
164
+ * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.
165
+ * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should
166
+ * coalesce into a single trailing run.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * const rebuild = createSerialRunner({
171
+ * run: () => build(),
172
+ * onError: (error) => log.error(error.message),
173
+ * })
174
+ * watcher.on('change', () => void rebuild())
175
+ * ```
176
+ */
177
+ function createSerialRunner({ run, onError }) {
178
+ let running = false;
179
+ let dirty = false;
180
+ return async () => {
181
+ if (running) {
182
+ dirty = true;
183
+ return;
184
+ }
185
+ running = true;
186
+ do {
187
+ dirty = false;
188
+ try {
189
+ await run();
190
+ } catch (error) {
191
+ onError(toError(error));
192
+ }
193
+ } while (dirty);
194
+ running = false;
195
+ };
196
+ }
197
+ //#endregion
198
+ //#region src/loggers/clackLogger.ts
199
+ /**
200
+ * TTY logger for local development, with spinners and progress bars.
201
+ */
202
+ const clackLogger = {
203
+ name: "clack",
204
+ install(context, options) {
205
+ const logLevel$5 = options?.logLevel ?? logLevel.info;
206
+ const state = {
207
+ ...createProgressCounters(),
208
+ spinner: clack.spinner(),
209
+ isSpinning: false,
210
+ runningPlugins: /* @__PURE__ */ new Set(),
211
+ activeProgress: /* @__PURE__ */ new Map(),
212
+ activeHookLogs: /* @__PURE__ */ new Map()
213
+ };
214
+ function stopActiveProgress() {
215
+ for (const [, active] of state.activeProgress) {
216
+ if (active.interval) clearInterval(active.interval);
217
+ active.progressBar?.stop();
218
+ }
219
+ state.activeProgress.clear();
220
+ }
221
+ function reset() {
222
+ stopActiveProgress();
223
+ resetProgressCounters(state);
224
+ state.spinner = clack.spinner();
225
+ state.isSpinning = false;
226
+ state.runningPlugins.clear();
227
+ state.activeHookLogs.clear();
228
+ }
229
+ function pluginProgressText() {
230
+ const running = [...state.runningPlugins].map((name) => styleText("bold", name));
231
+ return getMessage(running.length > 0 ? `Generating ${running.join(", ")}` : "Generating plugins");
232
+ }
233
+ function showProgressStep() {
234
+ if (logLevel$5 <= logLevel.silent) return;
235
+ const line = buildProgressLine(state);
236
+ if (line) clack.log.step(getMessage(line));
237
+ }
238
+ function getMessage(message) {
239
+ return formatMessage(message, logLevel$5);
240
+ }
241
+ function onStep(hook, message) {
242
+ context.hook(hook, () => {
243
+ if (logLevel$5 <= logLevel.silent) return;
244
+ clack.log.step(getMessage(message));
245
+ });
246
+ }
247
+ function stopSpinner(text) {
248
+ if (!state.isSpinning) return;
249
+ state.spinner.stop(text);
250
+ state.isSpinning = false;
251
+ }
252
+ context.hook("kubb:info", ({ message, info = "" }) => {
253
+ if (logLevel$5 <= logLevel.silent) return;
254
+ const text = getMessage([
255
+ styleText("blue", "ℹ"),
256
+ message,
257
+ info ? styleText("dim", info) : void 0
258
+ ].filter(Boolean).join(" "));
259
+ if (state.isSpinning) {
260
+ state.spinner.message(text);
261
+ return;
262
+ }
263
+ clack.log.info(text);
264
+ });
265
+ context.hook("kubb:success", ({ message, info = "" }) => {
266
+ if (logLevel$5 <= logLevel.silent) return;
267
+ const text = getMessage([
268
+ styleText("blue", "✓"),
269
+ message,
270
+ logLevel$5 >= logLevel.info ? styleText("dim", info) : void 0
271
+ ].filter(Boolean).join(" "));
272
+ if (state.isSpinning) {
273
+ stopSpinner(text);
274
+ return;
275
+ }
276
+ clack.log.success(text);
277
+ });
278
+ context.hook("kubb:warn", ({ message, info }) => {
279
+ if (logLevel$5 < logLevel.warn) return;
280
+ const text = getMessage([
281
+ styleText("yellow", "⚠"),
282
+ message,
283
+ logLevel$5 >= logLevel.info && info ? styleText("dim", info) : void 0
284
+ ].filter(Boolean).join(" "));
285
+ clack.log.warn(text);
286
+ });
287
+ context.hook("kubb:error", ({ error }) => {
288
+ const text = [styleText("red", "✗"), error.message].join(" ");
289
+ if (state.isSpinning) {
290
+ stopSpinner(getMessage(text));
291
+ return;
292
+ }
293
+ clack.log.error(getMessage(text));
294
+ const frames = logLevel$5 >= logLevel.verbose ? formatErrorFrames(error) : null;
295
+ if (frames) {
296
+ for (const frame of frames.frames) clack.log.message(getMessage(styleText("dim", frame)));
297
+ if (frames.cause) {
298
+ clack.log.message(styleText("dim", frames.cause.header));
299
+ for (const frame of frames.cause.frames) clack.log.message(getMessage(` ${styleText("dim", frame)}`));
300
+ }
301
+ }
302
+ });
303
+ context.hook("kubb:diagnostic", ({ diagnostic }) => {
304
+ if (logLevel$5 <= logLevel.silent && diagnostic.severity !== "error") return;
305
+ stopSpinner();
306
+ stopActiveProgress();
307
+ if (Diagnostics.isUpdate(diagnostic)) {
308
+ clack.box(`\`v${diagnostic.currentVersion}\` → \`v${diagnostic.latestVersion}\`
309
+ Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
310
+ width: "auto",
311
+ formatBorder: (s) => styleText("yellow", s),
312
+ rounded: true,
313
+ withGuide: false,
314
+ contentAlign: "center",
315
+ titleAlign: "center"
316
+ });
317
+ return;
318
+ }
319
+ const { headline, details } = Diagnostics.format(diagnostic);
320
+ clack.log.message([headline, ...details], {
321
+ symbol: "",
322
+ secondarySymbol: ""
323
+ });
324
+ });
325
+ context.hook("kubb:lifecycle:start", async ({ version }) => {
326
+ console.log(`\n${getIntro({
327
+ title: "The meta framework for code generation",
328
+ description: "Ready to start",
329
+ version,
330
+ areEyesOpen: true
331
+ })}\n`);
332
+ reset();
333
+ });
334
+ context.hook("kubb:generation:start", ({ config }) => {
335
+ reset();
336
+ state.totalPlugins = config.plugins?.length ?? 0;
337
+ if (logLevel$5 <= logLevel.silent) return;
338
+ const text = getMessage([
339
+ "Generation started",
340
+ config.name ? `for ${styleText("dim", config.name)}` : void 0,
341
+ getInputPath(config)
342
+ ].filter(Boolean).join(" "));
343
+ clack.intro(text);
344
+ });
345
+ context.hook("kubb:plugin:start", ({ plugin }) => {
346
+ if (logLevel$5 <= logLevel.silent) return;
347
+ stopSpinner();
348
+ state.runningPlugins.add(plugin.name);
349
+ const active = state.activeProgress.get("plugins");
350
+ if (active) {
351
+ active.progressBar.advance(0, pluginProgressText());
352
+ return;
353
+ }
354
+ const progressBar = clack.progress({
355
+ style: "block",
356
+ max: Math.max(state.totalPlugins, 1),
357
+ size: 30
358
+ });
359
+ progressBar.start(pluginProgressText());
360
+ progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText());
361
+ state.activeProgress.set("plugins", { progressBar });
362
+ });
363
+ context.hook("kubb:plugin:end", ({ plugin, success }) => {
364
+ stopSpinner();
365
+ const active = state.activeProgress.get("plugins");
366
+ if (!active || logLevel$5 <= logLevel.silent) return;
367
+ state.runningPlugins.delete(plugin.name);
368
+ recordPluginResult(state, success);
369
+ active.progressBar.advance(1, pluginProgressText());
370
+ if (state.runningPlugins.size === 0) {
371
+ active.progressBar.stop(getMessage("Plugins generated"));
372
+ state.activeProgress.delete("plugins");
373
+ showProgressStep();
374
+ }
375
+ });
376
+ context.hook("kubb:files:processing:start", ({ files }) => {
377
+ if (logLevel$5 <= logLevel.silent) return;
378
+ stopSpinner();
379
+ state.totalFiles = files.length;
380
+ state.processedFiles = 0;
381
+ const text = `Writing ${files.length} files`;
382
+ const progressBar = clack.progress({
383
+ style: "block",
384
+ max: files.length,
385
+ size: 30
386
+ });
387
+ context.callHook("kubb:info", { message: text });
388
+ progressBar.start(getMessage(text));
389
+ state.activeProgress.set("files", { progressBar });
390
+ });
391
+ context.hook("kubb:files:processing:update", ({ files }) => {
392
+ if (logLevel$5 <= logLevel.silent) return;
393
+ stopSpinner();
394
+ const active = state.activeProgress.get("files");
395
+ for (const { file, config } of files) {
396
+ state.processedFiles++;
397
+ if (active) active.progressBar.advance(void 0, `Writing ${relative(config.root, file.path)}`);
398
+ }
399
+ });
400
+ context.hook("kubb:files:processing:end", () => {
401
+ if (logLevel$5 <= logLevel.silent) return;
402
+ stopSpinner();
403
+ const text = getMessage("Files written successfully");
404
+ const active = state.activeProgress.get("files");
405
+ if (!active) return;
406
+ active.progressBar.stop(text);
407
+ state.activeProgress.delete("files");
408
+ showProgressStep();
409
+ });
410
+ context.hook("kubb:generation:end", ({ config }) => {
411
+ stopSpinner();
412
+ const text = getMessage(config.name ? `Generation completed for ${styleText("dim", config.name)}` : "Generation completed");
413
+ clack.outro(text);
414
+ });
415
+ onStep("kubb:format:start", "Formatting");
416
+ onStep("kubb:lint:start", "Linting");
417
+ onStep("kubb:hooks:start", "Running hooks");
418
+ context.hook("kubb:hook:start", ({ id, command, name, args }) => {
419
+ if (logLevel$5 <= logLevel.silent || !id) return;
420
+ stopSpinner();
421
+ const commandWithArgs = formatCommandWithArgs(command, args);
422
+ const title = getMessage(`Running ${styleText("dim", name ?? commandWithArgs)}`);
423
+ const taskLog = clack.taskLog({ title });
424
+ state.activeHookLogs.set(id, {
425
+ taskLog,
426
+ hrStart: process$1.hrtime()
427
+ });
428
+ });
429
+ if (logLevel$5 > logLevel.silent) context.hook("kubb:hook:line", ({ id, line }) => {
430
+ state.activeHookLogs.get(id)?.taskLog.message(styleText("dim", line));
431
+ });
432
+ context.hook("kubb:hook:end", ({ id, command, name, args, success, error, stdout, stderr }) => {
433
+ if (!id) return;
434
+ if (logLevel$5 <= logLevel.silent) {
435
+ if (!success) {
436
+ if (stdout) console.log(stdout);
437
+ if (stderr) console.error(stderr);
438
+ }
439
+ return;
440
+ }
441
+ const active = state.activeHookLogs.get(id);
442
+ if (!active) return;
443
+ state.activeHookLogs.delete(id);
444
+ const commandWithArgs = formatCommandWithArgs(command, args);
445
+ const duration = formatMsWithColor(getElapsedMs(active.hrStart));
446
+ if (success) active.taskLog.success(getMessage(`${styleText("dim", name ?? commandWithArgs)} completed in ${duration}`));
447
+ else {
448
+ const reason = error?.message ? ` (${error.message})` : "";
449
+ active.taskLog.error(getMessage(`${styleText("dim", name ?? commandWithArgs)} failed${reason}`), { showLog: true });
450
+ }
451
+ });
452
+ context.hook("kubb:lifecycle:end", () => {
453
+ reset();
454
+ });
455
+ }
456
+ };
457
+ //#endregion
458
+ //#region src/loggers/plainLogger.ts
459
+ /**
460
+ * Plain console adapter for non-TTY environments, built on `console.log`.
461
+ */
462
+ const plainLogger = {
463
+ name: "plain",
464
+ install(context, options) {
465
+ const logLevel$4 = options?.logLevel ?? logLevel.info;
466
+ const hookTimer = createHookTimer();
467
+ function getMessage(message) {
468
+ return formatMessage(message, logLevel$4);
469
+ }
470
+ function onStep(hook, message) {
471
+ context.hook(hook, () => {
472
+ if (logLevel$4 <= logLevel.silent) return;
473
+ console.log(getMessage(message));
474
+ });
475
+ }
476
+ context.hook("kubb:info", ({ message, info }) => {
477
+ if (logLevel$4 <= logLevel.silent) return;
478
+ const text = getMessage([
479
+ "ℹ",
480
+ message,
481
+ info
482
+ ].join(" "));
483
+ console.log(text);
484
+ });
485
+ context.hook("kubb:success", ({ message, info = "" }) => {
486
+ if (logLevel$4 <= logLevel.silent) return;
487
+ const text = getMessage([
488
+ "✓",
489
+ message,
490
+ logLevel$4 >= logLevel.info ? info : void 0
491
+ ].filter(Boolean).join(" "));
492
+ console.log(text);
493
+ });
494
+ context.hook("kubb:warn", ({ message, info }) => {
495
+ if (logLevel$4 < logLevel.warn) return;
496
+ const text = getMessage([
497
+ "⚠",
498
+ message,
499
+ logLevel$4 >= logLevel.info ? info : void 0
500
+ ].filter(Boolean).join(" "));
501
+ console.log(text);
502
+ });
503
+ context.hook("kubb:error", ({ error }) => {
504
+ const text = getMessage(["✗", error.message].join(" "));
505
+ console.log(text);
506
+ const frames = logLevel$4 >= logLevel.verbose ? formatErrorFrames(error) : null;
507
+ if (frames) {
508
+ for (const frame of frames.frames) console.log(getMessage(frame));
509
+ if (frames.cause) {
510
+ console.log(frames.cause.header);
511
+ for (const frame of frames.cause.frames) console.log(getMessage(` ${frame}`));
512
+ }
513
+ }
514
+ });
515
+ context.hook("kubb:diagnostic", ({ diagnostic }) => {
516
+ if (logLevel$4 <= logLevel.silent && diagnostic.severity !== "error") return;
517
+ console.log(getMessage(Diagnostics.formatLines(diagnostic).join("\n")));
518
+ });
519
+ context.hook("kubb:lifecycle:start", ({ version }) => {
520
+ console.log(`Kubb CLI v${version}`);
521
+ });
522
+ context.hook("kubb:generation:start", ({ config }) => {
523
+ const text = getMessage(["Generation started", getInputPath(config)].filter(Boolean).join(" "));
524
+ console.log(text);
525
+ });
526
+ context.hook("kubb:plugin:start", ({ plugin }) => {
527
+ if (logLevel$4 <= logLevel.silent) return;
528
+ const text = getMessage(`Generating ${plugin.name}`);
529
+ console.log(text);
530
+ });
531
+ context.hook("kubb:plugin:end", ({ plugin, duration, success }) => {
532
+ if (logLevel$4 <= logLevel.silent) return;
533
+ const durationStr = formatMs(duration);
534
+ const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
535
+ console.log(text);
536
+ });
537
+ context.hook("kubb:files:processing:start", ({ files }) => {
538
+ if (logLevel$4 <= logLevel.silent) return;
539
+ const text = getMessage(`Writing ${files.length} files`);
540
+ console.log(text);
541
+ });
542
+ context.hook("kubb:files:processing:update", ({ files }) => {
543
+ if (logLevel$4 <= logLevel.silent) return;
544
+ for (const { file, config } of files) console.log(getMessage(`Writing ${relative(config.root, file.path)}`));
545
+ });
546
+ context.hook("kubb:files:processing:end", () => {
547
+ if (logLevel$4 <= logLevel.silent) return;
548
+ const text = getMessage("Files written successfully");
549
+ console.log(text);
550
+ });
551
+ context.hook("kubb:generation:end", ({ config }) => {
552
+ const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
553
+ console.log(text);
554
+ });
555
+ onStep("kubb:format:start", "Format started");
556
+ onStep("kubb:format:end", "Format completed");
557
+ onStep("kubb:lint:start", "Lint started");
558
+ onStep("kubb:lint:end", "Lint completed");
559
+ onStep("kubb:hooks:start", "Hooks started");
560
+ onStep("kubb:hooks:end", "Hooks completed");
561
+ context.hook("kubb:hook:start", ({ id, command, name, args }) => {
562
+ if (logLevel$4 <= logLevel.silent) return;
563
+ if (id) hookTimer.start(id);
564
+ const commandWithArgs = formatCommandWithArgs(command, args);
565
+ console.log(getMessage(`Hook ${name ?? commandWithArgs} started`));
566
+ });
567
+ context.hook("kubb:hook:end", ({ id, command, name, args, success, error, stdout, stderr }) => {
568
+ if (logLevel$4 <= logLevel.silent) return;
569
+ const ms = id ? hookTimer.end(id) : void 0;
570
+ const durationStr = ms !== void 0 ? ` in ${formatMs(ms)}` : "";
571
+ const commandWithArgs = formatCommandWithArgs(command, args);
572
+ if (success) console.log(getMessage(`✓ Hook ${name ?? commandWithArgs} completed${durationStr}`));
573
+ else {
574
+ if (stdout) console.log(stdout);
575
+ if (stderr) console.error(stderr);
576
+ const reason = error?.message ? ` (${error.message})` : "";
577
+ console.log(getMessage(`✗ Hook ${name ?? commandWithArgs} failed${durationStr}${reason}`));
578
+ }
579
+ });
580
+ }
581
+ };
582
+ //#endregion
583
+ //#region src/loggers/utils.ts
584
+ /**
585
+ * Display path for a config's input: the string form, or its `path` field when the input is an
586
+ * object. Loggers show it alongside `Generation started`.
587
+ */
588
+ function getInputPath(config) {
589
+ const { input } = config;
590
+ if (typeof input === "string") return input;
591
+ return typeof input?.path === "string" ? input.path : void 0;
592
+ }
593
+ /**
594
+ * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
595
+ * Shared across all logger adapters to avoid duplication.
596
+ */
597
+ function formatMessage(message, logLevel$3) {
598
+ if (logLevel$3 >= logLevel.verbose) {
599
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
600
+ hour12: false,
601
+ hour: "2-digit",
602
+ minute: "2-digit",
603
+ second: "2-digit"
604
+ });
605
+ return `${styleText("dim", `[${timestamp}]`)} ${message}`;
606
+ }
607
+ return message;
608
+ }
609
+ /**
610
+ * First stack frames for verbose error output, including an optional `cause` chain.
611
+ */
612
+ function formatErrorFrames(error) {
613
+ if (!error.stack) return null;
614
+ const frames = error.stack.split("\n").slice(1, 4).map((frame) => frame.trim());
615
+ const caused = toCause(error);
616
+ if (!caused?.stack) return { frames };
617
+ return {
618
+ frames,
619
+ cause: {
620
+ header: `└─ caused by ${caused.message}`,
621
+ frames: caused.stack.split("\n").slice(1, 4).map((frame) => frame.trim())
622
+ }
623
+ };
624
+ }
625
+ /**
626
+ * Build the progress summary line shown by the clack logger.
627
+ * Returns null when there is nothing to display.
628
+ */
629
+ function buildProgressLine(state) {
630
+ const parts = [];
631
+ const duration = formatMs(getElapsedMs(state.hrStart));
632
+ if (state.totalPlugins > 0) {
633
+ const pluginStr = state.failedPlugins > 0 ? `Plugins ${styleText("green", state.completedPlugins.toString())}/${state.totalPlugins} ${styleText("red", `(${state.failedPlugins} failed)`)}` : `Plugins ${styleText("green", state.completedPlugins.toString())}/${state.totalPlugins}`;
634
+ parts.push(pluginStr);
635
+ }
636
+ if (state.totalFiles > 0) parts.push(`Files ${styleText("green", state.processedFiles.toString())}/${state.totalFiles}`);
637
+ if (parts.length === 0) return null;
638
+ parts.push(`${styleText("green", duration)} elapsed`);
639
+ return parts.join(styleText("dim", " | "));
640
+ }
641
+ /**
642
+ * Creates the per-run progress counters used by the clack logger.
643
+ */
644
+ function createProgressCounters() {
645
+ return {
646
+ totalPlugins: 0,
647
+ completedPlugins: 0,
648
+ failedPlugins: 0,
649
+ totalFiles: 0,
650
+ processedFiles: 0,
651
+ hrStart: process$1.hrtime()
652
+ };
653
+ }
654
+ /**
655
+ * Resets the progress counters in place at the start/end of a generation run.
656
+ */
657
+ function resetProgressCounters(state) {
658
+ state.totalPlugins = 0;
659
+ state.completedPlugins = 0;
660
+ state.failedPlugins = 0;
661
+ state.totalFiles = 0;
662
+ state.processedFiles = 0;
663
+ state.hrStart = process$1.hrtime();
664
+ }
665
+ /**
666
+ * Records a finished plugin against the progress counters.
667
+ */
668
+ function recordPluginResult(state, success) {
669
+ if (success) state.completedPlugins++;
670
+ else state.failedPlugins++;
671
+ }
672
+ /**
673
+ * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
674
+ */
675
+ function createHookTimer() {
676
+ const starts = /* @__PURE__ */ new Map();
677
+ return {
678
+ start(id) {
679
+ starts.set(id, process$1.hrtime());
680
+ },
681
+ end(id) {
682
+ const hrStart = starts.get(id);
683
+ if (!hrStart) return;
684
+ starts.delete(id);
685
+ return getElapsedMs(hrStart);
686
+ }
687
+ };
688
+ }
689
+ /**
690
+ * Join a command and its optional args into a single display string.
691
+ *
692
+ * @example With args
693
+ * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`
694
+ */
695
+ function formatCommandWithArgs(command, args) {
696
+ return args?.length ? `${command} ${args.join(" ")}` : command;
697
+ }
698
+ /**
699
+ * Bridges a {@link Reporter} onto the run's hook emitter: calls `report` with each config's
700
+ * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
701
+ */
702
+ function installReporter(context, reporter, ctx) {
703
+ context.hook("kubb:generation:end", async ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = process$1.hrtime() }) => {
704
+ await reporter.report({
705
+ config,
706
+ diagnostics,
707
+ filesCreated,
708
+ status,
709
+ hrStart
710
+ }, ctx);
711
+ });
712
+ if (reporter.drain) context.hook("kubb:lifecycle:end", () => reporter.drain?.(ctx));
713
+ }
714
+ /**
715
+ * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
716
+ * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This
717
+ * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
718
+ * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
719
+ *
720
+ * Loggers and reporters are independent, except for `cli`: it both installs the live logger view
721
+ * here and registers as a reporter that prints the per-config summary. The `json` reporter owns
722
+ * stdout, so the whole `cli` reporter (live logger and summary) is skipped whenever `json` is
723
+ * among the reporters, even if `cli` is also listed.
724
+ */
725
+ async function setupReporters(context, { logLevel, reporters }) {
726
+ const hasJson = reporters.some((reporter) => reporter.name === "json");
727
+ const ctx = { logLevel };
728
+ for (const reporter of reporters) {
729
+ if (reporter.name === "cli") {
730
+ if (hasJson) continue;
731
+ await (canUseTTY() ? clackLogger : plainLogger).install(context, { logLevel });
732
+ }
733
+ installReporter(context, reporter, ctx);
734
+ }
735
+ }
736
+ /**
737
+ * Picks the reporters whose `name` matches one of `names`, in the order the names are given.
738
+ * The config carries every available reporter, and the host selects which to activate by name
739
+ * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are
740
+ * skipped.
741
+ */
742
+ function selectReporters(reporters, names) {
743
+ const seen = /* @__PURE__ */ new Set();
744
+ const selected = [];
745
+ for (const name of names) {
746
+ if (seen.has(name)) continue;
747
+ seen.add(name);
748
+ const reporter = reporters.find((candidate) => candidate.name === name);
749
+ if (reporter) selected.push(reporter);
750
+ }
751
+ return selected;
752
+ }
753
+ //#endregion
754
+ //#region ../../internals/shared/src/loader.ts
755
+ /**
756
+ * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at
757
+ * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.
758
+ */
759
+ const JITI_OPTIONS = {
760
+ jsx: {
761
+ runtime: "automatic",
762
+ importSource: "@kubb/renderer-jsx"
763
+ },
764
+ moduleCache: false
765
+ };
766
+ /**
767
+ * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.
768
+ *
769
+ * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.
770
+ *
771
+ * @example
772
+ * ```ts
773
+ * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })
774
+ * ```
775
+ */
776
+ function createModuleLoader() {
777
+ const jiti = createJiti(import.meta.url, JITI_OPTIONS);
778
+ return { load(filePath, options) {
779
+ return options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath);
780
+ } };
781
+ }
782
+ //#endregion
783
+ //#region src/runners/generate/utils.ts
784
+ const loader = createModuleLoader();
785
+ const tsLoader = (configFile) => loader.load(configFile, { default: true });
786
+ const MODULE_NAME = "kubb";
787
+ const SEARCH_FILES = [
788
+ "",
789
+ ".config/",
790
+ "configs/"
791
+ ].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`]);
792
+ const SEARCH_EXTENSIONS = [
793
+ "ts",
794
+ "mts",
795
+ "cts",
796
+ "js",
797
+ "mjs",
798
+ "cjs"
799
+ ];
800
+ /**
801
+ * Discovers the Kubb config and resolves it into a normalized array of configs.
802
+ * Every config in the result is guaranteed to have a `plugins` array.
803
+ */
804
+ async function getConfigs({ configPath, input, watch, logLevel }) {
805
+ const abs = configPath ? resolve(configPath) : void 0;
806
+ const sources = abs ? [{
807
+ files: [basename(abs)],
808
+ extensions: [],
809
+ parser: tsLoader
810
+ }] : [{
811
+ files: SEARCH_FILES,
812
+ extensions: SEARCH_EXTENSIONS,
813
+ parser: tsLoader
814
+ }];
815
+ let result;
816
+ try {
817
+ result = await loadConfig({
818
+ cwd: abs ? dirname(abs) : process$1.cwd(),
819
+ sources,
820
+ merge: false
821
+ });
822
+ } catch (error) {
823
+ throw new Error("Config failed loading", { cause: error });
824
+ }
825
+ const [filepath] = result.sources;
826
+ if (!result.config || !filepath) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
827
+ const config = result.config;
828
+ const resolved = await (typeof config === "function" ? config({
829
+ config: configPath,
830
+ input,
831
+ watch,
832
+ logLevel
833
+ }) : config);
834
+ return {
835
+ configPath: filepath,
836
+ configs: (Array.isArray(resolved) ? resolved : [resolved]).map((item) => {
837
+ return {
838
+ ...item,
839
+ plugins: item.plugins ?? []
840
+ };
841
+ })
842
+ };
843
+ }
844
+ /**
845
+ * Returns `true` when `latest` is a newer semver version than `current`. Compares each numeric
846
+ * part, so `5.10.0` beats `5.9.0` where a plain string comparison would not. Prerelease
847
+ * suffixes are ignored, and a malformed version never reports an update.
848
+ *
849
+ * @example Double-digit minor
850
+ * `isNewerVersion('5.9.0', '5.10.0') // true`
851
+ *
852
+ * @example String comparison would get this wrong the other way
853
+ * `isNewerVersion('5.10.0', '5.9.0') // false`
854
+ */
855
+ function isNewerVersion(current, latest) {
856
+ if (!isValid(current) || !isValid(latest)) return false;
857
+ return isGreater(truncate(latest, "patch"), truncate(current, "patch"));
858
+ }
859
+ /**
860
+ * Tokenizes a shell command string, respecting single and double quotes.
861
+ *
862
+ * @example
863
+ * ```ts
864
+ * tokenize('git commit -m "initial commit"')
865
+ * // → ['git', 'commit', '-m', 'initial commit']
866
+ * ```
867
+ */
868
+ function tokenize(command) {
869
+ return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
870
+ }
871
+ /**
872
+ * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's
873
+ * outcome, so the caller can turn failures into diagnostics.
874
+ */
875
+ async function runPostGenerate({ commands, hooks }) {
876
+ const results = [];
877
+ for (const entry of commands) {
878
+ const { command, name } = typeof entry === "string" ? {
879
+ command: entry,
880
+ name: void 0
881
+ } : entry;
882
+ const [cmd, ...args] = tokenize(command);
883
+ if (!cmd) continue;
884
+ const hookId = randomUUID();
885
+ const commandWithArgs = [cmd, ...args].join(" ");
886
+ await hooks.callHook("kubb:hook:start", {
887
+ id: hookId,
888
+ command: cmd,
889
+ name,
890
+ args
891
+ });
892
+ results.push(await runHook({
893
+ id: hookId,
894
+ command: cmd,
895
+ name,
896
+ args,
897
+ commandWithArgs,
898
+ hooks
899
+ }));
900
+ }
901
+ return results;
902
+ }
903
+ /**
904
+ * Spawns a hook command and returns its outcome, mirroring it through `kubb:hook:end` for the
905
+ * loggers. A non-zero exit returns `success: false` rather than throwing, so the caller can turn
906
+ * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`
907
+ * only while a listener is attached.
908
+ */
909
+ async function runHook({ id, command, name, args, commandWithArgs, hooks }) {
910
+ const emitEnd = async (result) => {
911
+ await hooks.callHook("kubb:hook:end", {
912
+ command,
913
+ name,
914
+ args,
915
+ id,
916
+ ...result
917
+ });
918
+ return result;
919
+ };
920
+ const stream = hooks.listenerCount("kubb:hook:line") > 0;
921
+ try {
922
+ const proc = x(command, [...args ?? []], {
923
+ nodeOptions: { detached: process$1.platform !== "win32" },
924
+ throwOnError: true
925
+ });
926
+ if (stream) for await (const line of proc) await hooks.callHook("kubb:hook:line", {
927
+ id,
928
+ line
929
+ });
930
+ await proc;
931
+ await hooks.callHook("kubb:success", { message: `${styleText("dim", name ?? commandWithArgs)} successfully executed` });
932
+ return emitEnd({
933
+ success: true,
934
+ error: null
935
+ });
936
+ } catch (err) {
937
+ if (!(err instanceof NonZeroExitError)) return emitEnd({
938
+ success: false,
939
+ error: toError(err)
940
+ });
941
+ const stderr = err.output?.stderr ?? "";
942
+ const stdout = err.output?.stdout ?? "";
943
+ return emitEnd({
944
+ success: false,
945
+ error: /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`),
946
+ stdout,
947
+ stderr
948
+ });
949
+ }
950
+ }
951
+ /**
952
+ * Starts a file watcher on the given paths and calls `cb` on any change.
953
+ * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)
954
+ * are debounced into one build, and builds never overlap: changes during a build queue exactly
955
+ * one rebuild.
956
+ */
957
+ async function startWatcher(path, cb, log = {
958
+ info: console.log,
959
+ error: console.log
960
+ }) {
961
+ const { watch } = await import("chokidar");
962
+ const watcher = watch(path, {
963
+ ignorePermissionErrors: true,
964
+ ignored: WATCHER_IGNORED_PATHS,
965
+ ignoreInitial: true
966
+ });
967
+ process$1.once("SIGINT", () => {
968
+ watcher.close();
969
+ });
970
+ process$1.once("SIGTERM", () => {
971
+ watcher.close();
972
+ });
973
+ const runBuild = createSerialRunner({
974
+ run: () => cb(path),
975
+ onError: () => log.error(styleText("red", "Watcher failed"))
976
+ });
977
+ let debounceTimer = null;
978
+ watcher.on("all", (type, file) => {
979
+ log.info(styleText("yellow", styleText("bold", `Change detected: ${type} ${file}`)));
980
+ if (debounceTimer) clearTimeout(debounceTimer);
981
+ debounceTimer = setTimeout(() => {
982
+ debounceTimer = null;
983
+ runBuild();
984
+ }, 100);
985
+ });
986
+ }
987
+ //#endregion
988
+ //#region src/runners/generate/run.ts
989
+ /**
990
+ * Runs one formatter or linter pass over the output directory. Returns the failure instead of
991
+ * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:
992
+ * the caller emits them through `Diagnostics.emit`, like every other diagnostic.
993
+ */
994
+ async function runToolPass({ toolValue, tool, outputPath, logLevel: logLevel$1, hooks, onStart, onEnd }) {
995
+ await onStart();
996
+ let resolvedTool = toolValue;
997
+ if (resolvedTool === "auto") {
998
+ const detected = await tool.detect();
999
+ if (!detected) await hooks.callHook("kubb:warn", { message: tool.noToolMessage });
1000
+ else {
1001
+ resolvedTool = detected;
1002
+ await hooks.callHook("kubb:info", { message: `Auto-detected ${tool.label}: ${styleText("dim", resolvedTool)}` });
1003
+ }
1004
+ }
1005
+ let toolError = null;
1006
+ if (resolvedTool && resolvedTool !== "auto" && resolvedTool in tool.map && existsSync(outputPath)) {
1007
+ const toolConfig = tool.map[resolvedTool];
1008
+ const successMessage = [
1009
+ `${tool.successPrefix} with ${styleText("dim", resolvedTool)}`,
1010
+ logLevel$1 >= logLevel.info ? `on ${styleText("dim", outputPath)}` : void 0,
1011
+ "successfully"
1012
+ ].filter(Boolean).join(" ");
1013
+ try {
1014
+ const hookId = randomUUID();
1015
+ const hookArgs = toolConfig.args(outputPath);
1016
+ const commandWithArgs = [toolConfig.command, ...hookArgs].join(" ");
1017
+ await hooks.callHook("kubb:hook:start", {
1018
+ id: hookId,
1019
+ command: toolConfig.command,
1020
+ args: hookArgs
1021
+ });
1022
+ const result = await runHook({
1023
+ id: hookId,
1024
+ command: toolConfig.command,
1025
+ args: hookArgs,
1026
+ commandWithArgs,
1027
+ hooks
1028
+ });
1029
+ if (result.success) await hooks.callHook("kubb:success", { message: successMessage });
1030
+ else toolError = result.error ?? new Error(toolConfig.errorMessage);
1031
+ } catch (caughtError) {
1032
+ toolError = toError(caughtError);
1033
+ }
1034
+ }
1035
+ await onEnd();
1036
+ return toolError;
1037
+ }
1038
+ async function generate(options) {
1039
+ const { input, hooks, logLevel } = options;
1040
+ const hrStart = process$1.hrtime();
1041
+ const inputPath = input ?? (typeof options.config.input === "string" ? options.config.input : void 0);
1042
+ const config = {
1043
+ ...options.config,
1044
+ input: input ?? options.config.input
1045
+ };
1046
+ const processOutput = async ({ config: resolvedConfig, outputPath }) => {
1047
+ const outputDiagnostics = [];
1048
+ const reportOutputFailure = async (code, label, error) => {
1049
+ const diagnostic = outputDiagnostic(code, label, error);
1050
+ outputDiagnostics.push(diagnostic);
1051
+ await Diagnostics.emit(hooks, diagnostic);
1052
+ };
1053
+ const toolPasses = [{
1054
+ value: resolvedConfig.output.format,
1055
+ code: Diagnostics.code.formatFailed,
1056
+ tool: {
1057
+ label: "formatter",
1058
+ map: formatters,
1059
+ detect: () => detectTool([
1060
+ "oxfmt",
1061
+ "biome",
1062
+ "prettier"
1063
+ ]),
1064
+ successPrefix: "Formatting",
1065
+ noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting."
1066
+ },
1067
+ onStart: () => hooks.callHook("kubb:format:start"),
1068
+ onEnd: () => hooks.callHook("kubb:format:end")
1069
+ }, {
1070
+ value: resolvedConfig.output.lint,
1071
+ code: Diagnostics.code.lintFailed,
1072
+ tool: {
1073
+ label: "linter",
1074
+ map: linters,
1075
+ detect: () => detectTool([
1076
+ "oxlint",
1077
+ "biome",
1078
+ "eslint"
1079
+ ]),
1080
+ successPrefix: "Linting",
1081
+ noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting."
1082
+ },
1083
+ onStart: () => hooks.callHook("kubb:lint:start"),
1084
+ onEnd: () => hooks.callHook("kubb:lint:end")
1085
+ }];
1086
+ for (const pass of toolPasses) {
1087
+ if (!pass.value) continue;
1088
+ const error = await runToolPass({
1089
+ toolValue: pass.value,
1090
+ tool: pass.tool,
1091
+ onStart: pass.onStart,
1092
+ onEnd: pass.onEnd,
1093
+ outputPath,
1094
+ logLevel,
1095
+ hooks
1096
+ });
1097
+ if (error) await reportOutputFailure(pass.code, pass.tool.label, error);
1098
+ }
1099
+ if (resolvedConfig.output.postGenerate?.length) {
1100
+ await hooks.callHook("kubb:hooks:start");
1101
+ const hookResults = await runPostGenerate({
1102
+ commands: resolvedConfig.output.postGenerate,
1103
+ hooks
1104
+ });
1105
+ for (const hookResult of hookResults) {
1106
+ if (hookResult.success) continue;
1107
+ await reportOutputFailure(Diagnostics.code.postGenerateFailed, "Post-generate command", hookResult.error ?? /* @__PURE__ */ new Error("Post-generate command failed"));
1108
+ }
1109
+ await hooks.callHook("kubb:hooks:end");
1110
+ }
1111
+ return outputDiagnostics;
1112
+ };
1113
+ hooks.hook("kubb:generation:end", ({ status }) => {
1114
+ if (status === "success") return hooks.callHook("kubb:success", {
1115
+ message: "Generation succeeded",
1116
+ info: inputPath
1117
+ });
1118
+ });
1119
+ const kubb = createKubb(config, { hooks });
1120
+ const result = await kubb.generate({ processOutput });
1121
+ const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({
1122
+ name: p.name,
1123
+ options: p.options
1124
+ }));
1125
+ await sendTelemetry(buildTelemetryEvent({
1126
+ command: "generate",
1127
+ kubbVersion: version,
1128
+ plugins: telemetryPlugins,
1129
+ hrStart,
1130
+ filesCreated: result.files.length,
1131
+ status: result.success ? "success" : "failed"
1132
+ }));
1133
+ return result.success;
1134
+ }
1135
+ /**
1136
+ * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).
1137
+ */
1138
+ function outputDiagnostic(code, label, caughtError) {
1139
+ const error = toError(caughtError);
1140
+ return {
1141
+ code,
1142
+ severity: "error",
1143
+ message: `${label} failed: ${error.message}`,
1144
+ help: "Check that the tool is installed and that the command and its config are correct.",
1145
+ location: { kind: "config" },
1146
+ cause: error
1147
+ };
1148
+ }
1149
+ async function checkForUpdate(hooks) {
1150
+ try {
1151
+ const data = await (await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })).json();
1152
+ if (data.version && isNewerVersion(version, data.version)) await Diagnostics.emit(hooks, Diagnostics.update({
1153
+ currentVersion: version,
1154
+ latestVersion: data.version
1155
+ }));
1156
+ } catch {}
1157
+ }
1158
+ /**
1159
+ * Runs the full Kubb generation lifecycle for the given CLI options.
1160
+ * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),
1161
+ * checks for a newer version, and calls `generate` for each config entry.
1162
+ */
1163
+ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters }) {
1164
+ const logLevel$2 = logLevel[logLevelKey] ?? logLevel.info;
1165
+ const hooks = new Hookable();
1166
+ let configs;
1167
+ let resolvedConfigPath;
1168
+ try {
1169
+ const loaded = await getConfigs({
1170
+ configPath,
1171
+ input,
1172
+ watch,
1173
+ logLevel: logLevelKey
1174
+ });
1175
+ configs = loaded.configs;
1176
+ resolvedConfigPath = loaded.configPath;
1177
+ } catch (error) {
1178
+ await setupReporters(hooks, {
1179
+ logLevel: logLevel$2,
1180
+ reporters: [cliReporter]
1181
+ });
1182
+ await hooks.callHook("kubb:error", { error: toError(error) });
1183
+ process$1.exit(1);
1184
+ }
1185
+ const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
1186
+ await setupReporters(hooks, {
1187
+ logLevel: logLevel$2,
1188
+ reporters: selectReporters(configs[0]?.reporters ?? [], requestedNames)
1189
+ });
1190
+ await hooks.callHook("kubb:lifecycle:start", { version });
1191
+ await checkForUpdate(hooks);
1192
+ try {
1193
+ const relativeConfigPath = path.relative(process$1.cwd(), resolvedConfigPath);
1194
+ await hooks.callHook("kubb:info", {
1195
+ message: "Config loaded",
1196
+ info: relativeConfigPath
1197
+ });
1198
+ await hooks.callHook("kubb:success", {
1199
+ message: "Config loaded successfully",
1200
+ info: relativeConfigPath
1201
+ });
1202
+ let anyFailed = false;
1203
+ for (const config of configs) {
1204
+ const effectiveInput = input ?? config.input;
1205
+ const watchPath = typeof effectiveInput === "string" && getInputKind(effectiveInput) === "file" ? effectiveInput : void 0;
1206
+ if (watchPath && watch) {
1207
+ const watchedPaths = [watchPath];
1208
+ const build = async (paths) => {
1209
+ await generate({
1210
+ input,
1211
+ config,
1212
+ logLevel: logLevel$2,
1213
+ hooks
1214
+ });
1215
+ clack.log.step(styleText("yellow", `Watching for changes in ${paths.join(" and ")}`));
1216
+ };
1217
+ try {
1218
+ await build(watchedPaths);
1219
+ } catch (buildError) {
1220
+ await hooks.callHook("kubb:error", { error: toError(buildError) });
1221
+ }
1222
+ await startWatcher(watchedPaths, build, {
1223
+ info: (msg) => clack.log.info(msg),
1224
+ error: (msg) => clack.log.error(msg)
1225
+ });
1226
+ } else try {
1227
+ if (!await generate({
1228
+ input,
1229
+ config,
1230
+ logLevel: logLevel$2,
1231
+ hooks
1232
+ })) anyFailed = true;
1233
+ } catch (configError) {
1234
+ await hooks.callHook("kubb:error", { error: toError(configError) });
1235
+ anyFailed = true;
1236
+ }
1237
+ }
1238
+ await hooks.callHook("kubb:lifecycle:end");
1239
+ if (anyFailed) process$1.exit(1);
1240
+ } catch (error) {
1241
+ await hooks.callHook("kubb:error", { error: toError(error) });
1242
+ process$1.exit(1);
1243
+ }
1244
+ }
1245
+ //#endregion
1246
+ export { run };
1247
+
1248
+ //# sourceMappingURL=run-Beh-ji9Y.js.map