@kubb/cli 5.0.0-beta.2 → 5.0.0-beta.20

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 (151) hide show
  1. package/README.md +177 -26
  2. package/dist/agent-CjtFcQSP.js +68 -0
  3. package/dist/agent-CjtFcQSP.js.map +1 -0
  4. package/dist/agent-ImlBMmqx.cjs +70 -0
  5. package/dist/agent-ImlBMmqx.cjs.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-BvFE5Tac.js} +1 -0
  7. package/dist/constants-B2JTeRBb.js +42 -0
  8. package/dist/constants-B2JTeRBb.js.map +1 -0
  9. package/dist/constants-BINTA5VZ.cjs +77 -0
  10. package/dist/constants-BINTA5VZ.cjs.map +1 -0
  11. package/dist/constants-BYGmiFs0.cjs +139 -0
  12. package/dist/constants-BYGmiFs0.cjs.map +1 -0
  13. package/dist/constants-DSJ-Xrbv.js +116 -0
  14. package/dist/constants-DSJ-Xrbv.js.map +1 -0
  15. package/dist/define-Bdn8j5VM.cjs.map +1 -1
  16. package/dist/{define-Ctii4bel.js → define-m_fp-Aqm.js} +2 -2
  17. package/dist/{define-Ctii4bel.js.map → define-m_fp-Aqm.js.map} +1 -1
  18. package/dist/{errors-CjPmyZHy.js → errors-CINO1EIv.js} +2 -2
  19. package/dist/{errors-CjPmyZHy.js.map → errors-CINO1EIv.js.map} +1 -1
  20. package/dist/errors-CLCjoSg0.cjs.map +1 -1
  21. package/dist/{generate-DL_7a7Wd.cjs → generate-BzD-zvO8.cjs} +10 -4
  22. package/dist/generate-BzD-zvO8.cjs.map +1 -0
  23. package/dist/{generate-B3PZ6Dp-.js → generate-DMjDB40_.js} +12 -6
  24. package/dist/generate-DMjDB40_.js.map +1 -0
  25. package/dist/index.cjs +20 -11
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +22 -13
  29. package/dist/index.js.map +1 -1
  30. package/dist/init-DSUkgcQb.js +53 -0
  31. package/dist/init-DSUkgcQb.js.map +1 -0
  32. package/dist/init-DTtYizXX.cjs +53 -0
  33. package/dist/init-DTtYizXX.cjs.map +1 -0
  34. package/dist/mcp-WXRUaZnw.cjs +39 -0
  35. package/dist/mcp-WXRUaZnw.cjs.map +1 -0
  36. package/dist/mcp-mW5bt29k.js +39 -0
  37. package/dist/mcp-mW5bt29k.js.map +1 -0
  38. package/dist/package-B1xAdhcK.js +6 -0
  39. package/dist/package-B1xAdhcK.js.map +1 -0
  40. package/dist/{package-D8wlStAg.cjs → package-CxbQOn_j.cjs} +2 -2
  41. package/dist/package-CxbQOn_j.cjs.map +1 -0
  42. package/dist/run-B11-UaUs.cjs +33 -0
  43. package/dist/run-B11-UaUs.cjs.map +1 -0
  44. package/dist/{init-eNRlotJK.js → run-BNqMQygv.js} +107 -149
  45. package/dist/run-BNqMQygv.js.map +1 -0
  46. package/dist/{generate-B3jl4ukb.cjs → run-BP_t4Z6z.cjs} +472 -397
  47. package/dist/run-BP_t4Z6z.cjs.map +1 -0
  48. package/dist/{init-CZ5Xq2Hd.cjs → run-BnGfi7Cp.cjs} +105 -147
  49. package/dist/run-BnGfi7Cp.cjs.map +1 -0
  50. package/dist/{agent-Ev5hU5hH.js → run-BzpYYOQs.js} +53 -44
  51. package/dist/run-BzpYYOQs.js.map +1 -0
  52. package/dist/run-CCZ24VKk.js +51 -0
  53. package/dist/run-CCZ24VKk.js.map +1 -0
  54. package/dist/{generate-Dt_r0ELY.js → run-CM9IkB_6.js} +475 -400
  55. package/dist/run-CM9IkB_6.js.map +1 -0
  56. package/dist/run-CQbj3ley.cjs +52 -0
  57. package/dist/run-CQbj3ley.cjs.map +1 -0
  58. package/dist/{agent-B_pirbeB.cjs → run-DwdAwnLG.cjs} +51 -42
  59. package/dist/run-DwdAwnLG.cjs.map +1 -0
  60. package/dist/run-PSA9X7ci.js +32 -0
  61. package/dist/run-PSA9X7ci.js.map +1 -0
  62. package/dist/shell-475fQKaX.cjs.map +1 -1
  63. package/dist/{shell-DLzN4fRo.js → shell-CN6DNqeC.js} +2 -2
  64. package/dist/{shell-DLzN4fRo.js.map → shell-CN6DNqeC.js.map} +1 -1
  65. package/dist/{telemetry-DN95_2pF.cjs → telemetry-B2iWkY5e.cjs} +5 -7
  66. package/dist/telemetry-B2iWkY5e.cjs.map +1 -0
  67. package/dist/{telemetry-LgT_sdPe.js → telemetry-BkektVz6.js} +6 -8
  68. package/dist/telemetry-BkektVz6.js.map +1 -0
  69. package/dist/validate-BQxNrR5z.js +26 -0
  70. package/dist/validate-BQxNrR5z.js.map +1 -0
  71. package/dist/validate-CvFVXmSa.cjs +26 -0
  72. package/dist/validate-CvFVXmSa.cjs.map +1 -0
  73. package/package.json +23 -15
  74. package/src/commands/agent/start.ts +10 -7
  75. package/src/commands/agent.ts +3 -1
  76. package/src/commands/generate.ts +5 -3
  77. package/src/commands/init.ts +34 -3
  78. package/src/commands/mcp.ts +28 -4
  79. package/src/commands/validate.ts +6 -4
  80. package/src/constants.ts +2 -58
  81. package/src/index.ts +5 -3
  82. package/src/loggers/clackLogger.ts +66 -72
  83. package/src/loggers/fileSystemLogger.ts +26 -13
  84. package/src/loggers/githubActionsLogger.ts +72 -26
  85. package/src/loggers/plainLogger.ts +51 -26
  86. package/src/loggers/types.ts +6 -0
  87. package/src/loggers/utils.ts +158 -9
  88. package/src/runners/agent/run.ts +113 -0
  89. package/src/runners/agent/utils.ts +98 -0
  90. package/src/runners/generate/run.ts +316 -0
  91. package/src/runners/generate/utils.ts +216 -0
  92. package/src/runners/init/run.ts +212 -0
  93. package/src/{utils/packageManager.ts → runners/init/utils.ts} +10 -0
  94. package/src/runners/mcp/run.ts +37 -0
  95. package/src/runners/validate/run.ts +63 -0
  96. package/src/{utils/telemetry.ts → telemetry.ts} +12 -5
  97. package/dist/agent-0Nk--lcr.cjs +0 -58
  98. package/dist/agent-0Nk--lcr.cjs.map +0 -1
  99. package/dist/agent-B_pirbeB.cjs.map +0 -1
  100. package/dist/agent-DKeVuiUC.js +0 -56
  101. package/dist/agent-DKeVuiUC.js.map +0 -1
  102. package/dist/agent-Ev5hU5hH.js.map +0 -1
  103. package/dist/constants-CnDXa1R6.cjs +0 -148
  104. package/dist/constants-CnDXa1R6.cjs.map +0 -1
  105. package/dist/constants-aL3CP_Wq.js +0 -95
  106. package/dist/constants-aL3CP_Wq.js.map +0 -1
  107. package/dist/generate-B3PZ6Dp-.js.map +0 -1
  108. package/dist/generate-B3jl4ukb.cjs.map +0 -1
  109. package/dist/generate-DL_7a7Wd.cjs.map +0 -1
  110. package/dist/generate-Dt_r0ELY.js.map +0 -1
  111. package/dist/init-Bj94Nvt8.js +0 -25
  112. package/dist/init-Bj94Nvt8.js.map +0 -1
  113. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  114. package/dist/init-CyN1oyTF.cjs +0 -25
  115. package/dist/init-CyN1oyTF.cjs.map +0 -1
  116. package/dist/init-eNRlotJK.js.map +0 -1
  117. package/dist/mcp-BzW703d7.js +0 -16
  118. package/dist/mcp-BzW703d7.js.map +0 -1
  119. package/dist/mcp-CLcDV4Jm.cjs +0 -41
  120. package/dist/mcp-CLcDV4Jm.cjs.map +0 -1
  121. package/dist/mcp-D7EIR9fR.js +0 -40
  122. package/dist/mcp-D7EIR9fR.js.map +0 -1
  123. package/dist/mcp-ZY-ONTOp.cjs +0 -16
  124. package/dist/mcp-ZY-ONTOp.cjs.map +0 -1
  125. package/dist/package-D8wlStAg.cjs.map +0 -1
  126. package/dist/package-Yo-9_m5C.js +0 -6
  127. package/dist/package-Yo-9_m5C.js.map +0 -1
  128. package/dist/telemetry-DN95_2pF.cjs.map +0 -1
  129. package/dist/telemetry-LgT_sdPe.js.map +0 -1
  130. package/dist/validate-Dplr99xO.js +0 -25
  131. package/dist/validate-Dplr99xO.js.map +0 -1
  132. package/dist/validate-_8mBa63G.cjs +0 -25
  133. package/dist/validate-_8mBa63G.cjs.map +0 -1
  134. package/dist/validate-kLJoT_hi.js +0 -33
  135. package/dist/validate-kLJoT_hi.js.map +0 -1
  136. package/dist/validate-yKKzqEZ5.cjs +0 -34
  137. package/dist/validate-yKKzqEZ5.cjs.map +0 -1
  138. package/src/runners/agent.ts +0 -149
  139. package/src/runners/generate.ts +0 -333
  140. package/src/runners/init.ts +0 -296
  141. package/src/runners/mcp.ts +0 -45
  142. package/src/runners/validate.ts +0 -39
  143. package/src/types.ts +0 -11
  144. package/src/utils/Writables.ts +0 -17
  145. package/src/utils/executeHooks.ts +0 -45
  146. package/src/utils/flags.ts +0 -9
  147. package/src/utils/getConfig.ts +0 -10
  148. package/src/utils/getCosmiConfig.ts +0 -80
  149. package/src/utils/getSummary.ts +0 -68
  150. package/src/utils/runHook.ts +0 -91
  151. package/src/utils/watcher.ts +0 -19
