@kubb/cli 5.0.0-beta.5 → 5.0.0-beta.51

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 (148) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +171 -51
  3. package/dist/Telemetry-BG80bcoQ.cjs +350 -0
  4. package/dist/Telemetry-BG80bcoQ.cjs.map +1 -0
  5. package/dist/Telemetry-CyBqvgcj.js +313 -0
  6. package/dist/Telemetry-CyBqvgcj.js.map +1 -0
  7. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  8. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  9. package/dist/{define-Ctii4bel.js → define-C63T4jp6.js} +2 -2
  10. package/dist/{define-Ctii4bel.js.map → define-C63T4jp6.js.map} +1 -1
  11. package/dist/{errors-CjPmyZHy.js → errors-BsemQCMn.js} +2 -2
  12. package/dist/{errors-CjPmyZHy.js.map → errors-BsemQCMn.js.map} +1 -1
  13. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  14. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  15. package/dist/generate-BRpukupe.cjs +82 -0
  16. package/dist/generate-BRpukupe.cjs.map +1 -0
  17. package/dist/generate-XeCSLYWp.js +83 -0
  18. package/dist/generate-XeCSLYWp.js.map +1 -0
  19. package/dist/index.cjs +22 -16
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +21 -15
  23. package/dist/index.js.map +1 -1
  24. package/dist/init-C156kkn3.cjs +53 -0
  25. package/dist/init-C156kkn3.cjs.map +1 -0
  26. package/dist/init-Djx-xXm2.js +53 -0
  27. package/dist/init-Djx-xXm2.js.map +1 -0
  28. package/dist/mcp--t_K4yMF.js +39 -0
  29. package/dist/mcp--t_K4yMF.js.map +1 -0
  30. package/dist/mcp-D4ZwcNDD.cjs +39 -0
  31. package/dist/mcp-D4ZwcNDD.cjs.map +1 -0
  32. package/dist/package-_PDiS5qW.js +6 -0
  33. package/dist/package-_PDiS5qW.js.map +1 -0
  34. package/dist/{package-BmYRU2hz.cjs → package-aN3cIOkh.cjs} +2 -2
  35. package/dist/package-aN3cIOkh.cjs.map +1 -0
  36. package/dist/run-7yQQ3lIR.js +51 -0
  37. package/dist/run-7yQQ3lIR.js.map +1 -0
  38. package/dist/{init-C5sZulT6.cjs → run-BtjzfTz3.cjs} +155 -85
  39. package/dist/run-BtjzfTz3.cjs.map +1 -0
  40. package/dist/{init-Cag3082g.js → run-C-omuksC.js} +147 -77
  41. package/dist/run-C-omuksC.js.map +1 -0
  42. package/dist/run-CDs_ebOt.cjs +1458 -0
  43. package/dist/run-CDs_ebOt.cjs.map +1 -0
  44. package/dist/run-CZEf3B3A.cjs +33 -0
  45. package/dist/run-CZEf3B3A.cjs.map +1 -0
  46. package/dist/run-CsBW0NRp.js +32 -0
  47. package/dist/run-CsBW0NRp.js.map +1 -0
  48. package/dist/run-YYlwMdeu.cjs +52 -0
  49. package/dist/run-YYlwMdeu.cjs.map +1 -0
  50. package/dist/run-aODbKkaY.js +1455 -0
  51. package/dist/run-aODbKkaY.js.map +1 -0
  52. package/dist/{shell-DLzN4fRo.js → shell-DsgkfUSW.js} +2 -2
  53. package/dist/{shell-DLzN4fRo.js.map → shell-DsgkfUSW.js.map} +1 -1
  54. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  55. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  56. package/dist/validate-DWdTJLGF.js +26 -0
  57. package/dist/validate-DWdTJLGF.js.map +1 -0
  58. package/dist/validate-sOD68Kma.cjs +26 -0
  59. package/dist/validate-sOD68Kma.cjs.map +1 -0
  60. package/package.json +14 -24
  61. package/src/Telemetry.ts +290 -0
  62. package/src/commands/generate.ts +27 -13
  63. package/src/commands/init.ts +34 -3
  64. package/src/commands/mcp.ts +28 -4
  65. package/src/commands/validate.ts +6 -4
  66. package/src/constants.ts +1 -81
  67. package/src/index.ts +7 -6
  68. package/src/loggers/clackLogger.ts +135 -201
  69. package/src/loggers/defineLogger.ts +59 -0
  70. package/src/loggers/plainLogger.ts +47 -102
  71. package/src/loggers/types.ts +6 -1
  72. package/src/loggers/utils.ts +164 -23
  73. package/src/runners/generate/run.ts +403 -0
  74. package/src/runners/generate/utils.ts +228 -0
  75. package/src/runners/init/run.ts +210 -0
  76. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  77. package/src/runners/mcp/run.ts +37 -0
  78. package/src/runners/validate/run.ts +63 -0
  79. package/dist/agent-BcUEl9yB.js +0 -56
  80. package/dist/agent-BcUEl9yB.js.map +0 -1
  81. package/dist/agent-CS45W0kL.cjs +0 -122
  82. package/dist/agent-CS45W0kL.cjs.map +0 -1
  83. package/dist/agent-CsMvXeqI.cjs +0 -58
  84. package/dist/agent-CsMvXeqI.cjs.map +0 -1
  85. package/dist/agent-IP0eLV3C.js +0 -118
  86. package/dist/agent-IP0eLV3C.js.map +0 -1
  87. package/dist/constants-B4iBDvCe.cjs +0 -148
  88. package/dist/constants-B4iBDvCe.cjs.map +0 -1
  89. package/dist/constants-DmPrkaz8.js +0 -95
  90. package/dist/constants-DmPrkaz8.js.map +0 -1
  91. package/dist/generate-7td_hs73.cjs +0 -65
  92. package/dist/generate-7td_hs73.cjs.map +0 -1
  93. package/dist/generate-BqeFFQGD.js +0 -66
  94. package/dist/generate-BqeFFQGD.js.map +0 -1
  95. package/dist/generate-CUd1dUY5.cjs +0 -1755
  96. package/dist/generate-CUd1dUY5.cjs.map +0 -1
  97. package/dist/generate-DVmGtwWe.js +0 -1752
  98. package/dist/generate-DVmGtwWe.js.map +0 -1
  99. package/dist/init-C5sZulT6.cjs.map +0 -1
  100. package/dist/init-Cag3082g.js.map +0 -1
  101. package/dist/init-CfAn19gC.js +0 -25
  102. package/dist/init-CfAn19gC.js.map +0 -1
  103. package/dist/init-CfsYoyGe.cjs +0 -25
  104. package/dist/init-CfsYoyGe.cjs.map +0 -1
  105. package/dist/mcp-BfORW-mY.cjs +0 -47
  106. package/dist/mcp-BfORW-mY.cjs.map +0 -1
  107. package/dist/mcp-BtOV6acy.js +0 -16
  108. package/dist/mcp-BtOV6acy.js.map +0 -1
  109. package/dist/mcp-CIbuLGMx.cjs +0 -16
  110. package/dist/mcp-CIbuLGMx.cjs.map +0 -1
  111. package/dist/mcp-DtQ5o0On.js +0 -46
  112. package/dist/mcp-DtQ5o0On.js.map +0 -1
  113. package/dist/package-BmYRU2hz.cjs.map +0 -1
  114. package/dist/package-DBU5ii-k.js +0 -6
  115. package/dist/package-DBU5ii-k.js.map +0 -1
  116. package/dist/telemetry-BU25EoI-.cjs +0 -282
  117. package/dist/telemetry-BU25EoI-.cjs.map +0 -1
  118. package/dist/telemetry-CaNU4-Bf.js +0 -245
  119. package/dist/telemetry-CaNU4-Bf.js.map +0 -1
  120. package/dist/validate-CQqM9siF.js +0 -25
  121. package/dist/validate-CQqM9siF.js.map +0 -1
  122. package/dist/validate-DBXLaLIn.cjs +0 -34
  123. package/dist/validate-DBXLaLIn.cjs.map +0 -1
  124. package/dist/validate-DI23zgmL.js +0 -33
  125. package/dist/validate-DI23zgmL.js.map +0 -1
  126. package/dist/validate-DwX4LzYq.cjs +0 -25
  127. package/dist/validate-DwX4LzYq.cjs.map +0 -1
  128. package/src/commands/agent/start.ts +0 -47
  129. package/src/commands/agent.ts +0 -8
  130. package/src/loggers/fileSystemLogger.ts +0 -138
  131. package/src/loggers/githubActionsLogger.ts +0 -379
  132. package/src/runners/agent.ts +0 -155
  133. package/src/runners/generate.ts +0 -333
  134. package/src/runners/init.ts +0 -296
  135. package/src/runners/mcp.ts +0 -51
  136. package/src/runners/validate.ts +0 -39
  137. package/src/types.ts +0 -11
  138. package/src/utils/Writables.ts +0 -17
  139. package/src/utils/executeHooks.ts +0 -45
  140. package/src/utils/flags.ts +0 -9
  141. package/src/utils/getConfig.ts +0 -10
  142. package/src/utils/getCosmiConfig.ts +0 -75
  143. package/src/utils/getSummary.ts +0 -68
  144. package/src/utils/runHook.ts +0 -91
  145. package/src/utils/telemetry.ts +0 -273
  146. package/src/utils/watcher.ts +0 -19
  147. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
  148. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -1,1755 +0,0 @@
