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

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