@@ -1,9 +1,9 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as toCause, r as toError } from "./errors-CjPmyZHy.js";
3
- import { a as canUseTTY, i as executeIfOnline, o as isGitHubActions, r as sendTelemetry, t as buildTelemetryEvent } from "./telemetry-LgT_sdPe.js";
4
- import { n as tokenize } from "./shell-DLzN4fRo.js";
5
- import { t as version } from "./package-Yo-9_m5C.js";
6
- import { a as SUMMARY_SEPARATOR, n as KUBB_NPM_PACKAGE_URL, o as WATCHER_IGNORED_PATHS } from "./constants-aL3CP_Wq.js";
1
+ import "./chunk-BvFE5Tac.js";
2
+ import { n as toCause, r as toError } from "./errors-CINO1EIv.js";
3
+ import { a as canUseTTY, i as executeIfOnline, o as isGitHubActions, r as sendTelemetry, t as buildTelemetryEvent } from "./telemetry-BkektVz6.js";
4
+ import { n as tokenize } from "./shell-CN6DNqeC.js";
5
+ import { t as version } from "./package-B1xAdhcK.js";
6
+ import { a as WATCHER_IGNORED_PATHS, i as SUMMARY_SEPARATOR, t as KUBB_NPM_PACKAGE_URL } from "./constants-B2JTeRBb.js";
7
7
  import { styleText } from "node:util";
8
8
  import { EventEmitter } from "node:events";
9
9
  import { createHash } from "node:crypto";
@@ -14,10 +14,9 @@ import path, { dirname, relative, resolve } from "node:path";
14
14
  import process$1 from "node:process";
15
15
  import * as clack from "@clack/prompts";
16
16
  import { createKubb, defineLogger, isInputPath, logLevel } from "@kubb/core";
17
- import { NonZeroExitError, x } from "tinyexec";
18
- import { Writable } from "node:stream";
19
17
  import { cosmiconfig } from "cosmiconfig";
20
- import { unrun } from "unrun";
18
+ import { createJiti } from "jiti";
19
+ import { NonZeroExitError, x } from "tinyexec";
21
20
  //#region ../../internals/utils/src/asyncEventEmitter.ts
22
21
  /**
23
22
  * Typed `EventEmitter` that awaits all async listeners before resolving.
@@ -48,9 +47,12 @@ var AsyncEventEmitter = class {
48
47
  * await emitter.emit('build', 'petstore')
49
48
  * ```
50
49
  */
