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

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