1
- const require_chunk = require("./chunk-ByKO4r7w.cjs");
2
- const require_errors = require("./errors-CLCjoSg0.cjs");
3
- const require_telemetry = require("./telemetry-BU25EoI-.cjs");
4
- const require_shell = require("./shell-475fQKaX.cjs");
5
- const require_package = require("./package-BmYRU2hz.cjs");
6
- const require_constants = require("./constants-B4iBDvCe.cjs");
7
- let node_util = require("node:util");
8
- let node_events = require("node:events");
9
- let node_crypto = require("node:crypto");
10
- let node_child_process = require("node:child_process");
11
- let node_fs = require("node:fs");
12
- let node_fs_promises = require("node:fs/promises");
13
- let node_path = require("node:path");
14
- node_path = require_chunk.__toESM(node_path, 1);
15
- let node_process = require("node:process");
16
- node_process = require_chunk.__toESM(node_process, 1);
17
- let _clack_prompts = require("@clack/prompts");
18
- _clack_prompts = require_chunk.__toESM(_clack_prompts, 1);
19
- let _kubb_core = require("@kubb/core");
20
- let tinyexec = require("tinyexec");
21
- let node_stream = require("node:stream");
22
- let cosmiconfig = require("cosmiconfig");
23
- let jiti = require("jiti");
24
- //#region ../../internals/utils/src/asyncEventEmitter.ts
25
- /**
26
- * Typed `EventEmitter` that awaits all async listeners before resolving.
27
- * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
28
- *
29
- * @example
30
- * ```ts
31
- * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
32
- * emitter.on('build', async (name) => { console.log(name) })
33
- * await emitter.emit('build', 'petstore') // all listeners awaited
34
- * ```
35
- */
36
- var AsyncEventEmitter = class {
37
- /**
38
- * Maximum number of listeners per event before Node emits a memory-leak warning.
39
- * @default 10
40
- */
41
- constructor(maxListener = 10) {
42
- this.#emitter.setMaxListeners(maxListener);
43
- }
44
- #emitter = new node_events.EventEmitter();
45
- /**
46
- * Emits `eventName` and awaits all registered listeners sequentially.
47
- * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
48
- *
49
- * @example
50
- * ```ts
51
- * await emitter.emit('build', 'petstore')
52
- * ```
53
- */
54
- async emit(eventName, ...eventArgs) {
55
- const listeners = this.#emitter.listeners(eventName);
56
- if (listeners.length === 0) return;
57
- for (const listener of listeners) try {
58
- await listener(...eventArgs);
59
- } catch (err) {
60
- let serializedArgs;
61
- try {
62
- serializedArgs = JSON.stringify(eventArgs);
63
- } catch {
64
- serializedArgs = String(eventArgs);
65
- }
66
- throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: require_errors.toError(err) });
67
- }
68
- }
69
- /**
70
- * Registers a persistent listener for `eventName`.
71
- *
72
- * @example
73
- * ```ts
74
- * emitter.on('build', async (name) => { console.log(name) })
75
- * ```
76
- */
77
- on(eventName, handler) {
78
- this.#emitter.on(eventName, handler);
79
- }
80
- /**
81
- * Registers a one-shot listener that removes itself after the first invocation.
82
- *
83
- * @example
84
- * ```ts
85
- * emitter.onOnce('build', async (name) => { console.log(name) })
86
- * ```
87
- */
88
- onOnce(eventName, handler) {
89
- const wrapper = (...args) => {
90
- this.off(eventName, wrapper);
91
- return handler(...args);
92
- };
93
- this.on(eventName, wrapper);
94
- }
95
- /**
96
- * Removes a previously registered listener.
97
- *
98
- * @example
99
- * ```ts
100
- * emitter.off('build', handler)
101
- * ```
102
- */
103
- off(eventName, handler) {
104
- this.#emitter.off(eventName, handler);
105
- }
106
- /**
107
- * Returns the number of listeners registered for `eventName`.
108
- *
109
- * @example
110
- * ```ts
111
- * emitter.on('build', handler)
112
- * emitter.listenerCount('build') // 1
113
- * ```
114
- */
115
- listenerCount(eventName) {
116
- return this.#emitter.listenerCount(eventName);
117
- }
118
- /**
119
- * Removes all listeners from every event channel.
120
- *
121
- * @example
122
- * ```ts
123
- * emitter.removeAll()
124
- * ```
125
- */
126
- removeAll() {
127
- this.#emitter.removeAllListeners();
128
- }
129
- };
130
- //#endregion
131
- //#region ../../internals/utils/src/time.ts
132
- /**
133
- * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
134
- * Rounds to 2 decimal places for sub-millisecond precision without noise.
135
- *
136
- * @example
137
- * ```ts
138
- * const start = process.hrtime()
139
- * doWork()
140
- * getElapsedMs(start) // 42.35
141
- * ```
142
- */
143
- function getElapsedMs(hrStart) {
144
- const [seconds, nanoseconds] = process.hrtime(hrStart);
145
- const ms = seconds * 1e3 + nanoseconds / 1e6;
146
- return Math.round(ms * 100) / 100;
147
- }
148
- /**
149
- * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
150
- *
151
- * @example
152
- * ```ts
153
- * formatMs(250) // '250ms'
154
- * formatMs(1500) // '1.50s'
155
- * formatMs(90000) // '1m 30.0s'
156
- * ```
157
- */
158
- function formatMs(ms) {
159
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
160
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
161
- return `${Math.round(ms)}ms`;
162
- }
163
- /**
164
- * Formats the elapsed time since `hrStart` as a human-readable string.
165
- *
166
- * @example
167
- * ```ts
168
- * const start = process.hrtime()
169
- * doWork()
170
- * formatHrtime(start) // '1.50s'
171
- * ```
172
- */
173
- function formatHrtime(hrStart) {
174
- return formatMs(getElapsedMs(hrStart));
175
- }
176
- //#endregion
177
- //#region ../../internals/utils/src/colors.ts
178
- /**
179
- * Parses a CSS hex color string (`#RGB`) into its RGB channels.
180
- * Falls back to `255` for any channel that cannot be parsed.
181
- */
182
- function parseHex(color) {
183
- const int = Number.parseInt(color.replace("#", ""), 16);
184
- return Number.isNaN(int) ? {
185
- r: 255,
186
- g: 255,
187
- b: 255
188
- } : {
189
- r: int >> 16 & 255,
190
- g: int >> 8 & 255,
191
- b: int & 255
192
- };
193
- }
194
- /**
195
- * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
196
- * for the given hex color.
197
- */
198
- function hex(color) {
199
- const { r, g, b } = parseHex(color);
200
- return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
201
- }
202
- function gradient(colorStops, text) {
203
- const chars = text.split("");
204
- return chars.map((char, i) => {
205
- const t = chars.length <= 1 ? 0 : i / (chars.length - 1);
206
- const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);
207
- const lt = t * (colorStops.length - 1) - seg;
208
- const from = parseHex(colorStops[seg]);
209
- const to = parseHex(colorStops[seg + 1]);
210
- 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`;
211
- }).join("");
212
- }
213
- /**
214
- * ANSI color functions for each part of the Kubb mascot illustration.
215
- */
216
- const palette = {
217
- /**
218
- * Top cap of the skittle.
219
- */
220
- lid: hex("#F55A17"),
221
- /**
222
- * Upper wood body.
223
- */
224
- woodTop: hex("#F5A217"),
225
- /**
226
- * Middle wood body.
227
- */
228
- woodMid: hex("#F58517"),
229
- /**
230
- * Base wood body.
231
- */
232
- woodBase: hex("#B45309"),
233
- /**
234
- * Eye whites.
235
- */
236
- eye: hex("#FFFFFF"),
237
- /**
238
- * Highlight accent.
239
- */
240
- highlight: hex("#adadc6"),
241
- /**
242
- * Cheek blush.
243
- */
244
- blush: hex("#FDA4AF")
245
- };
246
- /**
247
- * Generates the Kubb mascot welcome banner as an ANSI-colored string.
248
- *
249
- * @example
250
- * ```ts
251
- * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))
252
- * ```
253
- */
254
- function getIntro({ title, description, version, areEyesOpen }) {
255
- const kubbVersion = gradient([
256
- "#F58517",
257
- "#F5A217",
258
- "#F55A17"
259
- ], `KUBB v${version}`);
260
- const eyeTop = areEyesOpen ? palette.eye("█▀█") : palette.eye("───");
261
- const eyeBottom = areEyesOpen ? palette.eye("▀▀▀") : palette.eye("───");
262
- return `
263
- ${palette.lid("▄▄▄▄▄▄▄▄▄▄▄▄▄")}
264
- ${palette.woodTop("█ ")}${palette.highlight("▄▄")}${palette.woodTop(" ")}${palette.highlight("▄▄")}${palette.woodTop(" █")} ${kubbVersion}
265
- ${palette.woodMid("█ ")}${eyeTop}${palette.woodMid(" ")}${eyeTop}${palette.woodMid(" █")} ${(0, node_util.styleText)("gray", title)}
266
- ${palette.woodMid("█ ")}${eyeBottom}${palette.woodMid(" ")}${palette.blush("◡")}${palette.woodMid(" ")}${eyeBottom}${palette.woodMid(" █")} ${(0, node_util.styleText)("yellow", "➜")} ${(0, node_util.styleText)("white", description)}
267
- ${palette.woodBase("▀▀▀▀▀▀▀▀▀▀▀▀▀")}
268
- `;
269
- }
270
- /**
271
- * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.
272
- */
273
- const randomColors = [
274
- "black",
275
- "red",
276
- "green",
277
- "yellow",
278
- "blue",
279
- "white",
280
- "magenta",
281
- "cyan",
282
- "gray"
283
- ];
284
- /**
285
- * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.
286
- *
287
- * @example
288
- * ```ts
289
- * randomCliColor('petstore') // '\x1b[33m' + 'petstore' + '\x1b[39m' (always the same color for 'petstore')
290
- * ```
291
- */
292
- function randomCliColor(text) {
293
- if (!text) return "";
294
- return (0, node_util.styleText)(randomColors[(0, node_crypto.createHash)("sha256").update(text).digest().readUInt32BE(0) % randomColors.length] ?? "white", text);
295
- }
296
- /**
297
- * Formats a millisecond duration with a threshold-based ANSI color.
298
- * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.
299
- *
300
- * @example
301
- * ```ts
302
- * formatMsWithColor(200) // '\x1b[32m200ms\x1b[39m'
303
- * formatMsWithColor(800) // '\x1b[33m800ms\x1b[39m'
304
- * formatMsWithColor(1500) // '\x1b[31m1.50s\x1b[39m'
305
- * ```
306
- */
307
- function formatMsWithColor(ms) {
308
- const formatted = formatMs(ms);
309
- if (ms <= 500) return (0, node_util.styleText)("green", formatted);
310
- if (ms <= 1e3) return (0, node_util.styleText)("yellow", formatted);
311
- return (0, node_util.styleText)("red", formatted);
312
- }
313
- //#endregion
314
- //#region ../../internals/utils/src/formatters.ts
315
- /**
316
- * CLI command descriptors for each supported code formatter.
317
- *
318
- * Each entry contains the executable `command`, an `args` factory that maps an
319
- * output path to the correct argument list, and an `errorMessage` shown when
320
- * the formatter is not found.
321
- */
322
- const formatters = {
323
- prettier: {
324
- command: "prettier",
325
- args: (outputPath) => [
326
- "--ignore-unknown",
327
- "--write",
328
- outputPath
329
- ],
330
- errorMessage: "Prettier not found"
331
- },
332
- biome: {
333
- command: "biome",
334
- args: (outputPath) => [
335
- "format",
336
- "--write",
337
- outputPath
338
- ],
339
- errorMessage: "Biome not found"
340
- },
341
- oxfmt: {
342
- command: "oxfmt",
343
- args: (outputPath) => [outputPath],
344
- errorMessage: "Oxfmt not found"
345
- }
346
- };
347
- async function isFormatterAvailable(formatter) {
348
- return new Promise((resolve) => {
349
- const child = (0, node_child_process.spawn)(formatter, ["--version"], { stdio: "ignore" });
350
- child.on("close", (code) => resolve(code === 0));
351
- child.on("error", () => resolve(false));
352
- });
353
- }
354
- /**
355
- * Detects the first available code formatter on the current system.
356
- *
357
- * - Checks in preference order: `oxfmt`, `biome`, `prettier`.
358
- * - Returns `null` when none are found.
359
- *
360
- * @example
361
- * ```ts
362
- * const formatter = await detectFormatter()
363
- * if (formatter) {
364
- * console.log(`Using ${formatter} for formatting`)
365
- * }
366
- * ```
367
- */
368
- async function detectFormatter() {
369
- const formatterNames = new Set([
370
- "oxfmt",
371
- "biome",
372
- "prettier"
373
- ]);
374
- for (const formatter of formatterNames) if (await isFormatterAvailable(formatter)) return formatter;
375
- return null;
376
- }
377
- //#endregion
378
- //#region ../../internals/utils/src/fs.ts
379
- /**
380
- * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
381
- * Skips the write when the trimmed content is empty or identical to what is already on disk.
382
- * Creates any missing parent directories automatically.
383
- * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
384
- *
385
- * @example
386
- * ```ts
387
- * await write('./src/Pet.ts', source) // writes and returns trimmed content
388
- * await write('./src/Pet.ts', source) // null — file unchanged
389
- * await write('./src/Pet.ts', ' ') // null — empty content skipped
390
- * ```
391
- */
392
- async function write(path, data, options = {}) {
393
- const trimmed = data.trim();
394
- if (trimmed === "") return null;
395
- const resolved = (0, node_path.resolve)(path);
396
- if (typeof Bun !== "undefined") {
397
- const file = Bun.file(resolved);
398
- if ((await file.exists() ? await file.text() : null) === trimmed) return null;
399
- await Bun.write(resolved, trimmed);
400
- return trimmed;
401
- }
402
- try {
403
- if (await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" }) === trimmed) return null;
404
- } catch {}
405
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
406
- await (0, node_fs_promises.writeFile)(resolved, trimmed, { encoding: "utf-8" });
407
- if (options.sanity) {
408
- const savedData = await (0, node_fs_promises.readFile)(resolved, { encoding: "utf-8" });
409
- if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
410
- return savedData;
411
- }
412
- return trimmed;
413
- }
414
- //#endregion
415
- //#region ../../internals/utils/src/linters.ts
416
- /**
417
- * Collects all files under `dir` recursively using Node's built-in fs APIs.
418
- *
419
- * Passing explicit file paths to oxlint (instead of a directory) bypasses
420
- * oxlint's `.gitignore`-aware directory traversal, which would otherwise skip
421
- * files that are listed in `.gitignore` (e.g. generated output directories).
422
- */
423
- function findLintableFiles(dir) {
424
- try {
425
- return (0, node_fs.readdirSync)(dir, {
426
- withFileTypes: true,
427
- recursive: true
428
- }).filter((d) => d.isFile()).map((d) => `${d.parentPath}/${d.name}`);
429
- } catch {
430
- return [];
431
- }
432
- }
433
- /**
434
- * CLI command descriptors for each supported linter.
435
- *
436
- * Each entry contains the executable `command`, an `args` factory that maps an
437
- * output path to the correct argument list, and an `errorMessage` shown when
438
- * the linter is not found.
439
- */
440
- const linters = {
441
- eslint: {
442
- command: "eslint",
443
- args: (outputPath) => [outputPath, "--fix"],
444
- errorMessage: "Eslint not found"
445
- },
446
- biome: {
447
- command: "biome",
448
- args: (outputPath) => [
449
- "lint",
450
- "--fix",
451
- outputPath
452
- ],
453
- errorMessage: "Biome not found"
454
- },
455
- oxlint: {
456
- command: "oxlint",
457
- args: (outputPath) => ["--fix", ...findLintableFiles(outputPath)],
458
- errorMessage: "Oxlint not found"
459
- }
460
- };
461
- async function isLinterAvailable(linter) {
462
- return new Promise((resolve) => {
463
- const child = (0, node_child_process.spawn)(linter, ["--version"], { stdio: "ignore" });
464
- child.on("close", (code) => resolve(code === 0));
465
- child.on("error", () => resolve(false));
466
- });
467
- }
468
- /**
469
- * Detects the first available linter on the current system.
470
- *
471
- * - Checks in preference order: `oxlint`, `biome`, `eslint`.
472
- * - Returns `null` when none are found.
473
- *
474
- * @example
475
- * ```ts
476
- * const linter = await detectLinter()
477
- * if (linter) {
478
- * console.log(`Using ${linter} for linting`)
479
- * }
480
- * ```
481
- */
482
- async function detectLinter() {
483
- const linterNames = new Set([
484
- "oxlint",
485
- "biome",
486
- "eslint"
487
- ]);
488
- for (const linter of linterNames) if (await isLinterAvailable(linter)) return linter;
489
- return null;
490
- }
491
- //#endregion
492
- //#region src/utils/getSummary.ts
493
- function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }) {
494
- const duration = formatHrtime(hrStart);
495
- const pluginsCount = config.plugins?.length ?? 0;
496
- const successCount = pluginsCount - failedPlugins.size;
497
- const meta = {
498
- plugins: status === "success" ? `${(0, node_util.styleText)("green", `${successCount} successful`)}, ${pluginsCount} total` : `${(0, node_util.styleText)("green", `${successCount} successful`)}, ${(0, node_util.styleText)("red", `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
499
- pluginsFailed: status === "failed" ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(", ") : void 0,
500
- filesCreated,
501
- time: (0, node_util.styleText)("green", duration),
502
- output: node_path.default.resolve(config.root, config.output.path)
503
- };
504
- const labels = {
505
- plugins: "Plugins:",
506
- failed: "Failed:",
507
- generated: "Generated:",
508
- pluginTimings: "Plugin Timings:",
509
- output: "Output:"
510
- };
511
- const maxLength = Math.max(0, ...[...Object.values(labels), ...pluginTimings ? Array.from(pluginTimings.keys()) : []].map((s) => s.length));
512
- const summaryLines = [];
513
- summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`);
514
- if (meta.pluginsFailed) summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`);
515
- summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`);
516
- if (pluginTimings && pluginTimings.size > 0) {
517
- const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1]);
518
- summaryLines.push(`${labels.pluginTimings}`);
519
- sortedTimings.forEach(([name, time]) => {
520
- const timeStr = time >= 1e3 ? `${(time / 1e3).toFixed(2)}s` : `${Math.round(time)}ms`;
521
- const barLength = Math.min(Math.ceil(time / 100), 10);
522
- const bar = (0, node_util.styleText)("dim", "█".repeat(barLength));
523
- summaryLines.push(`${(0, node_util.styleText)("dim", "•")} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`);
524
- });
525
- }
526
- summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`);
527
- return summaryLines;
528
- }
529
- //#endregion
530
- //#region src/utils/runHook.ts
531
- /**
532
- * Executes a hook command, emits debug and completion events, and forwards output to an optional sink.
533
- */
534
- async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }) {
535
- try {
536
- const proc = (0, tinyexec.x)(command, [...args ?? []], {
537
- nodeOptions: { detached: process.platform !== "win32" },
538
- throwOnError: true
539
- });
540
- if (stream && sink?.onLine) for await (const line of proc) sink.onLine(line);
541
- const result = await proc;
542
- await context.emit("kubb:debug", {
543
- date: /* @__PURE__ */ new Date(),
544
- logs: [result.stdout.trimEnd()]
545
- });
546
- await context.emit("kubb:hook:end", {
547
- command,
548
- args,
549
- id,
550
- success: true,
551
- error: null
552
- });
553
- } catch (err) {
554
- if (!(err instanceof tinyexec.NonZeroExitError)) {
555
- await context.emit("kubb:hook:end", {
556
- command,
557
- args,
558
- id,
559
- success: false,
560
- error: require_errors.toError(err)
561
- });
562
- await context.emit("kubb:error", { error: require_errors.toError(err) });
563
- return;
564
- }
565
- const stderr = err.output?.stderr ?? "";
566
- const stdout = err.output?.stdout ?? "";
567
- await context.emit("kubb:debug", {
568
- date: /* @__PURE__ */ new Date(),
569
- logs: [stdout, stderr].filter(Boolean)
570
- });
571
- if (stderr) sink?.onStderr?.(stderr);
572
- if (stdout) sink?.onStdout?.(stdout);
573
- const errorMessage = /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`);
574
- await context.emit("kubb:hook:end", {
575
- command,
576
- args,
577
- id,
578
- success: false,
579
- error: errorMessage
580
- });
581
- await context.emit("kubb:error", { error: errorMessage });
582
- }
583
- }
584
- //#endregion
585
- //#region src/utils/Writables.ts
586
- var ClackWritable = class extends node_stream.Writable {
587
- taskLog;
588
- constructor(taskLog, opts) {
589
- super(opts);
590
- this.taskLog = taskLog;
591
- }
592
- _write(chunk, _encoding, callback) {
593
- this.taskLog.message(`${(0, node_util.styleText)("dim", chunk.toString())}`);
594
- callback();
595
- }
596
- };
597
- //#endregion
598
- //#region src/loggers/clackLogger.ts
599
- /**
600
- * TTY logger with beautiful UI and progress indicators for local development.
601
- */
602
- const clackLogger = (0, _kubb_core.defineLogger)({
603
- name: "clack",
604
- install(context, options) {
605
- const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
606
- const state = {
607
- totalPlugins: 0,
608
- completedPlugins: 0,
609
- failedPlugins: 0,
610
- totalFiles: 0,
611
- processedFiles: 0,
612
- hrStart: node_process.default.hrtime(),
613
- spinner: _clack_prompts.spinner(),
614
- isSpinning: false,
615
- activeProgress: /* @__PURE__ */ new Map()
616
- };
617
- function reset() {
618
- for (const [_key, active] of state.activeProgress) {
619
- if (active.interval) clearInterval(active.interval);
620
- active.progressBar?.stop();
621
- }
622
- state.totalPlugins = 0;
623
- state.completedPlugins = 0;
624
- state.failedPlugins = 0;
625
- state.totalFiles = 0;
626
- state.processedFiles = 0;
627
- state.hrStart = node_process.default.hrtime();
628
- state.spinner = _clack_prompts.spinner();
629
- state.isSpinning = false;
630
- state.activeProgress.clear();
631
- }
632
- function showProgressStep() {
633
- if (logLevel <= _kubb_core.logLevel.silent) return;
634
- const line = buildProgressLine(state);
635
- if (line) _clack_prompts.log.step(getMessage(line));
636
- }
637
- function getMessage(message) {
638
- return formatMessage(message, logLevel);
639
- }
640
- function startSpinner(text) {
641
- state.spinner.start(text);
642
- state.isSpinning = true;
643
- }
644
- function stopSpinner(text) {
645
- state.spinner.stop(text);
646
- state.isSpinning = false;
647
- }
648
- context.on("kubb:info", ({ message, info = "" }) => {
649
- if (logLevel <= _kubb_core.logLevel.silent) return;
650
- const text = getMessage([
651
- (0, node_util.styleText)("blue", "ℹ"),
652
- message,
653
- (0, node_util.styleText)("dim", info)
654
- ].join(" "));
655
- if (state.isSpinning) state.spinner.message(text);
656
- else _clack_prompts.log.info(text);
657
- });
658
- context.on("kubb:success", ({ message, info = "" }) => {
659
- if (logLevel <= _kubb_core.logLevel.silent) return;
660
- const text = getMessage([
661
- (0, node_util.styleText)("blue", "✓"),
662
- message,
663
- logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", info) : void 0
664
- ].filter(Boolean).join(" "));
665
- if (state.isSpinning) stopSpinner(text);
666
- else _clack_prompts.log.success(text);
667
- });
668
- context.on("kubb:warn", ({ message, info }) => {
669
- if (logLevel < _kubb_core.logLevel.warn) return;
670
- const text = getMessage([
671
- (0, node_util.styleText)("yellow", "⚠"),
672
- message,
673
- logLevel >= _kubb_core.logLevel.info && info ? (0, node_util.styleText)("dim", info) : void 0
674
- ].filter(Boolean).join(" "));
675
- _clack_prompts.log.warn(text);
676
- });
677
- context.on("kubb:error", ({ error }) => {
678
- const caused = require_errors.toCause(error);
679
- const text = [(0, node_util.styleText)("red", "✗"), error.message].join(" ");
680
- if (state.isSpinning) stopSpinner(getMessage(text));
681
- else _clack_prompts.log.error(getMessage(text));
682
- if (logLevel >= _kubb_core.logLevel.debug && error.stack) {
683
- const frames = error.stack.split("\n").slice(1, 4);
684
- for (const frame of frames) _clack_prompts.log.message(getMessage((0, node_util.styleText)("dim", frame.trim())));
685
- if (caused?.stack) {
686
- _clack_prompts.log.message((0, node_util.styleText)("dim", `└─ caused by ${caused.message}`));
687
- const frames = caused.stack.split("\n").slice(1, 4);
688
- for (const frame of frames) _clack_prompts.log.message(getMessage(` ${(0, node_util.styleText)("dim", frame.trim())}`));
689
- }
690
- }
691
- });
692
- context.on("kubb:version:new", ({ currentVersion, latestVersion }) => {
693
- if (logLevel <= _kubb_core.logLevel.silent) return;
694
- try {
695
- _clack_prompts.box(`\`v${currentVersion}\` → \`v${latestVersion}\`
696
- Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
697
- width: "auto",
698
- formatBorder: (s) => (0, node_util.styleText)("yellow", s),
699
- rounded: true,
700
- withGuide: false,
701
- contentAlign: "center",
702
- titleAlign: "center"
703
- });
704
- } catch {
705
- console.log(`Update available for Kubb: v${currentVersion} → v${latestVersion}`);
706
- console.log("Run `npm install -g @kubb/cli` to update");
707
- }
708
- });
709
- context.on("kubb:lifecycle:start", async ({ version }) => {
710
- console.log(`\n${getIntro({
711
- title: "The ultimate toolkit for working with APIs",
712
- description: "Ready to start",
713
- version,
714
- areEyesOpen: true
715
- })}\n`);
716
- reset();
717
- });
718
- context.on("kubb:config:start", () => {
719
- if (logLevel <= _kubb_core.logLevel.silent) return;
720
- const text = getMessage("Configuration started");
721
- _clack_prompts.intro(text);
722
- startSpinner(getMessage("Configuration loading"));
723
- });
724
- context.on("kubb:config:end", () => {
725
- if (logLevel <= _kubb_core.logLevel.silent) return;
726
- const text = getMessage("Configuration completed");
727
- _clack_prompts.outro(text);
728
- });
729
- context.on("kubb:generation:start", ({ config }) => {
730
- reset();
731
- state.totalPlugins = config.plugins?.length ?? 0;
732
- const text = getMessage(["Generation started", config.name ? `for ${(0, node_util.styleText)("dim", config.name)}` : void 0].filter(Boolean).join(" "));
733
- _clack_prompts.intro(text);
734
- });
735
- context.on("kubb:plugin:start", ({ plugin }) => {
736
- if (logLevel <= _kubb_core.logLevel.silent) return;
737
- stopSpinner();
738
- const progressBar = _clack_prompts.progress({
739
- style: "block",
740
- max: 100,
741
- size: 30
742
- });
743
- const text = getMessage(`Generating ${(0, node_util.styleText)("bold", plugin.name)}`);
744
- progressBar.start(text);
745
- const interval = setInterval(() => {
746
- progressBar.advance();
747
- }, 100);
748
- state.activeProgress.set(plugin.name, {
749
- progressBar,
750
- interval
751
- });
752
- });
753
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
754
- stopSpinner();
755
- const active = state.activeProgress.get(plugin.name);
756
- if (!active || logLevel === _kubb_core.logLevel.silent) return;
757
- clearInterval(active.interval);
758
- if (success) state.completedPlugins++;
759
- else state.failedPlugins++;
760
- const durationStr = formatMsWithColor(duration);
761
- const text = getMessage(success ? `${(0, node_util.styleText)("bold", plugin.name)} completed in ${durationStr}` : `${(0, node_util.styleText)("bold", plugin.name)} failed in ${(0, node_util.styleText)("red", formatMs(duration))}`);
762
- active.progressBar.stop(text);
763
- state.activeProgress.delete(plugin.name);
764
- showProgressStep();
765
- });
766
- context.on("kubb:files:processing:start", ({ files }) => {
767
- if (logLevel <= _kubb_core.logLevel.silent) return;
768
- stopSpinner();
769
- state.totalFiles = files.length;
770
- state.processedFiles = 0;
771
- const text = `Writing ${files.length} files`;
772
- const progressBar = _clack_prompts.progress({
773
- style: "block",
774
- max: files.length,
775
- size: 30
776
- });
777
- context.emit("kubb:info", { message: text });
778
- progressBar.start(getMessage(text));
779
- state.activeProgress.set("files", { progressBar });
780
- });
781
- context.on("kubb:file:processing:update", ({ file, config }) => {
782
- if (logLevel <= _kubb_core.logLevel.silent) return;
783
- stopSpinner();
784
- state.processedFiles++;
785
- const text = `Writing ${(0, node_path.relative)(config.root, file.path)}`;
786
- const active = state.activeProgress.get("files");
787
- if (!active) return;
788
- active.progressBar.advance(void 0, text);
789
- });
790
- context.on("kubb:files:processing:end", () => {
791
- if (logLevel <= _kubb_core.logLevel.silent) return;
792
- stopSpinner();
793
- const text = getMessage("Files written successfully");
794
- const active = state.activeProgress.get("files");
795
- if (!active) return;
796
- active.progressBar.stop(text);
797
- state.activeProgress.delete("files");
798
- showProgressStep();
799
- });
800
- context.on("kubb:generation:end", ({ config }) => {
801
- const text = getMessage(config.name ? `Generation completed for ${(0, node_util.styleText)("dim", config.name)}` : "Generation completed");
802
- _clack_prompts.outro(text);
803
- });
804
- context.on("kubb:format:start", () => {
805
- if (logLevel <= _kubb_core.logLevel.silent) return;
806
- const text = getMessage("Format started");
807
- _clack_prompts.intro(text);
808
- });
809
- context.on("kubb:format:end", () => {
810
- if (logLevel <= _kubb_core.logLevel.silent) return;
811
- const text = getMessage("Format completed");
812
- _clack_prompts.outro(text);
813
- });
814
- context.on("kubb:lint:start", () => {
815
- if (logLevel <= _kubb_core.logLevel.silent) return;
816
- const text = getMessage("Lint started");
817
- _clack_prompts.intro(text);
818
- });
819
- context.on("kubb:lint:end", () => {
820
- if (logLevel <= _kubb_core.logLevel.silent) return;
821
- const text = getMessage("Lint completed");
822
- _clack_prompts.outro(text);
823
- });
824
- context.on("kubb:hook:start", async ({ id, command, args }) => {
825
- const commandWithArgs = formatCommandWithArgs(command, args);
826
- const text = getMessage(`Hook ${(0, node_util.styleText)("dim", commandWithArgs)} started`);
827
- if (!id) return;
828
- if (logLevel <= _kubb_core.logLevel.silent) {
829
- await runHook({
830
- id,
831
- command,
832
- args,
833
- commandWithArgs,
834
- context,
835
- sink: {
836
- onStderr: (s) => console.error(s),
837
- onStdout: (s) => console.log(s)
838
- }
839
- });
840
- return;
841
- }
842
- _clack_prompts.intro(text);
843
- const logger = _clack_prompts.taskLog({ title: getMessage(["Executing hook", logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", commandWithArgs) : void 0].filter(Boolean).join(" ")) });
844
- const writable = new ClackWritable(logger);
845
- await runHook({
846
- id,
847
- command,
848
- args,
849
- commandWithArgs,
850
- context,
851
- stream: true,
852
- sink: {
853
- onLine: (line) => writable.write(line),
854
- onStderr: (s) => logger.error(s),
855
- onStdout: (s) => logger.message(s)
856
- }
857
- });
858
- });
859
- context.on("kubb:hook:end", ({ command, args }) => {
860
- if (logLevel <= _kubb_core.logLevel.silent) return;
861
- const text = getMessage(`Hook ${(0, node_util.styleText)("dim", formatCommandWithArgs(command, args))} successfully executed`);
862
- _clack_prompts.outro(text);
863
- });
864
- context.on("kubb:generation:summary", ({ config, pluginTimings, failedPlugins, filesCreated, status, hrStart }) => {
865
- const summary = getSummary({
866
- failedPlugins,
867
- filesCreated,
868
- config,
869
- status,
870
- hrStart,
871
- pluginTimings: logLevel >= _kubb_core.logLevel.verbose ? pluginTimings : void 0
872
- });
873
- const title = config.name || "";
874
- summary.unshift("\n");
875
- summary.push("\n");
876
- const borderColor = status === "success" ? "green" : "red";
877
- try {
878
- _clack_prompts.box(summary.join("\n"), getMessage(title), {
879
- width: "auto",
880
- formatBorder: (s) => (0, node_util.styleText)(borderColor, s),
881
- rounded: true,
882
- withGuide: false,
883
- contentAlign: "left",
884
- titleAlign: "center"
885
- });
886
- } catch {
887
- console.log(summary.join("\n"));
888
- }
889
- });
890
- context.on("kubb:lifecycle:end", () => {
891
- reset();
892
- });
893
- }
894
- });
895
- //#endregion
896
- //#region src/loggers/fileSystemLogger.ts
897
- /**
898
- * FileSystem logger that captures debug events and writes them to `.kubb` directory files.
899
- * Note: Logs write on `lifecycle:end` or process exit. Cached logs may be lost if the process crashes before these events.
900
- */
901
- const fileSystemLogger = (0, _kubb_core.defineLogger)({
902
- name: "filesystem",
903
- install(context) {
904
- const state = {
905
- cachedLogs: /* @__PURE__ */ new Set(),
906
- startDate: Date.now()
907
- };
908
- function reset() {
909
- state.cachedLogs = /* @__PURE__ */ new Set();
910
- state.startDate = Date.now();
911
- }
912
- async function writeLogs(name) {
913
- if (state.cachedLogs.size === 0) return [];
914
- const files = {};
915
- for (const log of state.cachedLogs) {
916
- const baseName = log.fileName || `${[
917
- "kubb",
918
- name,
919
- state.startDate
920
- ].filter(Boolean).join("-")}.log`;
921
- const pathName = (0, node_path.resolve)(node_process.default.cwd(), ".kubb", baseName);
922
- if (!files[pathName]) files[pathName] = [];
923
- if (log.logs.length > 0) {
924
- const timestamp = log.date.toLocaleString();
925
- files[pathName].push(`[${timestamp}]\n${log.logs.join("\n")}`);
926
- }
927
- }
928
- for (const [fileName, logs] of Object.entries(files)) await write(fileName, logs.join("\n\n"));
929
- return Object.keys(files);
930
- }
931
- context.on("kubb:info", ({ message, info }) => {
932
- state.cachedLogs.add({
933
- date: /* @__PURE__ */ new Date(),
934
- logs: [`ℹ ${message} ${info}`]
935
- });
936
- });
937
- context.on("kubb:success", ({ message, info }) => {
938
- state.cachedLogs.add({
939
- date: /* @__PURE__ */ new Date(),
940
- logs: [`✓ ${message} ${info}`]
941
- });
942
- });
943
- context.on("kubb:warn", ({ message, info }) => {
944
- state.cachedLogs.add({
945
- date: /* @__PURE__ */ new Date(),
946
- logs: [`⚠ ${message} ${info}`]
947
- });
948
- });
949
- context.on("kubb:error", ({ error }) => {
950
- state.cachedLogs.add({
951
- date: /* @__PURE__ */ new Date(),
952
- logs: [`✗ ${error.message}`, error.stack || "unknown stack"]
953
- });
954
- });
955
- context.on("kubb:debug", (message) => {
956
- state.cachedLogs.add({
957
- date: /* @__PURE__ */ new Date(),
958
- logs: message.logs
959
- });
960
- });
961
- context.on("kubb:plugin:start", ({ plugin }) => {
962
- state.cachedLogs.add({
963
- date: /* @__PURE__ */ new Date(),
964
- logs: [`Generating ${plugin.name}`]
965
- });
966
- });
967
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
968
- const durationStr = formatMs(duration);
969
- state.cachedLogs.add({
970
- date: /* @__PURE__ */ new Date(),
971
- logs: [success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`]
972
- });
973
- });
974
- context.on("kubb:files:processing:start", ({ files }) => {
975
- state.cachedLogs.add({
976
- date: /* @__PURE__ */ new Date(),
977
- logs: [`Start ${files.length} writing:`, ...files.map((file) => file.path)]
978
- });
979
- });
980
- context.on("kubb:generation:end", async ({ config }) => {
981
- const writtenFilePaths = await writeLogs(config.name);
982
- if (writtenFilePaths.length > 0) {
983
- const files = writtenFilePaths.map((f) => (0, node_path.relative)(node_process.default.cwd(), f));
984
- await context.emit("kubb:info", {
985
- message: "Debug files written to:",
986
- info: files.join(", ")
987
- });
988
- }
989
- reset();
990
- });
991
- const exitHandler = () => {
992
- if (state.cachedLogs.size > 0) writeLogs().catch(() => {});
993
- };
994
- node_process.default.once("exit", exitHandler);
995
- node_process.default.once("SIGINT", exitHandler);
996
- node_process.default.once("SIGTERM", exitHandler);
997
- }
998
- });
999
- //#endregion
1000
- //#region src/loggers/githubActionsLogger.ts
1001
- /**
1002
- * GitHub Actions logger using group annotations for collapsible sections in CI.
1003
- */
1004
- const githubActionsLogger = (0, _kubb_core.defineLogger)({
1005
- name: "github-actions",
1006
- install(context, options) {
1007
- const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
1008
- const state = {
1009
- totalPlugins: 0,
1010
- completedPlugins: 0,
1011
- failedPlugins: 0,
1012
- totalFiles: 0,
1013
- processedFiles: 0,
1014
- hrStart: process.hrtime(),
1015
- currentConfigs: []
1016
- };
1017
- function reset() {
1018
- state.totalPlugins = 0;
1019
- state.completedPlugins = 0;
1020
- state.failedPlugins = 0;
1021
- state.totalFiles = 0;
1022
- state.processedFiles = 0;
1023
- state.hrStart = process.hrtime();
1024
- state.currentConfigs = [];
1025
- }
1026
- function showProgressStep() {
1027
- if (logLevel <= _kubb_core.logLevel.silent) return;
1028
- const line = buildProgressLine(state);
1029
- if (line) console.log(getMessage(line));
1030
- }
1031
- function getMessage(message) {
1032
- return formatMessage(message, logLevel);
1033
- }
1034
- function openGroup(name) {
1035
- console.log(`::group::${name}`);
1036
- }
1037
- function closeGroup(_name) {
1038
- console.log("::endgroup::");
1039
- }
1040
- context.on("kubb:info", ({ message, info = "" }) => {
1041
- if (logLevel <= _kubb_core.logLevel.silent) return;
1042
- const text = getMessage([
1043
- (0, node_util.styleText)("blue", "ℹ"),
1044
- message,
1045
- (0, node_util.styleText)("dim", info)
1046
- ].join(" "));
1047
- console.log(text);
1048
- });
1049
- context.on("kubb:success", ({ message, info = "" }) => {
1050
- if (logLevel <= _kubb_core.logLevel.silent) return;
1051
- const text = getMessage([
1052
- (0, node_util.styleText)("blue", "✓"),
1053
- message,
1054
- logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", info) : void 0
1055
- ].filter(Boolean).join(" "));
1056
- console.log(text);
1057
- });
1058
- context.on("kubb:warn", ({ message, info = "" }) => {
1059
- if (logLevel <= _kubb_core.logLevel.silent) return;
1060
- const text = getMessage([
1061
- (0, node_util.styleText)("yellow", "⚠"),
1062
- message,
1063
- logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", info) : void 0
1064
- ].filter(Boolean).join(" "));
1065
- console.warn(`::warning::${text}`);
1066
- });
1067
- context.on("kubb:error", ({ error }) => {
1068
- const caused = require_errors.toCause(error);
1069
- if (logLevel <= _kubb_core.logLevel.silent) return;
1070
- const message = error.message || String(error);
1071
- console.error(`::error::${message}`);
1072
- if (logLevel >= _kubb_core.logLevel.debug && error.stack) {
1073
- const frames = error.stack.split("\n").slice(1, 4);
1074
- for (const frame of frames) console.log(getMessage((0, node_util.styleText)("dim", frame.trim())));
1075
- if (caused?.stack) {
1076
- console.log((0, node_util.styleText)("dim", `└─ caused by ${caused.message}`));
1077
- const frames = caused.stack.split("\n").slice(1, 4);
1078
- for (const frame of frames) console.log(getMessage(` ${(0, node_util.styleText)("dim", frame.trim())}`));
1079
- }
1080
- }
1081
- });
1082
- context.on("kubb:lifecycle:start", ({ version }) => {
1083
- console.log((0, node_util.styleText)("yellow", `Kubb ${version} 🧩`));
1084
- reset();
1085
- });
1086
- context.on("kubb:config:start", () => {
1087
- if (logLevel <= _kubb_core.logLevel.silent) return;
1088
- const text = getMessage("Configuration started");
1089
- openGroup("Configuration");
1090
- console.log(text);
1091
- });
1092
- context.on("kubb:config:end", ({ configs }) => {
1093
- state.currentConfigs = configs;
1094
- if (logLevel <= _kubb_core.logLevel.silent) return;
1095
- const text = getMessage("Configuration completed");
1096
- console.log(text);
1097
- closeGroup("Configuration");
1098
- });
1099
- context.on("kubb:generation:start", ({ config }) => {
1100
- reset();
1101
- state.totalPlugins = config.plugins?.length ?? 0;
1102
- const text = config.name ? `Generation for ${(0, node_util.styleText)("bold", config.name)}` : "Generation";
1103
- if (state.currentConfigs.length > 1) openGroup(text);
1104
- if (state.currentConfigs.length === 1) console.log(getMessage(text));
1105
- });
1106
- context.on("kubb:plugin:start", ({ plugin }) => {
1107
- if (logLevel <= _kubb_core.logLevel.silent) return;
1108
- const text = getMessage(`Generating ${(0, node_util.styleText)("bold", plugin.name)}`);
1109
- if (state.currentConfigs.length === 1) openGroup(`Plugin: ${plugin.name}`);
1110
- console.log(text);
1111
- });
1112
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
1113
- if (logLevel <= _kubb_core.logLevel.silent) return;
1114
- if (success) state.completedPlugins++;
1115
- else state.failedPlugins++;
1116
- const durationStr = formatMsWithColor(duration);
1117
- const text = getMessage(success ? `${(0, node_util.styleText)("bold", plugin.name)} completed in ${durationStr}` : `${(0, node_util.styleText)("bold", plugin.name)} failed in ${(0, node_util.styleText)("red", formatMs(duration))}`);
1118
- console.log(text);
1119
- if (state.currentConfigs.length > 1) console.log(" ");
1120
- if (state.currentConfigs.length === 1) closeGroup(`Plugin: ${plugin.name}`);
1121
- showProgressStep();
1122
- });
1123
- context.on("kubb:files:processing:start", ({ files }) => {
1124
- if (logLevel <= _kubb_core.logLevel.silent) return;
1125
- state.totalFiles = files.length;
1126
- state.processedFiles = 0;
1127
- if (state.currentConfigs.length === 1) openGroup("File Generation");
1128
- const text = getMessage(`Writing ${files.length} files`);
1129
- console.log(text);
1130
- });
1131
- context.on("kubb:files:processing:end", () => {
1132
- if (logLevel <= _kubb_core.logLevel.silent) return;
1133
- const text = getMessage("Files written successfully");
1134
- console.log(text);
1135
- if (state.currentConfigs.length === 1) closeGroup("File Generation");
1136
- showProgressStep();
1137
- });
1138
- context.on("kubb:file:processing:update", () => {
1139
- if (logLevel <= _kubb_core.logLevel.silent) return;
1140
- state.processedFiles++;
1141
- });
1142
- context.on("kubb:generation:end", ({ config }) => {
1143
- const text = getMessage(config.name ? `${(0, node_util.styleText)("blue", "✓")} Generation completed for ${(0, node_util.styleText)("dim", config.name)}` : `${(0, node_util.styleText)("blue", "✓")} Generation completed`);
1144
- console.log(text);
1145
- });
1146
- context.on("kubb:format:start", () => {
1147
- if (logLevel <= _kubb_core.logLevel.silent) return;
1148
- const text = getMessage("Format started");
1149
- if (state.currentConfigs.length === 1) openGroup("Formatting");
1150
- console.log(text);
1151
- });
1152
- context.on("kubb:format:end", () => {
1153
- if (logLevel <= _kubb_core.logLevel.silent) return;
1154
- const text = getMessage("Format completed");
1155
- console.log(text);
1156
- if (state.currentConfigs.length === 1) closeGroup("Formatting");
1157
- });
1158
- context.on("kubb:lint:start", () => {
1159
- if (logLevel <= _kubb_core.logLevel.silent) return;
1160
- const text = getMessage("Lint started");
1161
- if (state.currentConfigs.length === 1) openGroup("Linting");
1162
- console.log(text);
1163
- });
1164
- context.on("kubb:lint:end", () => {
1165
- if (logLevel <= _kubb_core.logLevel.silent) return;
1166
- const text = getMessage("Lint completed");
1167
- console.log(text);
1168
- if (state.currentConfigs.length === 1) closeGroup("Linting");
1169
- });
1170
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1171
- const commandWithArgs = formatCommandWithArgs(command, args);
1172
- const text = getMessage(`Hook ${(0, node_util.styleText)("dim", commandWithArgs)} started`);
1173
- if (logLevel > _kubb_core.logLevel.silent) {
1174
- if (state.currentConfigs.length === 1) openGroup(`Hook ${commandWithArgs}`);
1175
- console.log(text);
1176
- }
1177
- if (!id) return;
1178
- await runHook({
1179
- id,
1180
- command,
1181
- args,
1182
- commandWithArgs,
1183
- context,
1184
- sink: {
1185
- onStdout: logLevel > _kubb_core.logLevel.silent ? (s) => console.log(s) : void 0,
1186
- onStderr: logLevel > _kubb_core.logLevel.silent ? (s) => console.error(`::error::${s}`) : void 0
1187
- }
1188
- });
1189
- });
1190
- context.on("kubb:hook:end", ({ command, args }) => {
1191
- if (logLevel <= _kubb_core.logLevel.silent) return;
1192
- const commandWithArgs = formatCommandWithArgs(command, args);
1193
- const text = getMessage(`Hook ${(0, node_util.styleText)("dim", commandWithArgs)} completed`);
1194
- console.log(text);
1195
- if (state.currentConfigs.length === 1) closeGroup(`Hook ${commandWithArgs}`);
1196
- });
1197
- context.on("kubb:generation:summary", ({ config, status, hrStart, failedPlugins }) => {
1198
- const pluginsCount = config.plugins?.length ?? 0;
1199
- const successCount = pluginsCount - failedPlugins.size;
1200
- const duration = formatHrtime(hrStart);
1201
- if (state.currentConfigs.length > 1) console.log(" ");
1202
- console.log(status === "success" ? `Kubb Summary: ${(0, node_util.styleText)("blue", "✓")} ${`${successCount} successful`}, ${pluginsCount} total, ${(0, node_util.styleText)("green", duration)}` : `Kubb Summary: ${(0, node_util.styleText)("blue", "✓")} ${`${successCount} successful`}, ✗ ${`${failedPlugins.size} failed`}, ${pluginsCount} total, ${(0, node_util.styleText)("green", duration)}`);
1203
- if (state.currentConfigs.length > 1) closeGroup(config.name ? `Generation for ${(0, node_util.styleText)("bold", config.name)}` : "Generation");
1204
- });
1205
- context.on("kubb:lifecycle:end", () => {
1206
- reset();
1207
- });
1208
- }
1209
- });
1210
- //#endregion
1211
- //#region src/loggers/plainLogger.ts
1212
- /**
1213
- * Plain console adapter for non-TTY environments with simple `console.log` output.
1214
- */
1215
- const plainLogger = (0, _kubb_core.defineLogger)({
1216
- name: "plain",
1217
- install(context, options) {
1218
- const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
1219
- function getMessage(message) {
1220
- return formatMessage(message, logLevel);
1221
- }
1222
- context.on("kubb:info", ({ message, info }) => {
1223
- if (logLevel <= _kubb_core.logLevel.silent) return;
1224
- const text = getMessage([
1225
- "ℹ",
1226
- message,
1227
- info
1228
- ].join(" "));
1229
- console.log(text);
1230
- });
1231
- context.on("kubb:success", ({ message, info = "" }) => {
1232
- if (logLevel <= _kubb_core.logLevel.silent) return;
1233
- const text = getMessage([
1234
- "✓",
1235
- message,
1236
- logLevel >= _kubb_core.logLevel.info ? info : void 0
1237
- ].filter(Boolean).join(" "));
1238
- console.log(text);
1239
- });
1240
- context.on("kubb:warn", ({ message, info }) => {
1241
- if (logLevel < _kubb_core.logLevel.warn) return;
1242
- const text = getMessage([
1243
- "⚠",
1244
- message,
1245
- logLevel >= _kubb_core.logLevel.info ? info : void 0
1246
- ].filter(Boolean).join(" "));
1247
- console.log(text);
1248
- });
1249
- context.on("kubb:error", ({ error }) => {
1250
- const caused = require_errors.toCause(error);
1251
- const text = getMessage(["✗", error.message].join(" "));
1252
- console.log(text);
1253
- if (logLevel >= _kubb_core.logLevel.debug && error.stack) {
1254
- const frames = error.stack.split("\n").slice(1, 4);
1255
- for (const frame of frames) console.log(getMessage(frame.trim()));
1256
- if (caused?.stack) {
1257
- console.log(`└─ caused by ${caused.message}`);
1258
- const frames = caused.stack.split("\n").slice(1, 4);
1259
- for (const frame of frames) console.log(getMessage(` ${frame.trim()}`));
1260
- }
1261
- }
1262
- });
1263
- context.on("kubb:lifecycle:start", () => {
1264
- console.log("Kubb CLI 🧩");
1265
- });
1266
- context.on("kubb:config:start", () => {
1267
- if (logLevel <= _kubb_core.logLevel.silent) return;
1268
- const text = getMessage("Configuration started");
1269
- console.log(text);
1270
- });
1271
- context.on("kubb:config:end", () => {
1272
- if (logLevel <= _kubb_core.logLevel.silent) return;
1273
- const text = getMessage("Configuration completed");
1274
- console.log(text);
1275
- });
1276
- context.on("kubb:generation:start", () => {
1277
- const text = getMessage("Generation started");
1278
- console.log(text);
1279
- });
1280
- context.on("kubb:plugin:start", ({ plugin }) => {
1281
- if (logLevel <= _kubb_core.logLevel.silent) return;
1282
- const text = getMessage(`Generating ${plugin.name}`);
1283
- console.log(text);
1284
- });
1285
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
1286
- if (logLevel <= _kubb_core.logLevel.silent) return;
1287
- const durationStr = formatMs(duration);
1288
- const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
1289
- console.log(text);
1290
- });
1291
- context.on("kubb:files:processing:start", ({ files }) => {
1292
- if (logLevel <= _kubb_core.logLevel.silent) return;
1293
- const text = getMessage(`Writing ${files.length} files`);
1294
- console.log(text);
1295
- });
1296
- context.on("kubb:file:processing:update", ({ file, config }) => {
1297
- if (logLevel <= _kubb_core.logLevel.silent) return;
1298
- const text = getMessage(`Writing ${(0, node_path.relative)(config.root, file.path)}`);
1299
- console.log(text);
1300
- });
1301
- context.on("kubb:files:processing:end", () => {
1302
- if (logLevel <= _kubb_core.logLevel.silent) return;
1303
- const text = getMessage("Files written successfully");
1304
- console.log(text);
1305
- });
1306
- context.on("kubb:generation:end", ({ config }) => {
1307
- const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
1308
- console.log(text);
1309
- });
1310
- context.on("kubb:format:start", () => {
1311
- if (logLevel <= _kubb_core.logLevel.silent) return;
1312
- const text = getMessage("Format started");
1313
- console.log(text);
1314
- });
1315
- context.on("kubb:format:end", () => {
1316
- if (logLevel <= _kubb_core.logLevel.silent) return;
1317
- const text = getMessage("Format completed");
1318
- console.log(text);
1319
- });
1320
- context.on("kubb:lint:start", () => {
1321
- if (logLevel <= _kubb_core.logLevel.silent) return;
1322
- const text = getMessage("Lint started");
1323
- console.log(text);
1324
- });
1325
- context.on("kubb:lint:end", () => {
1326
- if (logLevel <= _kubb_core.logLevel.silent) return;
1327
- const text = getMessage("Lint completed");
1328
- console.log(text);
1329
- });
1330
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1331
- const commandWithArgs = formatCommandWithArgs(command, args);
1332
- const text = getMessage(`Hook ${commandWithArgs} started`);
1333
- if (logLevel > _kubb_core.logLevel.silent) console.log(text);
1334
- if (!id) return;
1335
- await runHook({
1336
- id,
1337
- command,
1338
- args,
1339
- commandWithArgs,
1340
- context,
1341
- sink: {
1342
- onStdout: logLevel > _kubb_core.logLevel.silent ? (s) => console.log(s) : void 0,
1343
- onStderr: logLevel > _kubb_core.logLevel.silent ? (s) => console.error(s) : void 0
1344
- }
1345
- });
1346
- });
1347
- context.on("kubb:hook:end", ({ command, args }) => {
1348
- if (logLevel <= _kubb_core.logLevel.silent) return;
1349
- const text = getMessage(`Hook ${formatCommandWithArgs(command, args)} completed`);
1350
- console.log(text);
1351
- });
1352
- context.on("kubb:generation:summary", ({ config, pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {
1353
- const summary = getSummary({
1354
- failedPlugins,
1355
- filesCreated,
1356
- config,
1357
- status,
1358
- hrStart,
1359
- pluginTimings: logLevel >= _kubb_core.logLevel.verbose ? pluginTimings : void 0
1360
- });
1361
- console.log(require_constants.SUMMARY_SEPARATOR);
1362
- console.log(summary.join("\n"));
1363
- console.log(require_constants.SUMMARY_SEPARATOR);
1364
- });
1365
- }
1366
- });
1367
- //#endregion
1368
- //#region src/loggers/utils.ts
1369
- /**
1370
- * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
1371
- * Shared across all logger adapters to avoid duplication.
1372
- */
1373
- function formatMessage(message, logLevel) {
1374
- if (logLevel >= _kubb_core.logLevel.verbose) return `${(0, node_util.styleText)("dim", `[${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
1375
- hour12: false,
1376
- hour: "2-digit",
1377
- minute: "2-digit",
1378
- second: "2-digit"
1379
- })}]`)} ${message}`;
1380
- return message;
1381
- }
1382
- /**
1383
- * Build the progress summary line shared by clack and GitHub Actions loggers.
1384
- * Returns null when there is nothing to display.
1385
- */
1386
- function buildProgressLine(state) {
1387
- const parts = [];
1388
- const duration = formatHrtime(state.hrStart);
1389
- if (state.totalPlugins > 0) {
1390
- 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}`;
1391
- parts.push(pluginStr);
1392
- }
1393
- if (state.totalFiles > 0) parts.push(`Files ${(0, node_util.styleText)("green", state.processedFiles.toString())}/${state.totalFiles}`);
1394
- if (parts.length === 0) return null;
1395
- parts.push(`${(0, node_util.styleText)("green", duration)} elapsed`);
1396
- return parts.join((0, node_util.styleText)("dim", " | "));
1397
- }
1398
- /**
1399
- * Join a command and its optional args into a single display string.
1400
- * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
1401
- */
1402
- function formatCommandWithArgs(command, args) {
1403
- return args?.length ? `${command} ${args.join(" ")}` : command;
1404
- }
1405
- function detectLogger() {
1406
- if (require_telemetry.isGitHubActions()) return "github-actions";
1407
- if (require_telemetry.canUseTTY()) return "clack";
1408
- return "plain";
1409
- }
1410
- const logMapper = {
1411
- clack: clackLogger,
1412
- plain: plainLogger,
1413
- "github-actions": githubActionsLogger
1414
- };
1415
- async function setupLogger(context, { logLevel }) {
1416
- const type = detectLogger();
1417
- const logger = logMapper[type];
1418
- if (!logger) throw new Error(`Unknown adapter type: ${type}`);
1419
- const cleanup = await logger.install(context, { logLevel });
1420
- if (logLevel >= _kubb_core.logLevel.debug) await fileSystemLogger.install(context, { logLevel });
1421
- return cleanup;
1422
- }
1423
- //#endregion
1424
- //#region src/utils/executeHooks.ts
1425
- async function executeHooks({ configHooks, hooks }) {
1426
- const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
1427
- for (const command of commands) {
1428
- const [cmd, ...args] = require_shell.tokenize(command);
1429
- if (!cmd) continue;
1430
- const hookId = (0, node_crypto.createHash)("sha256").update(command).digest("hex");
1431
- const hookEndPromise = new Promise((resolve, reject) => {
1432
- const handler = (ctx) => {
1433
- if (ctx.id !== hookId) return;
1434
- hooks.off("kubb:hook:end", handler);
1435
- if (!ctx.success) {
1436
- reject(ctx.error ?? /* @__PURE__ */ new Error(`Hook failed: ${command}`));
1437
- return;
1438
- }
1439
- hooks.emit("kubb:success", { message: `${(0, node_util.styleText)("dim", command)} successfully executed` }).then(resolve).catch(reject);
1440
- };
1441
- hooks.on("kubb:hook:end", handler);
1442
- });
1443
- await hooks.emit("kubb:hook:start", {
1444
- id: hookId,
1445
- command: cmd,
1446
- args
1447
- });
1448
- await hookEndPromise;
1449
- }
1450
- }
1451
- //#endregion
1452
- //#region src/utils/getConfig.ts
1453
- async function getConfigs(config, args) {
1454
- const resolved = await (typeof config === "function" ? config(args) : config);
1455
- return (Array.isArray(resolved) ? resolved : [resolved]).map((item) => ({
1456
- ...item,
1457
- plugins: item.plugins ?? []
1458
- }));
1459
- }
1460
- //#endregion
1461
- //#region src/utils/getCosmiConfig.ts
1462
- const jiti$1 = (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
1463
- jsx: {
1464
- runtime: "automatic",
1465
- importSource: "@kubb/renderer-jsx"
1466
- },
1467
- moduleCache: false
1468
- });
1469
- const tsLoader = async (configFile) => {
1470
- return jiti$1.import(configFile, { default: true });
1471
- };
1472
- async function getCosmiConfig(moduleName, config) {
1473
- let result;
1474
- const searchPlaces = [
1475
- "package.json",
1476
- `.${moduleName}rc`,
1477
- `.${moduleName}rc.json`,
1478
- `.${moduleName}rc.yaml`,
1479
- `.${moduleName}rc.yml`,
1480
- `.${moduleName}rc.ts`,
1481
- `.${moduleName}rc.mts`,
1482
- `.${moduleName}rc.cts`,
1483
- `.${moduleName}rc.js`,
1484
- `.${moduleName}rc.mjs`,
1485
- `.${moduleName}rc.cjs`,
1486
- `${moduleName}.config.ts`,
1487
- `${moduleName}.config.mts`,
1488
- `${moduleName}.config.cts`,
1489
- `${moduleName}.config.js`,
1490
- `${moduleName}.config.mjs`,
1491
- `${moduleName}.config.cjs`
1492
- ];
1493
- const explorer = (0, cosmiconfig.cosmiconfig)(moduleName, {
1494
- cache: false,
1495
- searchPlaces: [
1496
- ...searchPlaces.map((searchPlace) => {
1497
- return `.config/${searchPlace}`;
1498
- }),
1499
- ...searchPlaces.map((searchPlace) => {
1500
- return `configs/${searchPlace}`;
1501
- }),
1502
- ...searchPlaces
1503
- ],
1504
- loaders: {
1505
- ".ts": tsLoader,
1506
- ".mts": tsLoader,
1507
- ".cts": tsLoader
1508
- }
1509
- });
1510
- try {
1511
- result = config ? await explorer.load(config) : await explorer.search();
1512
- } catch (error) {
1513
- throw new Error("Config failed loading", { cause: error });
1514
- }
1515
- if (result?.isEmpty || !result || !result.config) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
1516
- return result;
1517
- }
1518
- //#endregion
1519
- //#region src/utils/watcher.ts
1520
- async function startWatcher(path, cb) {
1521
- const { watch } = await import("chokidar");
1522
- watch(path, {
1523
- ignorePermissionErrors: true,
1524
- ignored: require_constants.WATCHER_IGNORED_PATHS
1525
- }).on("all", async (type, file) => {
1526
- console.log((0, node_util.styleText)("yellow", (0, node_util.styleText)("bold", `Change detected: ${type} ${file}`)));
1527
- try {
1528
- await cb(path);
1529
- } catch (_e) {
1530
- console.log((0, node_util.styleText)("red", "Watcher failed"));
1531
- }
1532
- });
1533
- }
1534
- //#endregion
1535
- //#region src/runners/generate.ts
1536
- async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel, hooks, onStart, onEnd }) {
1537
- await onStart();
1538
- let resolvedTool = toolValue;
1539
- if (resolvedTool === "auto") {
1540
- const detected = await detect();
1541
- if (!detected) await hooks.emit("kubb:warn", { message: noToolMessage });
1542
- else {
1543
- resolvedTool = detected;
1544
- await hooks.emit("kubb:info", { message: `Auto-detected ${toolLabel}: ${(0, node_util.styleText)("dim", resolvedTool)}` });
1545
- }
1546
- }
1547
- let toolError;
1548
- if (resolvedTool && resolvedTool !== "auto" && resolvedTool in toolMap) {
1549
- const toolConfig = toolMap[resolvedTool];
1550
- try {
1551
- const hookId = (0, node_crypto.createHash)("sha256").update([configName, resolvedTool].filter(Boolean).join("-")).digest("hex");
1552
- const hookEndPromise = new Promise((resolve, reject) => {
1553
- const handler = (ctx) => {
1554
- if (ctx.id !== hookId) return;
1555
- hooks.off("kubb:hook:end", handler);
1556
- if (!ctx.success) {
1557
- reject(ctx.error ?? /* @__PURE__ */ new Error(`${toolConfig.errorMessage}`));
1558
- return;
1559
- }
1560
- hooks.emit("kubb:success", { message: [
1561
- `${successPrefix} with ${(0, node_util.styleText)("dim", resolvedTool)}`,
1562
- logLevel >= _kubb_core.logLevel.info ? `on ${(0, node_util.styleText)("dim", outputPath)}` : void 0,
1563
- "successfully"
1564
- ].filter(Boolean).join(" ") }).then(resolve).catch(reject);
1565
- };
1566
- hooks.on("kubb:hook:end", handler);
1567
- });
1568
- await hooks.emit("kubb:hook:start", {
1569
- id: hookId,
1570
- command: toolConfig.command,
1571
- args: toolConfig.args(outputPath)
1572
- });
1573
- await hookEndPromise;
1574
- } catch (caughtError) {
1575
- const err = require_errors.toError(caughtError);
1576
- await hooks.emit("kubb:error", { error: err });
1577
- toolError = err;
1578
- }
1579
- }
1580
- await onEnd();
1581
- if (toolError) throw toolError;
1582
- }
1583
- async function generate(options) {
1584
- const { input, hooks, logLevel } = options;
1585
- const hrStart = node_process.default.hrtime();
1586
- const inputPath = input ?? (options.config.input && "path" in options.config.input ? options.config.input.path : void 0);
1587
- const config = {
1588
- ...options.config,
1589
- input: inputPath ? {
1590
- ...options.config.input,
1591
- path: inputPath
1592
- } : options.config.input,
1593
- ...options.config.output
1594
- };
1595
- const kubb = (0, _kubb_core.createKubb)(config, { hooks });
1596
- await kubb.setup();
1597
- await hooks.emit("kubb:generation:start", { config });
1598
- await hooks.emit("kubb:info", {
1599
- message: config.name ? `Setup generation ${(0, node_util.styleText)("bold", config.name)}` : "Setup generation",
1600
- info: inputPath
1601
- });
1602
- await hooks.emit("kubb:info", {
1603
- message: config.name ? `Build generation ${(0, node_util.styleText)("bold", config.name)}` : "Build generation",
1604
- info: inputPath
1605
- });
1606
- const { files, failedPlugins, pluginTimings, error, driver } = await kubb.safeBuild();
1607
- await hooks.emit("kubb:info", { message: "Load summary" });
1608
- if (failedPlugins.size > 0 || error) {
1609
- const allErrors = [error, ...Array.from(failedPlugins).filter((it) => it.error).map((it) => it.error)].filter(Boolean);
1610
- for (const err of allErrors) await hooks.emit("kubb:error", { error: err });
1611
- await hooks.emit("kubb:generation:end", {
1612
- config,
1613
- files,
1614
- sources: kubb.sources
1615
- });
1616
- await hooks.emit("kubb:generation:summary", {
1617
- config,
1618
- failedPlugins,
1619
- filesCreated: files.length,
1620
- status: "failed",
1621
- hrStart,
1622
- pluginTimings: logLevel >= _kubb_core.logLevel.verbose ? pluginTimings : void 0
1623
- });
1624
- await require_telemetry.sendTelemetry(require_telemetry.buildTelemetryEvent({
1625
- command: "generate",
1626
- kubbVersion: require_package.version,
1627
- plugins: Array.from(driver.plugins.values(), (p) => ({
1628
- name: p.name,
1629
- options: p.options
1630
- })),
1631
- hrStart,
1632
- filesCreated: files.length,
1633
- status: "failed"
1634
- }));
1635
- node_process.default.exit(1);
1636
- }
1637
- await hooks.emit("kubb:success", {
1638
- message: "Generation successfully",
1639
- info: inputPath
1640
- });
1641
- await hooks.emit("kubb:generation:end", {
1642
- config,
1643
- files,
1644
- sources: kubb.sources
1645
- });
1646
- const outputPath = node_path.default.resolve(config.root, config.output.path);
1647
- if (config.output.format) await runToolPass({
1648
- toolValue: config.output.format,
1649
- detect: detectFormatter,
1650
- toolMap: formatters,
1651
- toolLabel: "formatter",
1652
- successPrefix: "Formatting",
1653
- noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting.",
1654
- configName: config.name,
1655
- outputPath,
1656
- logLevel,
1657
- hooks,
1658
- onStart: () => hooks.emit("kubb:format:start"),
1659
- onEnd: () => hooks.emit("kubb:format:end")
1660
- });
1661
- if (config.output.lint) await runToolPass({
1662
- toolValue: config.output.lint,
1663
- detect: detectLinter,
1664
- toolMap: linters,
1665
- toolLabel: "linter",
1666
- successPrefix: "Linting",
1667
- noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting.",
1668
- configName: config.name,
1669
- outputPath,
1670
- logLevel,
1671
- hooks,
1672
- onStart: () => hooks.emit("kubb:lint:start"),
1673
- onEnd: () => hooks.emit("kubb:lint:end")
1674
- });
1675
- if (config.hooks) {
1676
- await hooks.emit("kubb:hooks:start");
1677
- await executeHooks({
1678
- configHooks: config.hooks,
1679
- hooks
1680
- });
1681
- await hooks.emit("kubb:hooks:end");
1682
- }
1683
- await hooks.emit("kubb:generation:summary", {
1684
- config,
1685
- failedPlugins,
1686
- filesCreated: files.length,
1687
- status: "success",
1688
- hrStart,
1689
- pluginTimings
1690
- });
1691
- await require_telemetry.sendTelemetry(require_telemetry.buildTelemetryEvent({
1692
- command: "generate",
1693
- kubbVersion: require_package.version,
1694
- plugins: Array.from(driver.plugins.values(), (p) => ({
1695
- name: p.name,
1696
- options: p.options
1697
- })),
1698
- hrStart,
1699
- filesCreated: files.length,
1700
- status: "success"
1701
- }));
1702
- }
1703
- async function runGenerateCommand({ input, configPath, logLevel: logLevelKey, watch }) {
1704
- const logLevel = _kubb_core.logLevel[logLevelKey] ?? _kubb_core.logLevel.info;
1705
- const hooks = new AsyncEventEmitter();
1706
- await setupLogger(hooks, { logLevel });
1707
- await require_telemetry.executeIfOnline(async () => {
1708
- try {
1709
- const latestVersion = (await (await fetch(require_constants.KUBB_NPM_PACKAGE_URL)).json()).version;
1710
- if (latestVersion && require_package.version < latestVersion) await hooks.emit("kubb:version:new", {
1711
- currentVersion: require_package.version,
1712
- latestVersion
1713
- });
1714
- } catch {}
1715
- });
1716
- try {
1717
- const result = await getCosmiConfig("kubb", configPath);
1718
- const configs = await getConfigs(result.config, { input });
1719
- await hooks.emit("kubb:config:start");
1720
- await hooks.emit("kubb:info", {
1721
- message: "Config loaded",
1722
- info: node_path.default.relative(node_process.default.cwd(), result.filepath)
1723
- });
1724
- await hooks.emit("kubb:success", {
1725
- message: "Config loaded successfully",
1726
- info: node_path.default.relative(node_process.default.cwd(), result.filepath)
1727
- });
1728
- await hooks.emit("kubb:config:end", { configs });
1729
- await hooks.emit("kubb:lifecycle:start", { version: require_package.version });
1730
- for (const config of configs) if ((0, _kubb_core.isInputPath)(config) && watch) await startWatcher([input || config.input.path], async (paths) => {
1731
- hooks.removeAll();
1732
- await generate({
1733
- input,
1734
- config,
1735
- logLevel,
1736
- hooks
1737
- });
1738
- _clack_prompts.log.step((0, node_util.styleText)("yellow", `Watching for changes in ${paths.join(" and ")}`));
1739
- });
1740
- else await generate({
1741
- input,
1742
- config,
1743
- logLevel,
1744
- hooks
1745
- });
1746
- await hooks.emit("kubb:lifecycle:end");
1747
- } catch (error) {
1748
- await hooks.emit("kubb:error", { error: require_errors.toError(error) });
1749
- node_process.default.exit(1);
1750
- }
1751
- }
1752
- //#endregion
1753
- exports.runGenerateCommand = runGenerateCommand;
1754
-
1755
- //# sourceMappingURL=generate-CUd1dUY5.cjs.map