51
- async emit(eventName, ...eventArgs) {
50
+ emit(eventName, ...eventArgs) {
52
51
  const listeners = this.#emitter.listeners(eventName);
53
52
  if (listeners.length === 0) return;
53
+ return this.#emitAll(eventName, listeners, eventArgs);
54
+ }
55
+ async #emitAll(eventName, listeners, eventArgs) {
54
56
  for (const listener of listeners) try {
55
57
  await listener(...eventArgs);
56
58
  } catch (err) {
@@ -486,112 +488,6 @@ async function detectLinter() {
486
488
  return null;
487
489
  }
488
490
  //#endregion
489
- //#region src/utils/getSummary.ts
490
- function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }) {
491
- const duration = formatHrtime(hrStart);
492
- const pluginsCount = config.plugins?.length ?? 0;
493
- const successCount = pluginsCount - failedPlugins.size;
494
- const meta = {
495
- plugins: status === "success" ? `${styleText("green", `${successCount} successful`)}, ${pluginsCount} total` : `${styleText("green", `${successCount} successful`)}, ${styleText("red", `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
496
- pluginsFailed: status === "failed" ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(", ") : void 0,
497
- filesCreated,
498
- time: styleText("green", duration),
499
- output: path.resolve(config.root, config.output.path)
500
- };
501
- const labels = {
502
- plugins: "Plugins:",
503
- failed: "Failed:",
504
- generated: "Generated:",
505
- pluginTimings: "Plugin Timings:",
506
- output: "Output:"
507
- };
508
- const maxLength = Math.max(0, ...[...Object.values(labels), ...pluginTimings ? Array.from(pluginTimings.keys()) : []].map((s) => s.length));
509
- const summaryLines = [];
510
- summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`);
511
- if (meta.pluginsFailed) summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`);
512
- summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`);
513
- if (pluginTimings && pluginTimings.size > 0) {
514
- const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1]);
515
- summaryLines.push(`${labels.pluginTimings}`);
516
- sortedTimings.forEach(([name, time]) => {
517
- const timeStr = time >= 1e3 ? `${(time / 1e3).toFixed(2)}s` : `${Math.round(time)}ms`;
518
- const barLength = Math.min(Math.ceil(time / 100), 10);
519
- const bar = styleText("dim", "█".repeat(barLength));
520
- summaryLines.push(`${styleText("dim", "•")} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`);
521
- });
522
- }
523
- summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`);
524
- return summaryLines;
525
- }
526
- //#endregion
527
- //#region src/utils/runHook.ts
528
- /**
529
- * Executes a hook command, emits debug and completion events, and forwards output to an optional sink.
530
- */
531
- async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }) {
532
- try {
533
- const proc = x(command, [...args ?? []], {
534
- nodeOptions: { detached: process.platform !== "win32" },
535
- throwOnError: true
536
- });
537
- if (stream && sink?.onLine) for await (const line of proc) sink.onLine(line);
538
- const result = await proc;
539
- await context.emit("kubb:debug", {
540
- date: /* @__PURE__ */ new Date(),
541
- logs: [result.stdout.trimEnd()]
542
- });
543
- await context.emit("kubb:hook:end", {
544
- command,
545
- args,
546
- id,
547
- success: true,
548
- error: null
549
- });
550
- } catch (err) {
551
- if (!(err instanceof NonZeroExitError)) {
552
- await context.emit("kubb:hook:end", {
553
- command,
554
- args,
555
- id,
556
- success: false,
557
- error: toError(err)
558
- });
559
- await context.emit("kubb:error", { error: toError(err) });
560
- return;
561
- }
562
- const stderr = err.output?.stderr ?? "";
563
- const stdout = err.output?.stdout ?? "";
564
- await context.emit("kubb:debug", {
565
- date: /* @__PURE__ */ new Date(),
566
- logs: [stdout, stderr].filter(Boolean)
567
- });
568
- if (stderr) sink?.onStderr?.(stderr);
569
- if (stdout) sink?.onStdout?.(stdout);
570
- const errorMessage = /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`);
571
- await context.emit("kubb:hook:end", {
572
- command,
573
- args,
574
- id,
575
- success: false,
576
- error: errorMessage
577
- });
578
- await context.emit("kubb:error", { error: errorMessage });
579
- }
580
- }
581
- //#endregion
582
- //#region src/utils/Writables.ts
583
- var ClackWritable = class extends Writable {
584
- taskLog;
585
- constructor(taskLog, opts) {
586
- super(opts);
587
- this.taskLog = taskLog;
588
- }
589
- _write(chunk, _encoding, callback) {
590
- this.taskLog.message(`${styleText("dim", chunk.toString())}`);
591
- callback();
592
- }
593
- };
594
- //#endregion
595
491
  //#region src/loggers/clackLogger.ts
596
492
  /**
597
493
  * TTY logger with beautiful UI and progress indicators for local development.
@@ -609,7 +505,8 @@ const clackLogger = defineLogger({
609
505
  hrStart: process$1.hrtime(),
610
506
  spinner: clack.spinner(),
611
507
  isSpinning: false,
612
- activeProgress: /* @__PURE__ */ new Map()
508
+ activeProgress: /* @__PURE__ */ new Map(),
509
+ activeHookLogs: /* @__PURE__ */ new Map()
613
510
  };
614
511
  function reset() {
615
512
  for (const [_key, active] of state.activeProgress) {
@@ -625,6 +522,7 @@ const clackLogger = defineLogger({
625
522
  state.spinner = clack.spinner();
626
523
  state.isSpinning = false;
627
524
  state.activeProgress.clear();
525
+ state.activeHookLogs.clear();
628
526
  }
629
527
  function showProgressStep() {
630
528
  if (logLevel$8 <= logLevel.silent) return;
@@ -639,6 +537,7 @@ const clackLogger = defineLogger({
639
537
  state.isSpinning = true;
640
538
  }
641
539
  function stopSpinner(text) {
540
+ if (!state.isSpinning) return;
642
541
  state.spinner.stop(text);
643
542
  state.isSpinning = false;
644
543
  }
@@ -649,8 +548,11 @@ const clackLogger = defineLogger({
649
548
  message,
650
549
  styleText("dim", info)
651
550
  ].join(" "));
652
- if (state.isSpinning) state.spinner.message(text);
653
- else clack.log.info(text);
551
+ if (state.isSpinning) {
552
+ state.spinner.message(text);
553
+ return;
554
+ }
555
+ clack.log.info(text);
654
556
  });
655
557
  context.on("kubb:success", ({ message, info = "" }) => {
656
558
  if (logLevel$8 <= logLevel.silent) return;
@@ -659,8 +561,11 @@ const clackLogger = defineLogger({
659
561
  message,
660
562
  logLevel$8 >= logLevel.info ? styleText("dim", info) : void 0
661
563
  ].filter(Boolean).join(" "));
662
- if (state.isSpinning) stopSpinner(text);
663
- else clack.log.success(text);
564
+ if (state.isSpinning) {
565
+ stopSpinner(text);
566
+ return;
567
+ }
568
+ clack.log.success(text);
664
569
  });
665
570
  context.on("kubb:warn", ({ message, info }) => {
666
571
  if (logLevel$8 < logLevel.warn) return;
@@ -674,8 +579,11 @@ const clackLogger = defineLogger({
674
579
  context.on("kubb:error", ({ error }) => {
675
580
  const caused = toCause(error);
676
581
  const text = [styleText("red", "✗"), error.message].join(" ");
677
- if (state.isSpinning) stopSpinner(getMessage(text));
678
- else clack.log.error(getMessage(text));
582
+ if (state.isSpinning) {
583
+ stopSpinner(getMessage(text));
584
+ return;
585
+ }
586
+ clack.log.error(getMessage(text));
679
587
  if (logLevel$8 >= logLevel.debug && error.stack) {
680
588
  const frames = error.stack.split("\n").slice(1, 4);
681
589
  for (const frame of frames) clack.log.message(getMessage(styleText("dim", frame.trim())));
@@ -726,6 +634,7 @@ Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
726
634
  context.on("kubb:generation:start", ({ config }) => {
727
635
  reset();
728
636
  state.totalPlugins = config.plugins?.length ?? 0;
637
+ if (logLevel$8 <= logLevel.silent) return;
729
638
  const text = getMessage(["Generation started", config.name ? `for ${styleText("dim", config.name)}` : void 0].filter(Boolean).join(" "));
730
639
  clack.intro(text);
731
640
  });
@@ -795,68 +704,44 @@ Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
795
704
  showProgressStep();
796
705
  });
797
706
  context.on("kubb:generation:end", ({ config }) => {
707
+ stopSpinner();
798
708
  const text = getMessage(config.name ? `Generation completed for ${styleText("dim", config.name)}` : "Generation completed");
799
709
  clack.outro(text);
800
710
  });
801
711
  context.on("kubb:format:start", () => {
802
712
  if (logLevel$8 <= logLevel.silent) return;
803
- const text = getMessage("Format started");
804
- clack.intro(text);
805
- });
806
- context.on("kubb:format:end", () => {
807
- if (logLevel$8 <= logLevel.silent) return;
808
- const text = getMessage("Format completed");
809
- clack.outro(text);
713
+ clack.log.step(getMessage("Formatting"));
810
714
  });
811
715
  context.on("kubb:lint:start", () => {
812
716
  if (logLevel$8 <= logLevel.silent) return;
813
- const text = getMessage("Lint started");
814
- clack.intro(text);
717
+ clack.log.step(getMessage("Linting"));
815
718
  });
816
- context.on("kubb:lint:end", () => {
719
+ context.on("kubb:hooks:start", () => {
817
720
  if (logLevel$8 <= logLevel.silent) return;
818
- const text = getMessage("Lint completed");
819
- clack.outro(text);
721
+ clack.log.step(getMessage("Running hooks"));
820
722
  });
821
- context.on("kubb:hook:start", async ({ id, command, args }) => {
822
- const commandWithArgs = formatCommandWithArgs(command, args);
823
- const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} started`);
824
- if (!id) return;
825
- if (logLevel$8 <= logLevel.silent) {
826
- await runHook({
827
- id,
828
- command,
829
- args,
830
- commandWithArgs,
831
- context,
832
- sink: {
833
- onStderr: (s) => console.error(s),
834
- onStdout: (s) => console.log(s)
835
- }
836
- });
837
- return;
838
- }
839
- clack.intro(text);
840
- const logger = clack.taskLog({ title: getMessage(["Executing hook", logLevel$8 >= logLevel.info ? styleText("dim", commandWithArgs) : void 0].filter(Boolean).join(" ")) });
841
- const writable = new ClackWritable(logger);
842
- await runHook({
843
- id,
844
- command,
845
- args,
846
- commandWithArgs,
847
- context,
848
- stream: true,
849
- sink: {
850
- onLine: (line) => writable.write(line),
851
- onStderr: (s) => logger.error(s),
852
- onStdout: (s) => logger.message(s)
853
- }
723
+ context.on("kubb:hook:start", ({ id, command, args }) => {
724
+ if (logLevel$8 <= logLevel.silent || !id) return;
725
+ stopSpinner();
726
+ const title = getMessage(`Running ${styleText("dim", formatCommandWithArgs(command, args))}`);
727
+ const taskLog = clack.taskLog({ title });
728
+ state.activeHookLogs.set(id, {
729
+ taskLog,
730
+ hrStart: process$1.hrtime()
854
731
  });
855
732
  });
856
- context.on("kubb:hook:end", ({ command, args }) => {
857
- if (logLevel$8 <= logLevel.silent) return;
858
- const text = getMessage(`Hook ${styleText("dim", formatCommandWithArgs(command, args))} successfully executed`);
859
- clack.outro(text);
733
+ context.on("kubb:hook:end", ({ id, command, args, success, error }) => {
734
+ if (logLevel$8 <= logLevel.silent || !id) return;
735
+ const active = state.activeHookLogs.get(id);
736
+ if (!active) return;
737
+ state.activeHookLogs.delete(id);
738
+ const commandWithArgs = formatCommandWithArgs(command, args);
739
+ const duration = formatMsWithColor(getElapsedMs(active.hrStart));
740
+ if (success) active.taskLog.success(getMessage(`${styleText("dim", commandWithArgs)} completed in ${duration}`));
741
+ else {
742
+ const reason = error?.message ? ` (${error.message})` : "";
743
+ active.taskLog.error(getMessage(`${styleText("dim", commandWithArgs)} failed${reason}`), { showLog: true });
744
+ }
860
745
  });
861
746
  context.on("kubb:generation:summary", ({ config, pluginTimings, failedPlugins, filesCreated, status, hrStart }) => {
862
747
  const summary = getSummary({
@@ -887,13 +772,29 @@ Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
887
772
  context.on("kubb:lifecycle:end", () => {
888
773
  reset();
889
774
  });
775
+ return (_commandWithArgs, hookId) => {
776
+ if (logLevel$8 <= logLevel.silent) return {
777
+ onStdout: (s) => console.log(s),
778
+ onStderr: (s) => console.error(s)
779
+ };
780
+ const active = state.activeHookLogs.get(hookId);
781
+ if (!active) return;
782
+ const { taskLog } = active;
783
+ return {
784
+ stream: true,
785
+ onLine: (line) => taskLog.message(styleText("dim", line)),
786
+ onStdout: (s) => taskLog.message(s),
787
+ onStderr: (s) => taskLog.message(styleText("red", s))
788
+ };
789
+ };
890
790
  }
891
791
  });
892
792
  //#endregion
893
793
  //#region src/loggers/fileSystemLogger.ts
894
794
  /**
895
795
  * FileSystem logger that captures debug events and writes them to `.kubb` directory files.
896
- * Note: Logs write on `lifecycle:end` or process exit. Cached logs may be lost if the process crashes before these events.
796
+ *
797
+ * @note Logs are written on `kubb:lifecycle:end` or process exit. Cached logs may be lost if the process crashes before either event.
897
798
  */
898
799
  const fileSystemLogger = defineLogger({
899
800
  name: "filesystem",
@@ -918,29 +819,31 @@ const fileSystemLogger = defineLogger({
918
819
  const pathName = resolve(process$1.cwd(), ".kubb", baseName);
919
820
  if (!files[pathName]) files[pathName] = [];
920
821
  if (log.logs.length > 0) {
921
- const timestamp = log.date.toLocaleString();
922
- files[pathName].push(`[${timestamp}]\n${log.logs.join("\n")}`);
822
+ const prefix = `[${log.date.toLocaleString()}] `;
823
+ const indent = " ".repeat(prefix.length);
824
+ const [first, ...rest] = log.logs;
825
+ files[pathName].push([prefix + first, ...rest.map((line) => indent + line)].join("\n"));
923
826
  }
924
827
  }
925
- for (const [fileName, logs] of Object.entries(files)) await write(fileName, logs.join("\n\n"));
828
+ for (const [fileName, logs] of Object.entries(files)) await write(fileName, logs.join("\n"));
926
829
  return Object.keys(files);
927
830
  }
928
831
  context.on("kubb:info", ({ message, info }) => {
929
832
  state.cachedLogs.add({
930
833
  date: /* @__PURE__ */ new Date(),
931
- logs: [`ℹ ${message} ${info}`]
834
+ logs: [`ℹ ${[message, info].filter(Boolean).join(" ")}`]
932
835
  });
933
836
  });
934
837
  context.on("kubb:success", ({ message, info }) => {
935
838
  state.cachedLogs.add({
936
839
  date: /* @__PURE__ */ new Date(),
937
- logs: [`✓ ${message} ${info}`]
840
+ logs: [`✓ ${[message, info].filter(Boolean).join(" ")}`]
938
841
  });
939
842
  });
940
843
  context.on("kubb:warn", ({ message, info }) => {
941
844
  state.cachedLogs.add({
942
845
  date: /* @__PURE__ */ new Date(),
943
- logs: [`⚠ ${message} ${info}`]
846
+ logs: [`⚠ ${[message, info].filter(Boolean).join(" ")}`]
944
847
  });
945
848
  });
946
849
  context.on("kubb:error", ({ error }) => {
@@ -949,29 +852,30 @@ const fileSystemLogger = defineLogger({
949
852
  logs: [`✗ ${error.message}`, error.stack || "unknown stack"]
950
853
  });
951
854
  });
952
- context.on("kubb:debug", (message) => {
855
+ context.on("kubb:debug", ({ date, fileName, logs }) => {
953
856
  state.cachedLogs.add({
954
- date: /* @__PURE__ */ new Date(),
955
- logs: message.logs
857
+ date,
858
+ fileName,
859
+ logs
956
860
  });
957
861
  });
958
862
  context.on("kubb:plugin:start", ({ plugin }) => {
959
863
  state.cachedLogs.add({
960
864
  date: /* @__PURE__ */ new Date(),
961
- logs: [`Generating ${plugin.name}`]
865
+ logs: [`► Generating ${plugin.name}`]
962
866
  });
963
867
  });
964
868
  context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
965
869
  const durationStr = formatMs(duration);
966
870
  state.cachedLogs.add({
967
871
  date: /* @__PURE__ */ new Date(),
968
- logs: [success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`]
872
+ logs: [success ? `✓ ${plugin.name} completed in ${durationStr}` : `✗ ${plugin.name} failed in ${durationStr}`]
969
873
  });
970
874
  });
971
875
  context.on("kubb:files:processing:start", ({ files }) => {
972
876
  state.cachedLogs.add({
973
877
  date: /* @__PURE__ */ new Date(),
974
- logs: [`Start ${files.length} writing:`, ...files.map((file) => file.path)]
878
+ logs: [`► Writing ${files.length} files`, ...files.map((file) => ` ${file.path}`)]
975
879
  });
976
880
  });
977
881
  context.on("kubb:generation:end", async ({ config }) => {
@@ -1008,17 +912,21 @@ const githubActionsLogger = defineLogger({
1008
912
  failedPlugins: 0,
1009
913
  totalFiles: 0,
1010
914
  processedFiles: 0,
1011
- hrStart: process.hrtime(),
1012
- currentConfigs: []
915
+ hrStart: process$1.hrtime(),
916
+ currentConfigs: [],
917
+ hookStarts: /* @__PURE__ */ new Map(),
918
+ openGroupDepth: 0
1013
919
  };
1014
920
  function reset() {
921
+ closeAllGroups();
1015
922
  state.totalPlugins = 0;
1016
923
  state.completedPlugins = 0;
1017
924
  state.failedPlugins = 0;
1018
925
  state.totalFiles = 0;
1019
926
  state.processedFiles = 0;
1020
- state.hrStart = process.hrtime();
927
+ state.hrStart = process$1.hrtime();
1021
928
  state.currentConfigs = [];
929
+ state.hookStarts.clear();
1022
930
  }
1023
931
  function showProgressStep() {
1024
932
  if (logLevel$7 <= logLevel.silent) return;
@@ -1030,9 +938,17 @@ const githubActionsLogger = defineLogger({
1030
938
  }
1031
939
  function openGroup(name) {
1032
940
  console.log(`::group::${name}`);
941
+ state.openGroupDepth++;
1033
942
  }
1034
943
  function closeGroup(_name) {
1035
944
  console.log("::endgroup::");
945
+ if (state.openGroupDepth > 0) state.openGroupDepth--;
946
+ }
947
+ function closeAllGroups() {
948
+ while (state.openGroupDepth > 0) {
949
+ console.log("::endgroup::");
950
+ state.openGroupDepth--;
951
+ }
1036
952
  }
1037
953
  context.on("kubb:info", ({ message, info = "" }) => {
1038
954
  if (logLevel$7 <= logLevel.silent) return;
@@ -1063,6 +979,7 @@ const githubActionsLogger = defineLogger({
1063
979
  });
1064
980
  context.on("kubb:error", ({ error }) => {
1065
981
  const caused = toCause(error);
982
+ closeAllGroups();
1066
983
  if (logLevel$7 <= logLevel.silent) return;
1067
984
  const message = error.message || String(error);
1068
985
  console.error(`::error::${message}`);
@@ -1080,6 +997,9 @@ const githubActionsLogger = defineLogger({
1080
997
  console.log(styleText("yellow", `Kubb ${version} 🧩`));
1081
998
  reset();
1082
999
  });
1000
+ context.on("kubb:version:new", ({ currentVersion, latestVersion }) => {
1001
+ console.log(`::notice::Update available for Kubb: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`);
1002
+ });
1083
1003
  context.on("kubb:config:start", () => {
1084
1004
  if (logLevel$7 <= logLevel.silent) return;
1085
1005
  const text = getMessage("Configuration started");
@@ -1164,31 +1084,35 @@ const githubActionsLogger = defineLogger({
1164
1084
  console.log(text);
1165
1085
  if (state.currentConfigs.length === 1) closeGroup("Linting");
1166
1086
  });
1167
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1087
+ context.on("kubb:hooks:start", () => {
1088
+ if (logLevel$7 <= logLevel.silent) return;
1089
+ if (state.currentConfigs.length === 1) openGroup("Hooks");
1090
+ console.log(getMessage("Hooks started"));
1091
+ });
1092
+ context.on("kubb:hooks:end", () => {
1093
+ if (logLevel$7 <= logLevel.silent) return;
1094
+ console.log(getMessage("Hooks completed"));
1095
+ if (state.currentConfigs.length === 1) closeGroup("Hooks");
1096
+ });
1097
+ context.on("kubb:hook:start", ({ id, command, args }) => {
1098
+ if (logLevel$7 <= logLevel.silent) return;
1099
+ if (id) state.hookStarts.set(id, process$1.hrtime());
1168
1100
  const commandWithArgs = formatCommandWithArgs(command, args);
1169
1101
  const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} started`);
1170
- if (logLevel$7 > logLevel.silent) {
1171
- if (state.currentConfigs.length === 1) openGroup(`Hook ${commandWithArgs}`);
1172
- console.log(text);
1173
- }
1174
- if (!id) return;
1175
- await runHook({
1176
- id,
1177
- command,
1178
- args,
1179
- commandWithArgs,
1180
- context,
1181
- sink: {
1182
- onStdout: logLevel$7 > logLevel.silent ? (s) => console.log(s) : void 0,
1183
- onStderr: logLevel$7 > logLevel.silent ? (s) => console.error(`::error::${s}`) : void 0
1184
- }
1185
- });
1102
+ if (state.currentConfigs.length === 1) openGroup(`Hook ${commandWithArgs}`);
1103
+ console.log(text);
1186
1104
  });
1187
- context.on("kubb:hook:end", ({ command, args }) => {
1105
+ context.on("kubb:hook:end", ({ id, command, args, success, error }) => {
1188
1106
  if (logLevel$7 <= logLevel.silent) return;
1107
+ const hrStart = id ? state.hookStarts.get(id) : void 0;
1108
+ if (id) state.hookStarts.delete(id);
1109
+ const durationStr = hrStart ? ` in ${formatMsWithColor(getElapsedMs(hrStart))}` : "";
1189
1110
  const commandWithArgs = formatCommandWithArgs(command, args);
1190
- const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} completed`);
1191
- console.log(text);
1111
+ if (success) console.log(getMessage(`${styleText("green", "✓")} Hook ${styleText("dim", commandWithArgs)} completed${durationStr}`));
1112
+ else {
1113
+ const reason = error?.message ? ` (${error.message})` : "";
1114
+ console.log(`::error::Hook ${commandWithArgs} failed${durationStr}${reason}`);
1115
+ }
1192
1116
  if (state.currentConfigs.length === 1) closeGroup(`Hook ${commandWithArgs}`);
1193
1117
  });
1194
1118
  context.on("kubb:generation:summary", ({ config, status, hrStart, failedPlugins }) => {
@@ -1202,6 +1126,10 @@ const githubActionsLogger = defineLogger({
1202
1126
  context.on("kubb:lifecycle:end", () => {
1203
1127
  reset();
1204
1128
  });
1129
+ return (_commandWithArgs, _hookId) => ({
1130
+ onStdout: logLevel$7 > logLevel.silent ? (s) => console.log(s) : void 0,
1131
+ onStderr: logLevel$7 > logLevel.silent ? (s) => console.error(`::error::${s}`) : void 0
1132
+ });
1205
1133
  }
1206
1134
  });
1207
1135
  //#endregion
@@ -1213,6 +1141,7 @@ const plainLogger = defineLogger({
1213
1141
  name: "plain",
1214
1142
  install(context, options) {
1215
1143
  const logLevel$6 = options?.logLevel ?? logLevel.info;
1144
+ const hookStarts = /* @__PURE__ */ new Map();
1216
1145
  function getMessage(message) {
1217
1146
  return formatMessage(message, logLevel$6);
1218
1147
  }
@@ -1257,8 +1186,12 @@ const plainLogger = defineLogger({
1257
1186
  }
1258
1187
  }
1259
1188
  });
1260
- context.on("kubb:lifecycle:start", () => {
1261
- console.log("Kubb CLI 🧩");
1189
+ context.on("kubb:lifecycle:start", ({ version }) => {
1190
+ console.log(`Kubb CLI v${version}`);
1191
+ });
1192
+ context.on("kubb:version:new", ({ currentVersion, latestVersion }) => {
1193
+ if (logLevel$6 <= logLevel.silent) return;
1194
+ console.log(getMessage(`Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`));
1262
1195
  });
1263
1196
  context.on("kubb:config:start", () => {
1264
1197
  if (logLevel$6 <= logLevel.silent) return;
@@ -1324,27 +1257,31 @@ const plainLogger = defineLogger({
1324
1257
  const text = getMessage("Lint completed");
1325
1258
  console.log(text);
1326
1259
  });
1327
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1260
+ context.on("kubb:hooks:start", () => {
1261
+ if (logLevel$6 <= logLevel.silent) return;
1262
+ console.log(getMessage("Hooks started"));
1263
+ });
1264
+ context.on("kubb:hooks:end", () => {
1265
+ if (logLevel$6 <= logLevel.silent) return;
1266
+ console.log(getMessage("Hooks completed"));
1267
+ });
1268
+ context.on("kubb:hook:start", ({ id, command, args }) => {
1269
+ if (logLevel$6 <= logLevel.silent) return;
1270
+ if (id) hookStarts.set(id, process$1.hrtime());
1328
1271
  const commandWithArgs = formatCommandWithArgs(command, args);
1329
- const text = getMessage(`Hook ${commandWithArgs} started`);
1330
- if (logLevel$6 > logLevel.silent) console.log(text);
1331
- if (!id) return;
1332
- await runHook({
1333
- id,
1334
- command,
1335
- args,
1336
- commandWithArgs,
1337
- context,
1338
- sink: {
1339
- onStdout: logLevel$6 > logLevel.silent ? (s) => console.log(s) : void 0,
1340
- onStderr: logLevel$6 > logLevel.silent ? (s) => console.error(s) : void 0
1341
- }
1342
- });
1272
+ console.log(getMessage(`Hook ${commandWithArgs} started`));
1343
1273
  });
1344
- context.on("kubb:hook:end", ({ command, args }) => {
1274
+ context.on("kubb:hook:end", ({ id, command, args, success, error }) => {
1345
1275
  if (logLevel$6 <= logLevel.silent) return;
1346
- const text = getMessage(`Hook ${formatCommandWithArgs(command, args)} completed`);
1347
- console.log(text);
1276
+ const hrStart = id ? hookStarts.get(id) : void 0;
1277
+ if (id) hookStarts.delete(id);
1278
+ const durationStr = hrStart ? ` in ${formatMs(getElapsedMs(hrStart))}` : "";
1279
+ const commandWithArgs = formatCommandWithArgs(command, args);
1280
+ if (success) console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`));
1281
+ else {
1282
+ const reason = error?.message ? ` (${error.message})` : "";
1283
+ console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`));
1284
+ }
1348
1285
  });
1349
1286
  context.on("kubb:generation:summary", ({ config, pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {
1350
1287
  const summary = getSummary({
@@ -1359,6 +1296,10 @@ const plainLogger = defineLogger({
1359
1296
  console.log(summary.join("\n"));
1360
1297
  console.log(SUMMARY_SEPARATOR);
1361
1298
  });
1299
+ return (_commandWithArgs, _hookId) => ({
1300
+ onStdout: logLevel$6 > logLevel.silent ? (s) => console.log(s) : void 0,
1301
+ onStderr: logLevel$6 > logLevel.silent ? (s) => console.error(s) : void 0
1302
+ });
1362
1303
  }
1363
1304
  });
1364
1305
  //#endregion
@@ -1413,125 +1354,241 @@ async function setupLogger(context, { logLevel: logLevel$5 }) {
1413
1354
  const type = detectLogger();
1414
1355
  const logger = logMapper[type];
1415
1356
  if (!logger) throw new Error(`Unknown adapter type: ${type}`);
1416
- const cleanup = await logger.install(context, { logLevel: logLevel$5 });
1357
+ const makeSink = await logger.install(context, { logLevel: logLevel$5 });
1417
1358
  if (logLevel$5 >= logLevel.debug) await fileSystemLogger.install(context, { logLevel: logLevel$5 });
1418
- return cleanup;
1359
+ return typeof makeSink === "function" ? makeSink : void 0;
1419
1360
  }
1420
- //#endregion
1421
- //#region src/utils/executeHooks.ts
1422
- async function executeHooks({ configHooks, hooks }) {
1423
- const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
1424
- for (const command of commands) {
1425
- const [cmd, ...args] = tokenize(command);
1426
- if (!cmd) continue;
1427
- const hookId = createHash("sha256").update(command).digest("hex");
1428
- const hookEndPromise = new Promise((resolve, reject) => {
1429
- const handler = (ctx) => {
1430
- if (ctx.id !== hookId) return;
1431
- hooks.off("kubb:hook:end", handler);
1432
- if (!ctx.success) {
1433
- reject(ctx.error ?? /* @__PURE__ */ new Error(`Hook failed: ${command}`));
1434
- return;
1435
- }
1436
- hooks.emit("kubb:success", { message: `${styleText("dim", command)} successfully executed` }).then(resolve).catch(reject);
1437
- };
1438
- hooks.on("kubb:hook:end", handler);
1439
- });
1440
- await hooks.emit("kubb:hook:start", {
1441
- id: hookId,
1442
- command: cmd,
1443
- args
1361
+ /**
1362
+ * Builds the generation summary lines rendered in the end-of-run box.
1363
+ * Returns an array of styled strings, one per summary row.
1364
+ */
1365
+ function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }) {
1366
+ const duration = formatHrtime(hrStart);
1367
+ const pluginsCount = config.plugins?.length ?? 0;
1368
+ const successCount = pluginsCount - failedPlugins.size;
1369
+ const meta = {
1370
+ plugins: status === "success" ? `${styleText("green", `${successCount} successful`)}, ${pluginsCount} total` : `${styleText("green", `${successCount} successful`)}, ${styleText("red", `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
1371
+ pluginsFailed: status === "failed" ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(", ") : void 0,
1372
+ filesCreated,
1373
+ time: styleText("green", duration),
1374
+ output: path.resolve(config.root, config.output.path)
1375
+ };
1376
+ const labels = {
1377
+ plugins: "Plugins:",
1378
+ failed: "Failed:",
1379
+ generated: "Generated:",
1380
+ pluginTimings: "Plugin Timings:",
1381
+ output: "Output:"
1382
+ };
1383
+ const maxLength = Math.max(0, ...[...Object.values(labels), ...pluginTimings ? Array.from(pluginTimings.keys()) : []].map((s) => s.length));
1384
+ const summaryLines = [];
1385
+ summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`);
1386
+ if (meta.pluginsFailed) summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`);
1387
+ summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`);
1388
+ if (pluginTimings && pluginTimings.size > 0) {
1389
+ const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1]);
1390
+ summaryLines.push(`${labels.pluginTimings}`);
1391
+ sortedTimings.forEach(([name, time]) => {
1392
+ const timeStr = time >= 1e3 ? `${(time / 1e3).toFixed(2)}s` : `${Math.round(time)}ms`;
1393
+ const barLength = Math.min(Math.ceil(time / 100), 10);
1394
+ const bar = styleText("dim", "█".repeat(barLength));
1395
+ summaryLines.push(`${styleText("dim", "•")} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`);
1444
1396
  });
1445
- await hookEndPromise;
1446
1397
  }
1398
+ summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`);
1399
+ return summaryLines;
1447
1400
  }
1448
1401
  //#endregion
1449
- //#region src/utils/getConfig.ts
1450
- async function getConfigs(config, args) {
1451
- const resolved = await (typeof config === "function" ? config(args) : config);
1452
- return (Array.isArray(resolved) ? resolved : [resolved]).map((item) => ({
1453
- ...item,
1454
- plugins: item.plugins ?? []
1455
- }));
1456
- }
1457
- //#endregion
1458
- //#region src/utils/getCosmiConfig.ts
1459
- const unrunInputOptions = { transform: { jsx: {
1460
- runtime: "automatic",
1461
- importSource: "@kubb/renderer-jsx"
1462
- } } };
1463
- const tsLoader = async (configFile) => {
1464
- const { module } = await unrun({
1465
- path: configFile,
1466
- inputOptions: unrunInputOptions
1467
- });
1468
- return module;
1469
- };
1470
- async function getCosmiConfig(moduleName, config) {
1471
- let result;
1472
- const searchPlaces = [
1473
- "package.json",
1474
- `.${moduleName}rc`,
1475
- `.${moduleName}rc.json`,
1476
- `.${moduleName}rc.yaml`,
1477
- `.${moduleName}rc.yml`,
1478
- `.${moduleName}rc.ts`,
1479
- `.${moduleName}rc.mts`,
1480
- `.${moduleName}rc.cts`,
1481
- `.${moduleName}rc.js`,
1482
- `.${moduleName}rc.mjs`,
1483
- `.${moduleName}rc.cjs`,
1484
- `${moduleName}.config.ts`,
1485
- `${moduleName}.config.mts`,
1486
- `${moduleName}.config.cts`,
1487
- `${moduleName}.config.js`,
1488
- `${moduleName}.config.mjs`,
1489
- `${moduleName}.config.cjs`
1490
- ];
1491
- const explorer = cosmiconfig(moduleName, {
1402
+ //#region src/runners/generate/utils.ts
1403
+ const jiti = createJiti(import.meta.url, {
1404
+ jsx: {
1405
+ runtime: "automatic",
1406
+ importSource: "@kubb/renderer-jsx"
1407
+ },
1408
+ moduleCache: false
1409
+ });
1410
+ const tsLoader = (configFile) => jiti.import(configFile, { default: true });
1411
+ const MODULE_NAME = "kubb";
1412
+ const BASE_SEARCH_PLACES = [
1413
+ "package.json",
1414
+ `.${MODULE_NAME}rc`,
1415
+ `.${MODULE_NAME}rc.json`,
1416
+ `.${MODULE_NAME}rc.yaml`,
1417
+ `.${MODULE_NAME}rc.yml`,
1418
+ `.${MODULE_NAME}rc.ts`,
1419
+ `.${MODULE_NAME}rc.mts`,
1420
+ `.${MODULE_NAME}rc.cts`,
1421
+ `.${MODULE_NAME}rc.js`,
1422
+ `.${MODULE_NAME}rc.mjs`,
1423
+ `.${MODULE_NAME}rc.cjs`,
1424
+ `${MODULE_NAME}.config.ts`,
1425
+ `${MODULE_NAME}.config.mts`,
1426
+ `${MODULE_NAME}.config.cts`,
1427
+ `${MODULE_NAME}.config.js`,
1428
+ `${MODULE_NAME}.config.mjs`,
1429
+ `${MODULE_NAME}.config.cjs`
1430
+ ];
1431
+ const SEARCH_PLACES = [
1432
+ "",
1433
+ ".config/",
1434
+ "configs/"
1435
+ ].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`));
1436
+ async function getCosmiConfig(configFile) {
1437
+ const explorer = cosmiconfig(MODULE_NAME, {
1492
1438
  cache: false,
1493
- searchPlaces: [
1494
- ...searchPlaces.map((searchPlace) => {
1495
- return `.config/${searchPlace}`;
1496
- }),
1497
- ...searchPlaces.map((searchPlace) => {
1498
- return `configs/${searchPlace}`;
1499
- }),
1500
- ...searchPlaces
1501
- ],
1439
+ searchPlaces: SEARCH_PLACES,
1502
1440
  loaders: {
1503
1441
  ".ts": tsLoader,
1504
1442
  ".mts": tsLoader,
1505
1443
  ".cts": tsLoader
1506
1444
  }
1507
1445
  });
1446
+ let result;
1508
1447
  try {
1509
- result = config ? await explorer.load(config) : await explorer.search();
1448
+ result = configFile ? await explorer.load(configFile) : await explorer.search();
1510
1449
  } catch (error) {
1511
1450
  throw new Error("Config failed loading", { cause: error });
1512
1451
  }
1513
- 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");
1452
+ if (!result?.config || result.isEmpty) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
1514
1453
  return result;
1515
1454
  }
1516
- //#endregion
1517
- //#region src/utils/watcher.ts
1518
- async function startWatcher(path, cb) {
1455
+ /**
1456
+ * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
1457
+ * Every config in the result is guaranteed to have a `plugins` array.
1458
+ */
1459
+ async function getConfigs({ configPath, input }) {
1460
+ const result = await getCosmiConfig(configPath);
1461
+ const resolved = await (typeof result.config === "function" ? result.config({ input }) : result.config);
1462
+ const userConfigs = Array.isArray(resolved) ? resolved : [resolved];
1463
+ return {
1464
+ configPath: result.filepath,
1465
+ configs: userConfigs.map((item) => ({
1466
+ ...item,
1467
+ plugins: item.plugins ?? []
1468
+ }))
1469
+ };
1470
+ }
1471
+ /**
1472
+ * Runs the `done` hooks defined in a Kubb config in sequence.
1473
+ */
1474
+ async function executeHooks({ configHooks, hooks, makeSink }) {
1475
+ const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
1476
+ for (const command of commands) {
1477
+ const [cmd, ...args] = tokenize(command);
1478
+ if (!cmd) continue;
1479
+ const hookId = createHash("sha256").update(command).digest("hex");
1480
+ const commandWithArgs = [cmd, ...args].join(" ");
1481
+ await hooks.emit("kubb:hook:start", {
1482
+ id: hookId,
1483
+ command: cmd,
1484
+ args
1485
+ });
1486
+ const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs, hookId) ?? {};
1487
+ await runHook({
1488
+ id: hookId,
1489
+ command: cmd,
1490
+ args,
1491
+ commandWithArgs,
1492
+ context: hooks,
1493
+ stream,
1494
+ sink: {
1495
+ onLine,
1496
+ onStdout,
1497
+ onStderr
1498
+ }
1499
+ });
1500
+ }
1501
+ }
1502
+ async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }) {
1503
+ const emitEnd = (success, error) => context.emit("kubb:hook:end", {
1504
+ command,
1505
+ args,
1506
+ id,
1507
+ success,
1508
+ error
1509
+ });
1510
+ try {
1511
+ const proc = x(command, [...args ?? []], {
1512
+ nodeOptions: { detached: process.platform !== "win32" },
1513
+ throwOnError: true
1514
+ });
1515
+ if (stream && sink?.onLine) for await (const line of proc) sink.onLine(line);
1516
+ const result = await proc;
1517
+ await context.emit("kubb:debug", {
1518
+ date: /* @__PURE__ */ new Date(),
1519
+ logs: [result.stdout.trimEnd()]
1520
+ });
1521
+ await context.emit("kubb:success", { message: `${styleText("dim", commandWithArgs)} successfully executed` });
1522
+ await emitEnd(true, null);
1523
+ } catch (err) {
1524
+ if (!(err instanceof NonZeroExitError)) {
1525
+ const error = toError(err);
1526
+ await emitEnd(false, error);
1527
+ await context.emit("kubb:error", { error });
1528
+ return;
1529
+ }
1530
+ const stderr = err.output?.stderr ?? "";
1531
+ const stdout = err.output?.stdout ?? "";
1532
+ await context.emit("kubb:debug", {
1533
+ date: /* @__PURE__ */ new Date(),
1534
+ logs: [stdout, stderr].filter(Boolean)
1535
+ });
1536
+ if (stderr) sink?.onStderr?.(stderr);
1537
+ if (stdout) sink?.onStdout?.(stdout);
1538
+ const error = /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`);
1539
+ await emitEnd(false, error);
1540
+ await context.emit("kubb:error", { error });
1541
+ }
1542
+ }
1543
+ /**
1544
+ * Starts a file watcher on the given paths and calls `cb` on any change.
1545
+ * Ignores `.git` and `node_modules` directories.
1546
+ */
1547
+ async function startWatcher(path, cb, log = {
1548
+ info: console.log,
1549
+ error: console.log
1550
+ }) {
1519
1551
  const { watch } = await import("chokidar");
1520
- watch(path, {
1552
+ const watcher = watch(path, {
1521
1553
  ignorePermissionErrors: true,
1522
1554
  ignored: WATCHER_IGNORED_PATHS
1523
- }).on("all", async (type, file) => {
1524
- console.log(styleText("yellow", styleText("bold", `Change detected: ${type} ${file}`)));
1555
+ });
1556
+ process.once("SIGINT", () => {
1557
+ watcher.close();
1558
+ });
1559
+ process.once("SIGTERM", () => {
1560
+ watcher.close();
1561
+ });
1562
+ watcher.on("all", async (type, file) => {
1563
+ log.info(styleText("yellow", styleText("bold", `Change detected: ${type} ${file}`)));
1525
1564
  try {
1526
1565
  await cb(path);
1527
1566
  } catch (_e) {
1528
- console.log(styleText("red", "Watcher failed"));
1567
+ log.error(styleText("red", "Watcher failed"));
1529
1568
  }
1530
1569
  });
1531
1570
  }
1532
1571
  //#endregion
1533
- //#region src/runners/generate.ts
1534
- async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel: logLevel$1, hooks, onStart, onEnd }) {
1572
+ //#region src/runners/generate/run.ts
1573
+ /**
1574
+ * Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
1575
+ * avoiding the race where a synchronous emitter fires end before the listener is attached.
1576
+ */
1577
+ function waitForHookEnd(hooks, hookId, onSuccess, fallbackErrorMessage) {
1578
+ return new Promise((resolve, reject) => {
1579
+ const handler = (ctx) => {
1580
+ if (ctx.id !== hookId) return;
1581
+ hooks.off("kubb:hook:end", handler);
1582
+ if (!ctx.success) {
1583
+ reject(ctx.error ?? new Error(fallbackErrorMessage));
1584
+ return;
1585
+ }
1586
+ Promise.resolve(onSuccess()).then(resolve).catch(reject);
1587
+ };
1588
+ hooks.on("kubb:hook:end", handler);
1589
+ });
1590
+ }
1591
+ async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel: logLevel$1, hooks, makeSink, onStart, onEnd }) {
1535
1592
  await onStart();
1536
1593
  let resolvedTool = toolValue;
1537
1594
  if (resolvedTool === "auto") {
@@ -1545,29 +1602,35 @@ async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefi
1545
1602
  let toolError;
1546
1603
  if (resolvedTool && resolvedTool !== "auto" && resolvedTool in toolMap) {
1547
1604
  const toolConfig = toolMap[resolvedTool];
1605
+ const hookId = createHash("sha256").update([configName, resolvedTool].filter(Boolean).join("-")).digest("hex");
1606
+ const successMessage = [
1607
+ `${successPrefix} with ${styleText("dim", resolvedTool)}`,
1608
+ logLevel$1 >= logLevel.info ? `on ${styleText("dim", outputPath)}` : void 0,
1609
+ "successfully"
1610
+ ].filter(Boolean).join(" ");
1548
1611
  try {
1549
- const hookId = createHash("sha256").update([configName, resolvedTool].filter(Boolean).join("-")).digest("hex");
1550
- const hookEndPromise = new Promise((resolve, reject) => {
1551
- const handler = (ctx) => {
1552
- if (ctx.id !== hookId) return;
1553
- hooks.off("kubb:hook:end", handler);
1554
- if (!ctx.success) {
1555
- reject(ctx.error ?? /* @__PURE__ */ new Error(`${toolConfig.errorMessage}`));
1556
- return;
1557
- }
1558
- hooks.emit("kubb:success", { message: [
1559
- `${successPrefix} with ${styleText("dim", resolvedTool)}`,
1560
- logLevel$1 >= logLevel.info ? `on ${styleText("dim", outputPath)}` : void 0,
1561
- "successfully"
1562
- ].filter(Boolean).join(" ") }).then(resolve).catch(reject);
1563
- };
1564
- hooks.on("kubb:hook:end", handler);
1565
- });
1612
+ const hookArgs = toolConfig.args(outputPath);
1613
+ const commandWithArgs = [toolConfig.command, ...hookArgs].join(" ");
1614
+ const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit("kubb:success", { message: successMessage }), toolConfig.errorMessage);
1566
1615
  await hooks.emit("kubb:hook:start", {
1567
1616
  id: hookId,
1568
1617
  command: toolConfig.command,
1569
- args: toolConfig.args(outputPath)
1618
+ args: hookArgs
1570
1619
  });
1620
+ const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs, hookId) ?? {};
1621
+ runHook({
1622
+ id: hookId,
1623
+ command: toolConfig.command,
1624
+ args: hookArgs,
1625
+ commandWithArgs,
1626
+ context: hooks,
1627
+ stream,
1628
+ sink: {
1629
+ onLine,
1630
+ onStdout,
1631
+ onStderr
1632
+ }
1633
+ }).catch(() => {});
1571
1634
  await hookEndPromise;
1572
1635
  } catch (caughtError) {
1573
1636
  const err = toError(caughtError);
@@ -1579,9 +1642,9 @@ async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefi
1579
1642
  if (toolError) throw toolError;
1580
1643
  }
1581
1644
  async function generate(options) {
1582
- const { input, hooks, logLevel: logLevel$2 } = options;
1645
+ const { input, hooks, logLevel: logLevel$2, makeSink } = options;
1583
1646
  const hrStart = process$1.hrtime();
1584
- const inputPath = input ?? ("path" in options.config.input ? options.config.input.path : void 0);
1647
+ const inputPath = input ?? (options.config.input && "path" in options.config.input ? options.config.input.path : void 0);
1585
1648
  const config = {
1586
1649
  ...options.config,
1587
1650
  input: inputPath ? {
@@ -1591,25 +1654,36 @@ async function generate(options) {
1591
1654
  ...options.config.output
1592
1655
  };
1593
1656
  const kubb = createKubb(config, { hooks });
1594
- await kubb.setup();
1595
1657
  await hooks.emit("kubb:generation:start", { config });
1596
1658
  await hooks.emit("kubb:info", {
1597
1659
  message: config.name ? `Setup generation ${styleText("bold", config.name)}` : "Setup generation",
1598
1660
  info: inputPath
1599
1661
  });
1662
+ await kubb.setup();
1600
1663
  await hooks.emit("kubb:info", {
1601
1664
  message: config.name ? `Build generation ${styleText("bold", config.name)}` : "Build generation",
1602
1665
  info: inputPath
1603
1666
  });
1604
1667
  const { files, failedPlugins, pluginTimings, error, driver } = await kubb.safeBuild();
1605
1668
  await hooks.emit("kubb:info", { message: "Load summary" });
1669
+ const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({
1670
+ name: p.name,
1671
+ options: p.options
1672
+ }));
1673
+ const reportTelemetry = (status) => sendTelemetry(buildTelemetryEvent({
1674
+ command: "generate",
1675
+ kubbVersion: version,
1676
+ plugins: telemetryPlugins,
1677
+ hrStart,
1678
+ filesCreated: files.length,
1679
+ status
1680
+ }));
1606
1681
  if (failedPlugins.size > 0 || error) {
1607
- const allErrors = [error, ...Array.from(failedPlugins).filter((it) => it.error).map((it) => it.error)].filter(Boolean);
1682
+ const allErrors = [error, ...Array.from(failedPlugins, (it) => it.error)].filter(Boolean);
1608
1683
  for (const err of allErrors) await hooks.emit("kubb:error", { error: err });
1609
1684
  await hooks.emit("kubb:generation:end", {
1610
1685
  config,
1611
- files,
1612
- sources: kubb.sources
1686
+ storage: kubb.storage
1613
1687
  });
1614
1688
  await hooks.emit("kubb:generation:summary", {
1615
1689
  config,
@@ -1619,62 +1693,51 @@ async function generate(options) {
1619
1693
  hrStart,
1620
1694
  pluginTimings: logLevel$2 >= logLevel.verbose ? pluginTimings : void 0
1621
1695
  });
1622
- await sendTelemetry(buildTelemetryEvent({
1623
- command: "generate",
1624
- kubbVersion: version,
1625
- plugins: Array.from(driver.plugins.values(), (p) => ({
1626
- name: p.name,
1627
- options: p.options
1628
- })),
1629
- hrStart,
1630
- filesCreated: files.length,
1631
- status: "failed"
1632
- }));
1633
- process$1.exit(1);
1696
+ await reportTelemetry("failed");
1697
+ return false;
1634
1698
  }
1635
1699
  await hooks.emit("kubb:success", {
1636
- message: "Generation successfully",
1700
+ message: "Generation succeeded",
1637
1701
  info: inputPath
1638
1702
  });
1639
1703
  await hooks.emit("kubb:generation:end", {
1640
1704
  config,
1641
- files,
1642
- sources: kubb.sources
1705
+ storage: kubb.storage
1643
1706
  });
1644
1707
  const outputPath = path.resolve(config.root, config.output.path);
1645
- if (config.output.format) await runToolPass({
1708
+ const toolPasses = [config.output.format && {
1646
1709
  toolValue: config.output.format,
1647
1710
  detect: detectFormatter,
1648
1711
  toolMap: formatters,
1649
1712
  toolLabel: "formatter",
1650
1713
  successPrefix: "Formatting",
1651
1714
  noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting.",
1652
- configName: config.name,
1653
- outputPath,
1654
- logLevel: logLevel$2,
1655
- hooks,
1656
1715
  onStart: () => hooks.emit("kubb:format:start"),
1657
1716
  onEnd: () => hooks.emit("kubb:format:end")
1658
- });
1659
- if (config.output.lint) await runToolPass({
1717
+ }, config.output.lint && {
1660
1718
  toolValue: config.output.lint,
1661
1719
  detect: detectLinter,
1662
1720
  toolMap: linters,
1663
1721
  toolLabel: "linter",
1664
1722
  successPrefix: "Linting",
1665
1723
  noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting.",
1724
+ onStart: () => hooks.emit("kubb:lint:start"),
1725
+ onEnd: () => hooks.emit("kubb:lint:end")
1726
+ }].filter(Boolean);
1727
+ for (const pass of toolPasses) await runToolPass({
1728
+ ...pass,
1666
1729
  configName: config.name,
1667
1730
  outputPath,
1668
1731
  logLevel: logLevel$2,
1669
1732
  hooks,
1670
- onStart: () => hooks.emit("kubb:lint:start"),
1671
- onEnd: () => hooks.emit("kubb:lint:end")
1733
+ makeSink
1672
1734
  });
1673
1735
  if (config.hooks) {
1674
1736
  await hooks.emit("kubb:hooks:start");
1675
1737
  await executeHooks({
1676
1738
  configHooks: config.hooks,
1677
- hooks
1739
+ hooks,
1740
+ makeSink
1678
1741
  });
1679
1742
  await hooks.emit("kubb:hooks:end");
1680
1743
  }
@@ -1686,68 +1749,80 @@ async function generate(options) {
1686
1749
  hrStart,
1687
1750
  pluginTimings
1688
1751
  });
1689
- await sendTelemetry(buildTelemetryEvent({
1690
- command: "generate",
1691
- kubbVersion: version,
1692
- plugins: Array.from(driver.plugins.values(), (p) => ({
1693
- name: p.name,
1694
- options: p.options
1695
- })),
1696
- hrStart,
1697
- filesCreated: files.length,
1698
- status: "success"
1699
- }));
1752
+ await reportTelemetry("success");
1753
+ return true;
1700
1754
  }
1701
- async function runGenerateCommand({ input, configPath, logLevel: logLevelKey, watch }) {
1702
- const logLevel$3 = logLevel[logLevelKey] ?? logLevel.info;
1703
- const hooks = new AsyncEventEmitter();
1704
- await setupLogger(hooks, { logLevel: logLevel$3 });
1755
+ async function checkForUpdate(hooks) {
1705
1756
  await executeIfOnline(async () => {
1706
1757
  try {
1707
- const latestVersion = (await (await fetch(KUBB_NPM_PACKAGE_URL)).json()).version;
1708
- if (latestVersion && version < latestVersion) await hooks.emit("kubb:version:new", {
1758
+ const data = await (await fetch(KUBB_NPM_PACKAGE_URL)).json();
1759
+ if (data.version && version < data.version) await hooks.emit("kubb:version:new", {
1709
1760
  currentVersion: version,
1710
- latestVersion
1761
+ latestVersion: data.version
1711
1762
  });
1712
1763
  } catch {}
1713
1764
  });
1765
+ }
1766
+ /**
1767
+ * Runs the full Kubb generation lifecycle for the given CLI options.
1768
+ * Sets up the logger, checks for a newer version, loads configs, and calls `generate` for each config entry.
1769
+ */
1770
+ async function run({ input, configPath, logLevel: logLevelKey, watch }) {
1771
+ const logLevel$3 = logLevel[logLevelKey] ?? logLevel.info;
1772
+ const hooks = new AsyncEventEmitter();
1773
+ const makeSink = await setupLogger(hooks, { logLevel: logLevel$3 });
1774
+ await hooks.emit("kubb:lifecycle:start", { version });
1775
+ await checkForUpdate(hooks);
1714
1776
  try {
1715
- const result = await getCosmiConfig("kubb", configPath);
1716
- const configs = await getConfigs(result.config, { input });
1717
1777
  await hooks.emit("kubb:config:start");
1778
+ const { configs, configPath: resolvedConfigPath } = await getConfigs({
1779
+ configPath,
1780
+ input
1781
+ });
1782
+ const relativeConfigPath = path.relative(process$1.cwd(), resolvedConfigPath);
1718
1783
  await hooks.emit("kubb:info", {
1719
1784
  message: "Config loaded",
1720
- info: path.relative(process$1.cwd(), result.filepath)
1785
+ info: relativeConfigPath
1721
1786
  });
1722
1787
  await hooks.emit("kubb:success", {
1723
1788
  message: "Config loaded successfully",
1724
- info: path.relative(process$1.cwd(), result.filepath)
1789
+ info: relativeConfigPath
1725
1790
  });
1726
1791
  await hooks.emit("kubb:config:end", { configs });
1727
- await hooks.emit("kubb:lifecycle:start", { version });
1792
+ let anyFailed = false;
1728
1793
  for (const config of configs) if (isInputPath(config) && watch) await startWatcher([input || config.input.path], async (paths) => {
1729
- hooks.removeAll();
1730
1794
  await generate({
1731
1795
  input,
1732
1796
  config,
1733
1797
  logLevel: logLevel$3,
1734
- hooks
1798
+ hooks,
1799
+ makeSink
1735
1800
  });
1736
1801
  clack.log.step(styleText("yellow", `Watching for changes in ${paths.join(" and ")}`));
1802
+ }, {
1803
+ info: (msg) => clack.log.info(msg),
1804
+ error: (msg) => clack.log.error(msg)
1737
1805
  });
1738
- else await generate({
1739
- input,
1740
- config,
1741
- logLevel: logLevel$3,
1742
- hooks
1743
- });
1806
+ else try {
1807
+ if (!await generate({
1808
+ input,
1809
+ config,
1810
+ logLevel: logLevel$3,
1811
+ hooks,
1812
+ makeSink
1813
+ })) anyFailed = true;
1814
+ } catch (configError) {
1815
+ await hooks.emit("kubb:error", { error: toError(configError) });
1816
+ anyFailed = true;
1817
+ }
1744
1818
  await hooks.emit("kubb:lifecycle:end");
1819
+ if (anyFailed) process$1.exit(1);
1745
1820
  } catch (error) {
1746
1821
  await hooks.emit("kubb:error", { error: toError(error) });
1747
1822
  process$1.exit(1);
1748
1823
  }
1749
1824
  }
1750
1825
  //#endregion
1751
- export { runGenerateCommand };
1826
+ export { run };
1752
1827
 
1753
- //# sourceMappingURL=generate-Dt_r0ELY.js.map
1828
+ //# sourceMappingURL=run-CM9IkB_6.js.map