@kubb/cli 5.14.6 → 5.15.1

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 (186) hide show
  1. package/bin/kubb.js +2 -1
  2. package/dist/{Telemetry-B5V_ufmv.cjs → Telemetry-B52pKz9i.cjs} +14 -118
  3. package/dist/Telemetry-B52pKz9i.cjs.map +1 -0
  4. package/dist/{Telemetry-DrnGartf.js → Telemetry-C7Qwy2s7.js} +12 -86
  5. package/dist/Telemetry-C7Qwy2s7.js.map +1 -0
  6. package/dist/{background-DlK0by5c.js → background-BJCuXYuB.js} +5 -6
  7. package/dist/{background-DlK0by5c.js.map → background-BJCuXYuB.js.map} +1 -1
  8. package/dist/{background-CdPT1eaq.cjs → background-CK2gQtTU.cjs} +5 -6
  9. package/dist/{background-CdPT1eaq.cjs.map → background-CK2gQtTU.cjs.map} +1 -1
  10. package/dist/{background-C6XHpEo7.js → background-D4mZCg-4.js} +1 -1
  11. package/dist/banner-BdTTDFkG.js +140 -0
  12. package/dist/banner-BdTTDFkG.js.map +1 -0
  13. package/dist/banner-wJFk-L-c.cjs +163 -0
  14. package/dist/banner-wJFk-L-c.cjs.map +1 -0
  15. package/dist/config-BL3HnFhb.js +1 -0
  16. package/dist/config-BWj9jBVj.cjs +62 -0
  17. package/dist/config-BWj9jBVj.cjs.map +1 -0
  18. package/dist/{config-CNqgDSu3.js → config-CQTxXvIG.js} +6 -52
  19. package/dist/config-CQTxXvIG.js.map +1 -0
  20. package/dist/{config-BG_Nr2CZ.cjs → config-CRrmj88c.cjs} +15 -62
  21. package/dist/config-CRrmj88c.cjs.map +1 -0
  22. package/dist/config-Uk3rbZfb.js +49 -0
  23. package/dist/config-Uk3rbZfb.js.map +1 -0
  24. package/dist/configFile-C0DIXNMD.js +993 -0
  25. package/dist/configFile-C0DIXNMD.js.map +1 -0
  26. package/dist/configFile-CoEpHdXG.cjs +1028 -0
  27. package/dist/configFile-CoEpHdXG.cjs.map +1 -0
  28. package/dist/{credentials-C8tjAhTo.js → credentials-B77iJx9H.js} +1 -1
  29. package/dist/{credentials-DDaKqtJn.cjs → credentials-DEsGwcGD.cjs} +3 -4
  30. package/dist/{credentials-DDaKqtJn.cjs.map → credentials-DEsGwcGD.cjs.map} +1 -1
  31. package/dist/{credentials-CZK6zPLv.js → credentials-osgjujE_.js} +3 -4
  32. package/dist/{credentials-CZK6zPLv.js.map → credentials-osgjujE_.js.map} +1 -1
  33. package/dist/env-C3xHRMez.js +1 -0
  34. package/dist/env-eu3XyKqJ.cjs +55 -0
  35. package/dist/env-eu3XyKqJ.cjs.map +1 -0
  36. package/dist/env-rv-VgSGN.js +34 -0
  37. package/dist/env-rv-VgSGN.js.map +1 -0
  38. package/dist/{errors-Cl69p_vI.cjs → errors-BponpdjN.cjs} +3 -4
  39. package/dist/{errors-Cl69p_vI.cjs.map → errors-BponpdjN.cjs.map} +1 -1
  40. package/dist/{errors-DmC83ALX.js → errors-wzqmMpMo.js} +3 -4
  41. package/dist/{errors-DmC83ALX.js.map → errors-wzqmMpMo.js.map} +1 -1
  42. package/dist/index.cjs +37 -2719
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +0 -2
  45. package/dist/index.d.ts +0 -2
  46. package/dist/index.js +35 -2713
  47. package/dist/index.js.map +1 -1
  48. package/dist/installWithSpinner-DpnpxHq5.js +49 -0
  49. package/dist/installWithSpinner-DpnpxHq5.js.map +1 -0
  50. package/dist/installWithSpinner-ONGfIVUJ.cjs +56 -0
  51. package/dist/installWithSpinner-ONGfIVUJ.cjs.map +1 -0
  52. package/dist/{text-CL6N6yPS.js → intro-9PB8sE8z.js} +8 -52
  53. package/dist/intro-9PB8sE8z.js.map +1 -0
  54. package/dist/{text-DrsG1EDN.cjs → intro-YPaf1Imr.cjs} +12 -80
  55. package/dist/intro-YPaf1Imr.cjs.map +1 -0
  56. package/dist/isCIEnvironment-D6xtAAZ2.js +14 -0
  57. package/dist/isCIEnvironment-D6xtAAZ2.js.map +1 -0
  58. package/dist/isCIEnvironment-DiVOMI5Q.cjs +20 -0
  59. package/dist/isCIEnvironment-DiVOMI5Q.cjs.map +1 -0
  60. package/dist/mascot--q1xjKw1.js +63 -0
  61. package/dist/mascot--q1xjKw1.js.map +1 -0
  62. package/dist/mascot-JSA0j3Q_.cjs +80 -0
  63. package/dist/mascot-JSA0j3Q_.cjs.map +1 -0
  64. package/dist/mcp-CcseJJwh.cjs +20 -0
  65. package/dist/mcp-CcseJJwh.cjs.map +1 -0
  66. package/dist/mcp-DUTsS8tR.js +21 -0
  67. package/dist/mcp-DUTsS8tR.js.map +1 -0
  68. package/dist/package-B1hUUjio.cjs +10 -0
  69. package/dist/package-B1hUUjio.cjs.map +1 -0
  70. package/dist/package-MYPMnnTX.js +5 -0
  71. package/dist/package-MYPMnnTX.js.map +1 -0
  72. package/dist/{registry-DOGpflct.js → registry-B3eYk4LN.js} +7 -67
  73. package/dist/registry-B3eYk4LN.js.map +1 -0
  74. package/dist/{registry-BzBp6aZI.cjs → registry-YE1pFWL-.cjs} +4 -82
  75. package/dist/registry-YE1pFWL-.cjs.map +1 -0
  76. package/dist/{reporters-GzXlc4CK.cjs → reporters-2cgjvXwR.cjs} +32 -40
  77. package/dist/{reporters-GzXlc4CK.cjs.map → reporters-2cgjvXwR.cjs.map} +1 -1
  78. package/dist/{reporters-mYHIUZSx.js → reporters-BM430HdQ.js} +19 -27
  79. package/dist/{reporters-mYHIUZSx.js.map → reporters-BM430HdQ.js.map} +1 -1
  80. package/dist/{rolldown-runtime-CPE0t6oh.cjs → rolldown-runtime-C3-Zg-KD.cjs} +1 -2
  81. package/dist/{rolldown-runtime-CRm0XQPb.js → rolldown-runtime-xo6NMXYd.js} +1 -2
  82. package/dist/run-1H9TGT8v.js +77 -0
  83. package/dist/run-1H9TGT8v.js.map +1 -0
  84. package/dist/run-BYP_t9dR.cjs +324 -0
  85. package/dist/run-BYP_t9dR.cjs.map +1 -0
  86. package/dist/run-Bq6gcfkS.js +1 -0
  87. package/dist/run-BrM7-NSV.js +181 -0
  88. package/dist/run-BrM7-NSV.js.map +1 -0
  89. package/dist/run-BsrNfFIl.js +228 -0
  90. package/dist/run-BsrNfFIl.js.map +1 -0
  91. package/dist/{run-l8IiOR_c.js → run-CLiHI99L.js} +9 -9
  92. package/dist/{run-l8IiOR_c.js.map → run-CLiHI99L.js.map} +1 -1
  93. package/dist/{run-C8Prej7s.cjs → run-CQORv7Gq.cjs} +44 -37
  94. package/dist/run-CQORv7Gq.cjs.map +1 -0
  95. package/dist/{run-EJtgdIin.js → run-CXVhxFfC.js} +31 -23
  96. package/dist/run-CXVhxFfC.js.map +1 -0
  97. package/dist/run-CrM4jsix.cjs +80 -0
  98. package/dist/run-CrM4jsix.cjs.map +1 -0
  99. package/dist/run-CvFakE3B.cjs +185 -0
  100. package/dist/run-CvFakE3B.cjs.map +1 -0
  101. package/dist/{run-DC_xH5H3.cjs → run-CyzKy-0p.cjs} +49 -41
  102. package/dist/run-CyzKy-0p.cjs.map +1 -0
  103. package/dist/run-D-nn9-Wq.js +319 -0
  104. package/dist/run-D-nn9-Wq.js.map +1 -0
  105. package/dist/run-DBnSbwtU.cjs +389 -0
  106. package/dist/run-DBnSbwtU.cjs.map +1 -0
  107. package/dist/{run-j1g5si5R.js → run-DTqMrPS9.js} +5 -6
  108. package/dist/{run-j1g5si5R.js.map → run-DTqMrPS9.js.map} +1 -1
  109. package/dist/{run-9fs2T2Je.js → run-DUwX6Icx.js} +26 -20
  110. package/dist/run-DUwX6Icx.js.map +1 -0
  111. package/dist/run-FEiyv6_U.js +385 -0
  112. package/dist/run-FEiyv6_U.js.map +1 -0
  113. package/dist/run-LY_UAYyM.cjs +233 -0
  114. package/dist/run-LY_UAYyM.cjs.map +1 -0
  115. package/dist/{run-sjzj0ir-.cjs → run-dMTJfs4_.cjs} +10 -10
  116. package/dist/{run-sjzj0ir-.cjs.map → run-dMTJfs4_.cjs.map} +1 -1
  117. package/dist/{run-CypFtkVE.cjs → run-uPA5s3rI.cjs} +5 -6
  118. package/dist/{run-CypFtkVE.cjs.map → run-uPA5s3rI.cjs.map} +1 -1
  119. package/dist/shared-C0EtrdUm.cjs +123 -0
  120. package/dist/shared-C0EtrdUm.cjs.map +1 -0
  121. package/dist/shared-Ct9stKpp.js +94 -0
  122. package/dist/shared-Ct9stKpp.js.map +1 -0
  123. package/dist/{snapshot-laSRD0z1.cjs → snapshot-CPF9zyZj.cjs} +13 -14
  124. package/dist/{snapshot-laSRD0z1.cjs.map → snapshot-CPF9zyZj.cjs.map} +1 -1
  125. package/dist/{snapshot-BJWnL6hE.js → snapshot-CiV08NJr.js} +10 -11
  126. package/dist/{snapshot-BJWnL6hE.js.map → snapshot-CiV08NJr.js.map} +1 -1
  127. package/dist/spinner-BZaln7O8.js +160 -0
  128. package/dist/spinner-BZaln7O8.js.map +1 -0
  129. package/dist/spinner-CfB0sIPy.cjs +208 -0
  130. package/dist/spinner-CfB0sIPy.cjs.map +1 -0
  131. package/dist/{status-DFEdbBPu.cjs → status-C066YA-4.cjs} +7 -8
  132. package/dist/{status-DFEdbBPu.cjs.map → status-C066YA-4.cjs.map} +1 -1
  133. package/dist/{status-BjmXLRm2.js → status-Dj8tivag.js} +6 -7
  134. package/dist/{status-BjmXLRm2.js.map → status-Dj8tivag.js.map} +1 -1
  135. package/dist/studio-B4XsXgKj.js +215 -0
  136. package/dist/studio-B4XsXgKj.js.map +1 -0
  137. package/dist/studio-D9_-mKee.cjs +218 -0
  138. package/dist/studio-D9_-mKee.cjs.map +1 -0
  139. package/dist/studioWorker.js +4 -5
  140. package/dist/{summary-DDnI70tn.js → summary-CbmQKA8l.js} +5 -6
  141. package/dist/{summary-DDnI70tn.js.map → summary-CbmQKA8l.js.map} +1 -1
  142. package/dist/{summary-1DCwzWEU.cjs → summary-Clvl5Hxs.cjs} +7 -8
  143. package/dist/{summary-1DCwzWEU.cjs.map → summary-Clvl5Hxs.cjs.map} +1 -1
  144. package/dist/table-BlRe9YTZ.cjs +15 -0
  145. package/dist/table-BlRe9YTZ.cjs.map +1 -0
  146. package/dist/table-CR7iZJGo.js +10 -0
  147. package/dist/table-CR7iZJGo.js.map +1 -0
  148. package/dist/text-BmiI4s6N.js +13 -0
  149. package/dist/text-BmiI4s6N.js.map +1 -0
  150. package/dist/text-Ep3AulAS.cjs +24 -0
  151. package/dist/text-Ep3AulAS.cjs.map +1 -0
  152. package/dist/time-3BKoci3G.cjs +82 -0
  153. package/dist/time-3BKoci3G.cjs.map +1 -0
  154. package/dist/time-C-wU7VhC.js +65 -0
  155. package/dist/time-C-wU7VhC.js.map +1 -0
  156. package/dist/utils-BdibacYq.js +244 -0
  157. package/dist/utils-BdibacYq.js.map +1 -0
  158. package/dist/utils-CO89mxRU.cjs +290 -0
  159. package/dist/utils-CO89mxRU.cjs.map +1 -0
  160. package/dist/utils-CbJ6hS_t.js +222 -0
  161. package/dist/utils-CbJ6hS_t.js.map +1 -0
  162. package/dist/utils-CcARPB45.cjs +286 -0
  163. package/dist/utils-CcARPB45.cjs.map +1 -0
  164. package/dist/validate-B3tLWYJU.cjs +27 -0
  165. package/dist/validate-B3tLWYJU.cjs.map +1 -0
  166. package/dist/validate-C5fyNF4v.js +28 -0
  167. package/dist/validate-C5fyNF4v.js.map +1 -0
  168. package/package.json +7 -7
  169. package/dist/Telemetry-B5V_ufmv.cjs.map +0 -1
  170. package/dist/Telemetry-DrnGartf.js.map +0 -1
  171. package/dist/config-BG_Nr2CZ.cjs.map +0 -1
  172. package/dist/config-CNqgDSu3.js.map +0 -1
  173. package/dist/config-DWDpFSn1.js +0 -1
  174. package/dist/registry-BzBp6aZI.cjs.map +0 -1
  175. package/dist/registry-DOGpflct.js.map +0 -1
  176. package/dist/run-9fs2T2Je.js.map +0 -1
  177. package/dist/run-C8Prej7s.cjs.map +0 -1
  178. package/dist/run-CXVme-aS.js +0 -1
  179. package/dist/run-DC_xH5H3.cjs.map +0 -1
  180. package/dist/run-EJtgdIin.js.map +0 -1
  181. package/dist/text-CL6N6yPS.js.map +0 -1
  182. package/dist/text-DrsG1EDN.cjs.map +0 -1
  183. package/dist/utils-C3vTpUje.cjs +0 -645
  184. package/dist/utils-C3vTpUje.cjs.map +0 -1
  185. package/dist/utils-CIc8YFtr.js +0 -536
  186. package/dist/utils-CIc8YFtr.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/cli",
3
- "version": "5.14.6",
3
+ "version": "5.15.1",
4
4
  "description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb studio, and kubb mcp to manage the full code generation lifecycle.",
5
5
  "keywords": [
6
6
  "cli",
@@ -68,7 +68,7 @@
68
68
  "dependencies": {
69
69
  "@clack/prompts": "^1.8.1",
70
70
  "@gunshi/plugin-dryrun": "^0.37.3",
71
- "@kubb/core": "5.14.6",
71
+ "@kubb/core": "5.15.1",
72
72
  "chokidar": "^6.0.0",
73
73
  "gunshi": "^0.37.3",
74
74
  "jiti": "^2.7.0",
@@ -79,13 +79,13 @@
79
79
  "devDependencies": {
80
80
  "@internals/shared": "0.0.1",
81
81
  "@internals/utils": "0.0.1",
82
- "@kubb/adapter-oas": "5.14.6",
83
- "@kubb/studio": "5.14.6"
82
+ "@kubb/adapter-oas": "5.15.1",
83
+ "@kubb/studio": "5.15.1"
84
84
  },
85
85
  "peerDependencies": {
86
- "@kubb/adapter-oas": "5.14.6",
87
- "@kubb/mcp": "5.14.6",
88
- "@kubb/studio": "5.14.6"
86
+ "@kubb/adapter-oas": "5.15.1",
87
+ "@kubb/mcp": "5.15.1",
88
+ "@kubb/studio": "5.15.1"
89
89
  },
90
90
  "peerDependenciesMeta": {
91
91
  "@kubb/adapter-oas": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"Telemetry-B5V_ufmv.cjs","names":["process","process","randomBytes","getAgentProfile","os"],"sources":["../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\n * `CI=false` and `CI=0` count as not CI, so a user can opt out locally.\n */\nexport function isCIEnvironment(): boolean {\n const ci = process.env.CI\n return !!(\n (ci && ci !== 'false' && ci !== '0') ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","","import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { getElapsedMs, isCIEnvironment, runtime } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\nimport { version } from '../package.json'\n\n/** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */\nconst OTLP_ENDPOINT = 'https://otlp.kubb.dev' as const\n\ntype TelemetryCommand = 'generate' | 'mcp' | 'studio' | 'validate'\n\n/**\n * Anonymous plugin name and options snapshot sent with each telemetry event.\n */\nexport type TelemetryPlugin = {\n /**\n * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.\n */\n name: string\n /**\n * Anonymized snapshot of the plugin options. Values are included but cannot be traced back to a user.\n */\n options: Record<string, unknown>\n}\n\n/** How a command run ended, as the command reports it to the function {@link trackRun} returned. */\ntype RunResult = {\n status: 'success' | 'failed'\n plugins?: Array<TelemetryPlugin>\n filesCreated?: number\n /**\n * Name the MCP client sends in its `initialize` request, e.g. `'claude-code'`. Only set for `kubb mcp`.\n */\n mcpClient?: string\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isDisabled(): boolean {\n return ['DO_NOT_TRACK', 'KUBB_DISABLE_TELEMETRY'].some((name) => ['1', 'true'].includes(process.env[name] ?? ''))\n}\n\n/** Tracks one command run for the running CLI version; returns the reporter the command calls once it knows how it ended. */\nexport function trackRun({ command, hrStart }: { command: TelemetryCommand; hrStart: [number, number] }): (result: RunResult) => Promise<void> {\n return (result) => sendTelemetry(buildOtlpPayload({ command, duration: Math.round(getElapsedMs(hrStart)), ...result }))\n}\n\n/**\n * The OTLP trace payload for one run: a span named after the command whose attributes are the\n * anonymous run facts. The attribute keys are the contract with otlp.kubb.dev.\n *\n * @see https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload({\n command,\n duration,\n status,\n plugins = [],\n filesCreated = 0,\n mcpClient,\n}: RunResult & { command: TelemetryCommand; duration: number }) {\n const traceId = randomBytes(16).toString('hex')\n const spanId = randomBytes(8).toString('hex')\n const endTimeNs = BigInt(Date.now()) * 1_000_000n\n const startTimeNs = endTimeNs - BigInt(duration) * 1_000_000n\n const pluginNames = [...new Set(plugins.map((plugin) => plugin.name))].sort()\n const agent = getAgentProfile()\n\n const attributes = [\n { key: 'kubb.command', value: { stringValue: command } },\n { key: 'kubb.version', value: { stringValue: version } },\n { key: 'kubb.node_version', value: { stringValue: process.versions.node.split('.')[0] as string } },\n { key: 'kubb.runtime', value: { stringValue: runtime.name } },\n { key: 'kubb.runtime_version', value: { stringValue: runtime.version.split('.')[0] as string } },\n { key: 'kubb.platform', value: { stringValue: os.platform() } },\n { key: 'kubb.ci', value: { boolValue: isCIEnvironment() } },\n // A terminal on stdin means a person typed the command; agents, scripts, and CI pipe it.\n { key: 'kubb.tty', value: { boolValue: process.stdin.isTTY === true } },\n ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\n // The client picks this name, so cap its length before it leaves the machine.\n ...(mcpClient ? [{ key: 'kubb.mcp_client', value: { stringValue: mcpClient.slice(0, 64) } }] : []),\n { key: 'kubb.files_created', value: { intValue: filesCreated } },\n { key: 'kubb.status', value: { stringValue: status } },\n {\n key: 'kubb.plugins',\n value: { arrayValue: { values: pluginNames.map((name) => ({ stringValue: name })) } },\n },\n ...pluginNames.map((name) => ({ key: `kubb.plugin.${name}`, value: { boolValue: true } })),\n {\n key: 'kubb.plugin_options',\n value: {\n arrayValue: {\n values: plugins.map((p) => ({\n kvlistValue: {\n values: [\n { key: 'name', value: { stringValue: p.name } },\n {\n key: 'options',\n value: {\n stringValue: JSON.stringify({\n ...p.options,\n usedEnumNames: undefined,\n }),\n },\n },\n ],\n },\n })),\n },\n },\n },\n ]\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb' } },\n { key: 'service.version', value: { stringValue: version } },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-core', version },\n spans: [\n {\n traceId,\n spanId,\n name: command,\n kind: 1,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: status === 'success' ? 1 : 2,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an OTLP payload to the Kubb endpoint. Respects `DO_NOT_TRACK` and\n * `KUBB_DISABLE_TELEMETRY`, and fails silently so telemetry never interrupts a run. No file\n * paths, OpenAPI specs, or secrets are sent.\n */\nexport async function sendTelemetry(payload: ReturnType<typeof buildOtlpPayload>): Promise<void> {\n if (isDisabled()) {\n return\n }\n\n try {\n await fetch(`${OTLP_ENDPOINT}/v1/traces`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Kubb-Telemetry-Version': '1',\n 'Kubb-Telemetry-Source': 'kubb-cli',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(5_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the run\n }\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgB,kBAA2B;CACzC,MAAM,KAAKA,aAAAA,QAAQ,IAAI;CACvB,OAAO,CAAC,EACL,MAAM,OAAO,WAAW,OAAO,OAChCA,aAAAA,QAAQ,IAAI,kBACZA,aAAAA,QAAQ,IAAI,aACZA,aAAAA,QAAQ,IAAI,0BACZA,aAAAA,QAAQ,IAAI,eACZA,aAAAA,QAAQ,IAAI,YACZA,aAAAA,QAAQ,IAAI,UACZA,aAAAA,QAAQ,IAAI,oBACZA,aAAAA,QAAQ,IAAI,aACZA,aAAAA,QAAQ,IAAI;AA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AAG,cAAc,aAAa;GACxC,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,0BAA0B;IAC1B,yBAAyB;GAC3B;GACA,MAAM,KAAK,UAAU,OAAO;GAC5B,QAAQ,YAAY,QAAQ,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"Telemetry-DrnGartf.js","names":["process","process"],"sources":["../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\n * `CI=false` and `CI=0` count as not CI, so a user can opt out locally.\n */\nexport function isCIEnvironment(): boolean {\n const ci = process.env.CI\n return !!(\n (ci && ci !== 'false' && ci !== '0') ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","","import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { getElapsedMs, isCIEnvironment, runtime } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\nimport { version } from '../package.json'\n\n/** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */\nconst OTLP_ENDPOINT = 'https://otlp.kubb.dev' as const\n\ntype TelemetryCommand = 'generate' | 'mcp' | 'studio' | 'validate'\n\n/**\n * Anonymous plugin name and options snapshot sent with each telemetry event.\n */\nexport type TelemetryPlugin = {\n /**\n * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.\n */\n name: string\n /**\n * Anonymized snapshot of the plugin options. Values are included but cannot be traced back to a user.\n */\n options: Record<string, unknown>\n}\n\n/** How a command run ended, as the command reports it to the function {@link trackRun} returned. */\ntype RunResult = {\n status: 'success' | 'failed'\n plugins?: Array<TelemetryPlugin>\n filesCreated?: number\n /**\n * Name the MCP client sends in its `initialize` request, e.g. `'claude-code'`. Only set for `kubb mcp`.\n */\n mcpClient?: string\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isDisabled(): boolean {\n return ['DO_NOT_TRACK', 'KUBB_DISABLE_TELEMETRY'].some((name) => ['1', 'true'].includes(process.env[name] ?? ''))\n}\n\n/** Tracks one command run for the running CLI version; returns the reporter the command calls once it knows how it ended. */\nexport function trackRun({ command, hrStart }: { command: TelemetryCommand; hrStart: [number, number] }): (result: RunResult) => Promise<void> {\n return (result) => sendTelemetry(buildOtlpPayload({ command, duration: Math.round(getElapsedMs(hrStart)), ...result }))\n}\n\n/**\n * The OTLP trace payload for one run: a span named after the command whose attributes are the\n * anonymous run facts. The attribute keys are the contract with otlp.kubb.dev.\n *\n * @see https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload({\n command,\n duration,\n status,\n plugins = [],\n filesCreated = 0,\n mcpClient,\n}: RunResult & { command: TelemetryCommand; duration: number }) {\n const traceId = randomBytes(16).toString('hex')\n const spanId = randomBytes(8).toString('hex')\n const endTimeNs = BigInt(Date.now()) * 1_000_000n\n const startTimeNs = endTimeNs - BigInt(duration) * 1_000_000n\n const pluginNames = [...new Set(plugins.map((plugin) => plugin.name))].sort()\n const agent = getAgentProfile()\n\n const attributes = [\n { key: 'kubb.command', value: { stringValue: command } },\n { key: 'kubb.version', value: { stringValue: version } },\n { key: 'kubb.node_version', value: { stringValue: process.versions.node.split('.')[0] as string } },\n { key: 'kubb.runtime', value: { stringValue: runtime.name } },\n { key: 'kubb.runtime_version', value: { stringValue: runtime.version.split('.')[0] as string } },\n { key: 'kubb.platform', value: { stringValue: os.platform() } },\n { key: 'kubb.ci', value: { boolValue: isCIEnvironment() } },\n // A terminal on stdin means a person typed the command; agents, scripts, and CI pipe it.\n { key: 'kubb.tty', value: { boolValue: process.stdin.isTTY === true } },\n ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\n // The client picks this name, so cap its length before it leaves the machine.\n ...(mcpClient ? [{ key: 'kubb.mcp_client', value: { stringValue: mcpClient.slice(0, 64) } }] : []),\n { key: 'kubb.files_created', value: { intValue: filesCreated } },\n { key: 'kubb.status', value: { stringValue: status } },\n {\n key: 'kubb.plugins',\n value: { arrayValue: { values: pluginNames.map((name) => ({ stringValue: name })) } },\n },\n ...pluginNames.map((name) => ({ key: `kubb.plugin.${name}`, value: { boolValue: true } })),\n {\n key: 'kubb.plugin_options',\n value: {\n arrayValue: {\n values: plugins.map((p) => ({\n kvlistValue: {\n values: [\n { key: 'name', value: { stringValue: p.name } },\n {\n key: 'options',\n value: {\n stringValue: JSON.stringify({\n ...p.options,\n usedEnumNames: undefined,\n }),\n },\n },\n ],\n },\n })),\n },\n },\n },\n ]\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb' } },\n { key: 'service.version', value: { stringValue: version } },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-core', version },\n spans: [\n {\n traceId,\n spanId,\n name: command,\n kind: 1,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: status === 'success' ? 1 : 2,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an OTLP payload to the Kubb endpoint. Respects `DO_NOT_TRACK` and\n * `KUBB_DISABLE_TELEMETRY`, and fails silently so telemetry never interrupts a run. No file\n * paths, OpenAPI specs, or secrets are sent.\n */\nexport async function sendTelemetry(payload: ReturnType<typeof buildOtlpPayload>): Promise<void> {\n if (isDisabled()) {\n return\n }\n\n try {\n await fetch(`${OTLP_ENDPOINT}/v1/traces`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Kubb-Telemetry-Version': '1',\n 'Kubb-Telemetry-Source': 'kubb-cli',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(5_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the run\n }\n}\n"],"mappings":";;;;;;;;;;A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AO,SAAS;IACjC;IACA,QAAQ,EACN,MAAM,WAAW,YAAY,IAAI,EACnC;GACF,CACF;EACF,CACF;CACF,CACF,EACF;AACF;;;;;;AAOA,eAAsB,cAAc,SAA6D;CAC/F,IAAI,WAAW,GACb;CAGF,IAAI;EACF,MAAM,MAAM,GAAG,cAAc,aAAa;GACxC,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,0BAA0B;IAC1B,yBAAyB;GAC3B;GACA,MAAM,KAAK,UAAU,OAAO;GAC5B,QAAQ,YAAY,QAAQ,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-BG_Nr2CZ.cjs","names":["jiti","createJiti","readFile","join","process","resolve","dirname","existsSync","basename","resolve","Diagnostics","process","toError"],"sources":["../../../internals/shared/src/constants.ts","../../../internals/shared/src/loader.ts","../../../internals/shared/src/config.ts","../src/config.ts"],"sourcesContent":["export const KUBB_CONFIG_FILENAME = 'kubb.config.ts' as const\n\n/** File extensions a Kubb config file may use. */\nexport const CONFIG_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'] as const\n\nexport const KUBB_PACKAGE_NAME = 'kubb' as const\n\n/**\n * Extensions `kubb` ships at its own version, so they count as installed without being a direct\n * dependency. `constants.test.ts` checks it against the `kubb` package's dependencies.\n */\nexport const BUNDLED_PACKAGES: ReadonlyArray<string> = ['@kubb/adapter-oas', '@kubb/parser-ts', '@kubb/parser-md', '@kubb/plugin-barrel']\n\nexport const initDefaults = {\n inputPath: './openapi.yaml',\n outputPath: './src/gen',\n plugins: ['plugin-ts'],\n} as const\n","import { readFile } from 'node:fs/promises'\nimport { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never\n * lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.\n */\nconst JAVASCRIPT_EXTENSION = /\\.[cm]?jsx?$/\n\n/**\n * Per-call options for {@link loadModule}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\nconst jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n/**\n * Loads a Kubb TypeScript or JavaScript config module via jiti.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load\n * re-evaluates the file, so a config edited on disk is picked up by the next load.\n *\n * @example\n * ```ts\n * const config = await loadModule('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport async function loadModule<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T> {\n if (!JAVASCRIPT_EXTENSION.test(filePath)) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n }\n\n // Transpiled through jiti instead, so every load re-evaluates the file as it is on disk now.\n // A TypeScript file it imports reloads too. A plain JavaScript file it imports still goes\n // through Node's `import()` and stays cached until the process restarts.\n const mod = (await jiti.evalModule(await readFile(filePath, 'utf8'), { filename: filePath, async: true, forceTranspile: true })) as\n | { default?: unknown }\n | undefined\n return (options?.default ? (mod?.default ?? mod) : mod) as T\n}\n","import { existsSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS } from './constants.ts'\nimport { loadModule } from './loader.ts'\n\n// A config in one of these folders belongs to the folder above it.\nconst CONFIG_FOLDERS = ['.config', 'configs']\nconst SEARCH_FILES = ['', ...CONFIG_FOLDERS.map((folder) => `${folder}/`)].flatMap((prefix) => [`${prefix}.kubbrc`, `${prefix}kubb.config`])\n\n/**\n * Every config file path the Kubb CLI checks in `dir`, in the order it checks them.\n */\nexport function configFileCandidates(dir: string): Array<string> {\n return SEARCH_FILES.flatMap((file) => CONFIG_EXTENSIONS.map((extension) => join(dir, `${file}${extension}`)))\n}\n\n/**\n * The first Kubb config file in `cwd` or the nearest parent folder that has one: `.kubbrc` before\n * `kubb.config`, the folder itself before its `.config/` and `configs/`, and {@link CONFIG_EXTENSIONS} in order.\n */\nexport function findConfigFile(cwd: string = process.cwd()): string | undefined {\n for (let dir = resolve(cwd); ; dir = dirname(dir)) {\n const found = configFileCandidates(dir).find((file) => existsSync(file))\n if (found || dirname(dir) === dir) return found\n }\n}\n\n/**\n * Loads a Kubb config module, calls it with `cli` when it exports a function, and returns its\n * configs as a list, so a single config and a `defineConfig([...])` array read the same. Each\n * `root` resolves from the folder the config belongs to: the file's folder, or the folder above\n * `.config/` and `configs/`. A missing `root` becomes that folder, so the CLI, the bundler, and\n * an editor read the same paths wherever they run.\n */\nexport async function loadConfigFile<T extends { root?: string }>({ file, cli }: { file: string; cli: unknown }): Promise<Array<T>> {\n const loaded = await loadModule<unknown>(file, { default: true })\n const resolved = (await (typeof loaded === 'function' ? loaded(cli) : loaded)) as T | Array<T>\n const dir = CONFIG_FOLDERS.includes(basename(dirname(file))) ? dirname(dirname(file)) : dirname(file)\n return (Array.isArray(resolved) ? resolved : [resolved]).map((config) => ({ ...config, root: resolve(dir, config.root ?? '.') }))\n}\n","import { resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS, findConfigFile, loadConfigFile } from '@internals/shared'\nimport { type CLIOptions, type Config, Diagnostics } from '@kubb/core'\nimport { toError } from '@internals/utils'\n\ntype GetConfigsOptions = {\n /** Explicit path to the Kubb config file. When omitted, the loader searches up from `process.cwd()`. */\n configPath?: string\n /** OpenAPI input path or URL that overrides `config.input` for this run. */\n input?: string\n /** Watch flag forwarded to the user's `defineConfig` function. */\n watch?: boolean\n /** Log level forwarded to the user's `defineConfig` function. */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /** Absolute path to the resolved config file. */\n configPath: string\n /** Resolved and normalized Kubb configs, each guaranteed to have a `plugins` array. */\n configs: Array<Config>\n}\n\n/** Discovers the Kubb config and resolves it into normalized configs, each guaranteed to have a `plugins` array. */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const file = configPath ? resolve(configPath) : findConfigFile()\n if (!file) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `No Kubb config found. Looked for kubb.config.* and .kubbrc.* (${CONFIG_EXTENSIONS.join(', ')}) in ${process.cwd()}, its .config/ and configs/ folders, and each parent folder.`,\n help: 'Run `kubb init` to create one, or pass a path with `--config`.',\n location: { kind: 'config' },\n })\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>({ file, cli: { config: configPath, input, watch, logLevel } satisfies CLIOptions })\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Config failed loading: ${file}`,\n help: 'Fix the error the config file throws, shown under `caused by:`.',\n location: { kind: 'config' },\n cause: toError(error),\n })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;AAE9E,MAAa,oBAAoB;;;;;AAMjC,MAAa,mBAA0C;CAAC;CAAqB;CAAmB;CAAmB;AAAqB;AAExI,MAAa,eAAe;CAC1B,WAAW;CACX,YAAY;CACZ,SAAS,CAAC,WAAW;AACvB;;;;;;;ACVA,MAAM,eAAe;CACnB,KAAK;EAAE,SAAS;EAAa,cAAc;CAAqB;CAChE,aAAa;AACf;;;;;AAMA,MAAM,uBAAuB;AAY7B,MAAMA,UAAAA,GAAOC,KAAAA,WAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,MAA4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G"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-CNqgDSu3.js","names":[],"sources":["../../../internals/shared/src/constants.ts","../../../internals/shared/src/loader.ts","../../../internals/shared/src/config.ts","../src/config.ts"],"sourcesContent":["export const KUBB_CONFIG_FILENAME = 'kubb.config.ts' as const\n\n/** File extensions a Kubb config file may use. */\nexport const CONFIG_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'] as const\n\nexport const KUBB_PACKAGE_NAME = 'kubb' as const\n\n/**\n * Extensions `kubb` ships at its own version, so they count as installed without being a direct\n * dependency. `constants.test.ts` checks it against the `kubb` package's dependencies.\n */\nexport const BUNDLED_PACKAGES: ReadonlyArray<string> = ['@kubb/adapter-oas', '@kubb/parser-ts', '@kubb/parser-md', '@kubb/plugin-barrel']\n\nexport const initDefaults = {\n inputPath: './openapi.yaml',\n outputPath: './src/gen',\n plugins: ['plugin-ts'],\n} as const\n","import { readFile } from 'node:fs/promises'\nimport { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never\n * lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.\n */\nconst JAVASCRIPT_EXTENSION = /\\.[cm]?jsx?$/\n\n/**\n * Per-call options for {@link loadModule}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\nconst jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n/**\n * Loads a Kubb TypeScript or JavaScript config module via jiti.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load\n * re-evaluates the file, so a config edited on disk is picked up by the next load.\n *\n * @example\n * ```ts\n * const config = await loadModule('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport async function loadModule<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T> {\n if (!JAVASCRIPT_EXTENSION.test(filePath)) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n }\n\n // Transpiled through jiti instead, so every load re-evaluates the file as it is on disk now.\n // A TypeScript file it imports reloads too. A plain JavaScript file it imports still goes\n // through Node's `import()` and stays cached until the process restarts.\n const mod = (await jiti.evalModule(await readFile(filePath, 'utf8'), { filename: filePath, async: true, forceTranspile: true })) as\n | { default?: unknown }\n | undefined\n return (options?.default ? (mod?.default ?? mod) : mod) as T\n}\n","import { existsSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS } from './constants.ts'\nimport { loadModule } from './loader.ts'\n\n// A config in one of these folders belongs to the folder above it.\nconst CONFIG_FOLDERS = ['.config', 'configs']\nconst SEARCH_FILES = ['', ...CONFIG_FOLDERS.map((folder) => `${folder}/`)].flatMap((prefix) => [`${prefix}.kubbrc`, `${prefix}kubb.config`])\n\n/**\n * Every config file path the Kubb CLI checks in `dir`, in the order it checks them.\n */\nexport function configFileCandidates(dir: string): Array<string> {\n return SEARCH_FILES.flatMap((file) => CONFIG_EXTENSIONS.map((extension) => join(dir, `${file}${extension}`)))\n}\n\n/**\n * The first Kubb config file in `cwd` or the nearest parent folder that has one: `.kubbrc` before\n * `kubb.config`, the folder itself before its `.config/` and `configs/`, and {@link CONFIG_EXTENSIONS} in order.\n */\nexport function findConfigFile(cwd: string = process.cwd()): string | undefined {\n for (let dir = resolve(cwd); ; dir = dirname(dir)) {\n const found = configFileCandidates(dir).find((file) => existsSync(file))\n if (found || dirname(dir) === dir) return found\n }\n}\n\n/**\n * Loads a Kubb config module, calls it with `cli` when it exports a function, and returns its\n * configs as a list, so a single config and a `defineConfig([...])` array read the same. Each\n * `root` resolves from the folder the config belongs to: the file's folder, or the folder above\n * `.config/` and `configs/`. A missing `root` becomes that folder, so the CLI, the bundler, and\n * an editor read the same paths wherever they run.\n */\nexport async function loadConfigFile<T extends { root?: string }>({ file, cli }: { file: string; cli: unknown }): Promise<Array<T>> {\n const loaded = await loadModule<unknown>(file, { default: true })\n const resolved = (await (typeof loaded === 'function' ? loaded(cli) : loaded)) as T | Array<T>\n const dir = CONFIG_FOLDERS.includes(basename(dirname(file))) ? dirname(dirname(file)) : dirname(file)\n return (Array.isArray(resolved) ? resolved : [resolved]).map((config) => ({ ...config, root: resolve(dir, config.root ?? '.') }))\n}\n","import { resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS, findConfigFile, loadConfigFile } from '@internals/shared'\nimport { type CLIOptions, type Config, Diagnostics } from '@kubb/core'\nimport { toError } from '@internals/utils'\n\ntype GetConfigsOptions = {\n /** Explicit path to the Kubb config file. When omitted, the loader searches up from `process.cwd()`. */\n configPath?: string\n /** OpenAPI input path or URL that overrides `config.input` for this run. */\n input?: string\n /** Watch flag forwarded to the user's `defineConfig` function. */\n watch?: boolean\n /** Log level forwarded to the user's `defineConfig` function. */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /** Absolute path to the resolved config file. */\n configPath: string\n /** Resolved and normalized Kubb configs, each guaranteed to have a `plugins` array. */\n configs: Array<Config>\n}\n\n/** Discovers the Kubb config and resolves it into normalized configs, each guaranteed to have a `plugins` array. */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const file = configPath ? resolve(configPath) : findConfigFile()\n if (!file) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `No Kubb config found. Looked for kubb.config.* and .kubbrc.* (${CONFIG_EXTENSIONS.join(', ')}) in ${process.cwd()}, its .config/ and configs/ folders, and each parent folder.`,\n help: 'Run `kubb init` to create one, or pass a path with `--config`.',\n location: { kind: 'config' },\n })\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>({ file, cli: { config: configPath, input, watch, logLevel } satisfies CLIOptions })\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Config failed loading: ${file}`,\n help: 'Fix the error the config file throws, shown under `caused by:`.',\n location: { kind: 'config' },\n cause: toError(error),\n })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;;;AAAA,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;AAE9E,MAAa,oBAAoB;;;;;AAMjC,MAAa,mBAA0C;CAAC;CAAqB;CAAmB;CAAmB;AAAqB;AAExI,MAAa,eAAe;CAC1B,WAAW;CACX,YAAY;CACZ,SAAS,CAAC,WAAW;AACvB;;;;;;;ACVA,MAAM,eAAe;CACnB,KAAK;EAAE,SAAS;EAAa,cAAc;CAAqB;CAChE,aAAa;AACf;;;;;AAMA,MAAM,uBAAuB;AAY7B,MAAM,OAAO,WAAW,YAAY,KAAK,YAAY;;;;;;;;;;;;AAarD,eAAsB,WAAwB,UAAkB,SAAyC;CACvG,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,OAAQ,SAAS,UAAU,KAAK,OAAO,UAAU,EAAE,SAAS,KAAK,CAAC,IAAI,KAAK,OAAO,QAAQ;CAM5F,MAAM,MAAO,MAAM,KAAK,WAAW,MAAM,SAAS,UAAU,MAAM,GAAG;EAAE,UAAU;EAAU,OAAO;EAAM,gBAAgB;CAAK,CAAC;CAG9H,OAAQ,SAAS,UAAW,KAAK,WAAW,MAAO;AACrD;;;AC9CA,MAAM,iBAAiB,CAAC,WAAW,SAAS;AAC5C,MAAM,eAAe,CAAC,IAAI,GAAG,eAAe,KAAK,WAAW,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,OAAO,U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AAM,KAAK;IAAE,QAAQ;IAAY;IAAO;IAAO;GAAS;EAAuB,CAAC;CAC3H,SAAS,OAAO;EACd,MAAM,IAAI,YAAY,MAAM;GAC1B,MAAM,YAAY,KAAK;GACvB,UAAU;GACV,SAAS,0BAA0B;GACnC,MAAM;GACN,UAAU,EAAE,MAAM,SAAS;GAC3B,OAAO,QAAQ,KAAK;EACtB,CAAC;CACH;CAEA,OAAO;EAAE,YAAY;EAAM,SAAS,QAAQ,KAAK,UAAU;GAAE,GAAG;GAAM,SAAS,KAAK,WAAW,CAAC;EAAE,EAAE;CAAE;AACxG"}
@@ -1 +0,0 @@
1
- export { t as getConfigs } from "./config-CNqgDSu3.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry-BzBp6aZI.cjs","names":["getIntro","isRichOutput","stripVTControlCharacters","isInteractiveRun","wakeUp","sleep","process","Diagnostics","getErrorMessage","toError","isRegistryEntry","isValid","isLessThan","difference"],"sources":["../src/ui/mascot.ts","../src/utils/registry.ts"],"sourcesContent":["import { setTimeout as sleep } from 'node:timers/promises'\nimport { stripVTControlCharacters } from 'node:util'\nimport { isRichOutput } from '../utils/env.ts'\nimport { type Expression, getIntro, wakeUp } from '../loggers/banner.ts'\nimport { isInteractiveRun } from './intro.ts'\n\nfunction bannerIntro(version: string, expression: Expression, command: string): string {\n return getIntro({ title: 'Turn your API spec into type-safe code', description: `kubb ${command}`, version, expression })\n}\n\n/** Whether the mascot can be drawn: a rich, 256-color terminal wide enough that no line wraps and throws off a redraw. */\nfunction canDrawMascot(version: string, command: string): boolean {\n if (!isRichOutput() || !process.stdout.hasColors(256)) return false\n\n return stripVTControlCharacters(bannerIntro(version, 'open', command))\n .split('\\n')\n .every((line) => line.length <= process.stdout.columns)\n}\n\n/**\n * Whether a command opens with the mascot. Only the long-running ones do: `generate`, a Studio\n * session or pairing, and `add` or `update` while they ask questions. Quick commands print only\n * their result.\n */\nexport function wantsMascot({ commandPath, values }: { commandPath: ReadonlyArray<string>; values: Record<string, unknown> }): boolean {\n const [command, subCommand] = commandPath\n if (values.help || values.version) return false\n if (command === 'studio') return subCommand === undefined || subCommand === 'connect' || subCommand === 'login'\n if (command === 'add' || command === 'update' || command === 'init') return isInteractiveRun({ yes: values.yes, dryRun: values.dryRun ?? values['dry-run'] })\n\n return command === undefined || command === 'generate'\n}\n\n/**\n * The still Kubb mascot with the version and the running command, such as `studio connect`, or a\n * single version line where the terminal cannot draw it. Commands print it as their header; it\n * draws at once, with no wake-up frames.\n */\nexport function getBanner(version: string, command: string): string {\n return canDrawMascot(version, command) ? `\\n${bannerIntro(version, 'open', command)}` : `Kubb CLI v${version}`\n}\n\n/**\n * Opens `kubb generate` with the mascot playing its wake-up frames in place, which takes under a\n * second and overlaps the config load. Elsewhere the still {@link getBanner} is the header.\n */\nexport async function logBanner(version: string): Promise<void> {\n if (!canDrawMascot(version, 'generate')) {\n console.log(getBanner(version, 'generate'))\n\n return\n }\n\n console.log('')\n for (const [index, [expression, ms]] of wakeUp.entries()) {\n const frame = bannerIntro(version, expression, 'generate')\n if (index > 0) process.stdout.moveCursor(0, -frame.split('\\n').length)\n console.log(frame)\n await sleep(ms)\n }\n}\n","import process from 'node:process'\nimport { getErrorMessage, toError } from '@internals/utils'\nimport { checkCompatibility, Diagnostics, type ExtensionManifest, isRegistryEntry, type RegistryArtifact, type RegistryEntry } from '@kubb/core'\nimport { difference, isLessThan, isValid } from 'verkit'\n\nconst DEFAULT_REGISTRY = 'https://kubb.dev/registry'\n\nconst SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*'\nconst ID = new RegExp(`^${SLUG}(\\\\/${SLUG})?$`)\n\n/** The registry base URL: `KUBB_REGISTRY`, or kubb.dev. */\nexport function registryUrl(): string {\n const url = process.env.KUBB_REGISTRY || DEFAULT_REGISTRY\n if (!/^https?:\\/\\//.test(url))\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `KUBB_REGISTRY must be an http(s) URL, got \"${url}\".`,\n help: 'Set `KUBB_REGISTRY` to an http(s) URL, or unset it to use https://kubb.dev/registry.',\n })\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Turns `owner/slug`, or a bare `slug` meaning `kubb-labs/<slug>`, into a registry id.\n *\n * @throws when the id has another shape, so it never reaches a URL unchecked.\n */\nexport function toRegistryId(input: string): string {\n if (!ID.test(input))\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `\"${input}\" is not a registry id. Use owner/slug, such as kubb-labs/plugin-zod, or a slug, such as plugin-zod.`,\n })\n return input.includes('/') ? input : `kubb-labs/${input}`\n}\n\n/** The shortest id `kubb add` and `kubb update` accept: the slug for an official extension, else `owner/slug`. */\nexport function toShortId(id: string): string {\n return id.startsWith('kubb-labs/') ? id.slice('kubb-labs/'.length) : id\n}\n\n/**\n * GETs `url` as JSON. A non-2xx answer or a body that is not JSON returns no `body`.\n * A network error throws with the URL.\n */\nasync function fetchJSON(url: string): Promise<{ status: number; body?: unknown }> {\n let response: Response\n try {\n response = await globalThis.fetch(url, { headers: { accept: 'application/json' } })\n } catch (cause) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Could not read ${url}: ${getErrorMessage(cause)}`,\n help: 'Check your network connection and that the registry is reachable.',\n cause: toError(cause),\n })\n }\n if (!response.ok) return { status: response.status }\n return { status: response.status, body: await response.json().catch(() => undefined) }\n}\n\n/** Fetches the registry index, leaving out entries that fail validation. */\nexport async function fetchRegistryIndex({ registry }: { registry: string }): Promise<Array<RegistryEntry>> {\n const { status, body } = await fetchJSON(`${registry}/index.json`)\n const index = body as { version?: unknown; extensions?: unknown } | null | undefined\n if (status !== 200 || index?.version !== 1 || !Array.isArray(index.extensions)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequestFailed,\n severity: 'error',\n message: `The registry at ${registry} sent an invalid index (HTTP ${status}).`,\n help: 'Try again later, or check that `KUBB_REGISTRY` points at a Kubb registry.',\n })\n }\n return index.extensions.filter(isRegistryEntry)\n}\n\n/** What the package manager installs: `<package>@<version>`, or a GitHub release's commit, so the install cannot move with the tag. */\nexport function installSpec(artifact: RegistryArtifact): string {\n return artifact.kind === 'github' ? `github:${artifact.owner}/${artifact.repo}#${artifact.commit}` : `${artifact.package}@${artifact.version}`\n}\n\n/** Why the running Kubb or Node.js version cannot use this extension, or `undefined` when it can. */\nexport function incompatibility(manifest: ExtensionManifest): string | undefined {\n try {\n checkCompatibility({ name: manifest.name, compatibility: manifest.compatibility })\n return undefined\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Whether `latest` is newer than `installed`. An unknown installed version counts as outdated, and an\n * invalid `latest` never does.\n */\nexport function isOutdated({ installed, latest }: { installed: string | undefined; latest: string }): boolean {\n if (!isValid(latest)) return false\n return !installed || !isValid(installed) || isLessThan(installed, latest)\n}\n\n/** `major`, `minor`, or `patch` from `installed` to `latest`, or `undefined` when either is unknown or invalid. */\nexport function bumpOf({ installed, latest }: { installed: string | undefined; latest: string }): 'major' | 'minor' | 'patch' | undefined {\n if (!installed || !isValid(installed) || !isValid(latest)) return undefined\n const kind = difference(installed, latest)\n if (!kind) return undefined\n if (kind.endsWith('major')) return 'major'\n return kind.endsWith('minor') ? 'minor' : 'patch'\n}\n\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0]!\n row[0] = i\n for (let j = 1; j <= b.length; j++) {\n const current = row[j]!\n row[j] = Math.min(row[j]! + 1, row[j - 1]! + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))\n previous = current\n }\n }\n return row[b.length]!\n}\n\n/** Words every extension shares, so they never make two ids look alike. */\nconst COMMON_TOKENS = new Set(['kubb', 'plugin', 'adapter', 'parser'])\n\n/**\n * The ids closest to a mistyped `input`, best first, at most three: those within a few edits of it,\n * or sharing a word such as `zod` in any order. Compares slugs, so the owner may be left out.\n */\nexport function closestIds({ input, ids }: { input: string; ids: Array<string> }): Array<string> {\n const slug = (id: string) => id.slice(id.indexOf('/') + 1)\n const tokens = new Set(\n slug(input)\n .split('-')\n .filter((token) => !COMMON_TOKENS.has(token)),\n )\n return ids\n .map((id) => ({\n id,\n distance: editDistance(slug(input), slug(id)),\n shared: slug(id)\n .split('-')\n .some((token) => tokens.has(token)),\n }))\n .filter(({ distance, shared }) => shared || distance <= Math.max(2, Math.floor(slug(input).length / 4)))\n .sort((a, b) => Number(b.shared) - Number(a.shared) || a.distance - b.distance)\n .slice(0, 3)\n .map(({ id }) => id)\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAS,YAAY,SAAiB,YAAwB,SAAyB;CACrF,OAAOA,cAAAA,SAAS;EAAE,OAAO;EAA0C,aAAa,QAAQ;EAAW;EAAS;CAAW,CAAC;AAC1H;;AAGA,SAAS,cAAc,SAAiB,SAA0B;CAChE,IAAI,CAACC,aAAAA,aAAa,KAAK,CAAC,QAAQ,OAAO,UAAU,GAAG,GAAG,OAAO;CAE9D,QAAA,GAAOC,UAAAA,yBAAAA,CAAyB,YAAY,SAAS,QAAQ,OAAO,CAAC,CAAC,CACnE,MAAM,IAAI,CAAC,CACX,OAAO,SAAS,KAAK,UAAU,QAAQ,OAAO,OAAO;AAC1D;;;;;;AAOA,SAAgB,YAAY,EAAE,aAAa,UAA4F;CACrI,MAAM,CAAC,SAAS,cAAc;CAC9B,IAAI,OAAO,QAAQ,OAAO,SAAS,OAAO;CAC1C,IAAI,YAAY,UAAU,OAAO,eAAe,KAAA,KAAa,eAAe,aAAa,eAAe;CACxG,IAAI,YAAY,SAAS,YAAY,YAAY,YAAY,QAAQ,OAAOC,aAAAA,iBAAiB;EAAE,KAAK,OAAO;EAAK,QAAQ,OAAO,UAAU,OAAO;CAAW,CAAC;CAE5J,OAAO,YAAY,KAAA,KAAa,YAAY;AAC9C;;;;;;AAOA,SAAgB,UAAU,SAAiB,SAAyB;CAClE,OAAO,cAAc,SAAS,OAAO,IAAI,KAAK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IAAI,CAAC;CACzD,MAAM,SAAS,IAAI,IACjB,KAAK,KAAK,CAAC,CACR,MAAM,GAAG,CAAC,CACV,QAAQ,UAAU,CAAC,cAAc,IAAI,KAAK,CAAC,CAChD;CACA,OAAO,IACJ,KAAK,QAAQ;EACZ;EACA,UAAU,aAAa,KAAK,KAAK,GAAG,KAAK,EAAE,CAAC;EAC5C,QAAQ,KAAK,EAAE,CAAC,CACb,MAAM,GAAG,CAAC,CACV,MAAM,UAAU,OAAO,IAAI,KAAK,CAAC;CACtC,EAAE,CAAC,CACF,QAAQ,EAAE,UAAU,aAAa,UAAU,YAAY,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CACvG,MAAM,GAAG,MAAM,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,CAC9E,MAAM,GAAG,CAAC,CAAC,CACX,KAAK,EAAE,SAAS,EAAE;AACvB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry-DOGpflct.js","names":["sleep","process"],"sources":["../src/ui/mascot.ts","../src/utils/registry.ts"],"sourcesContent":["import { setTimeout as sleep } from 'node:timers/promises'\nimport { stripVTControlCharacters } from 'node:util'\nimport { isRichOutput } from '../utils/env.ts'\nimport { type Expression, getIntro, wakeUp } from '../loggers/banner.ts'\nimport { isInteractiveRun } from './intro.ts'\n\nfunction bannerIntro(version: string, expression: Expression, command: string): string {\n return getIntro({ title: 'Turn your API spec into type-safe code', description: `kubb ${command}`, version, expression })\n}\n\n/** Whether the mascot can be drawn: a rich, 256-color terminal wide enough that no line wraps and throws off a redraw. */\nfunction canDrawMascot(version: string, command: string): boolean {\n if (!isRichOutput() || !process.stdout.hasColors(256)) return false\n\n return stripVTControlCharacters(bannerIntro(version, 'open', command))\n .split('\\n')\n .every((line) => line.length <= process.stdout.columns)\n}\n\n/**\n * Whether a command opens with the mascot. Only the long-running ones do: `generate`, a Studio\n * session or pairing, and `add` or `update` while they ask questions. Quick commands print only\n * their result.\n */\nexport function wantsMascot({ commandPath, values }: { commandPath: ReadonlyArray<string>; values: Record<string, unknown> }): boolean {\n const [command, subCommand] = commandPath\n if (values.help || values.version) return false\n if (command === 'studio') return subCommand === undefined || subCommand === 'connect' || subCommand === 'login'\n if (command === 'add' || command === 'update' || command === 'init') return isInteractiveRun({ yes: values.yes, dryRun: values.dryRun ?? values['dry-run'] })\n\n return command === undefined || command === 'generate'\n}\n\n/**\n * The still Kubb mascot with the version and the running command, such as `studio connect`, or a\n * single version line where the terminal cannot draw it. Commands print it as their header; it\n * draws at once, with no wake-up frames.\n */\nexport function getBanner(version: string, command: string): string {\n return canDrawMascot(version, command) ? `\\n${bannerIntro(version, 'open', command)}` : `Kubb CLI v${version}`\n}\n\n/**\n * Opens `kubb generate` with the mascot playing its wake-up frames in place, which takes under a\n * second and overlaps the config load. Elsewhere the still {@link getBanner} is the header.\n */\nexport async function logBanner(version: string): Promise<void> {\n if (!canDrawMascot(version, 'generate')) {\n console.log(getBanner(version, 'generate'))\n\n return\n }\n\n console.log('')\n for (const [index, [expression, ms]] of wakeUp.entries()) {\n const frame = bannerIntro(version, expression, 'generate')\n if (index > 0) process.stdout.moveCursor(0, -frame.split('\\n').length)\n console.log(frame)\n await sleep(ms)\n }\n}\n","import process from 'node:process'\nimport { getErrorMessage, toError } from '@internals/utils'\nimport { checkCompatibility, Diagnostics, type ExtensionManifest, isRegistryEntry, type RegistryArtifact, type RegistryEntry } from '@kubb/core'\nimport { difference, isLessThan, isValid } from 'verkit'\n\nconst DEFAULT_REGISTRY = 'https://kubb.dev/registry'\n\nconst SLUG = '[a-z0-9]+(?:-[a-z0-9]+)*'\nconst ID = new RegExp(`^${SLUG}(\\\\/${SLUG})?$`)\n\n/** The registry base URL: `KUBB_REGISTRY`, or kubb.dev. */\nexport function registryUrl(): string {\n const url = process.env.KUBB_REGISTRY || DEFAULT_REGISTRY\n if (!/^https?:\\/\\//.test(url))\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `KUBB_REGISTRY must be an http(s) URL, got \"${url}\".`,\n help: 'Set `KUBB_REGISTRY` to an http(s) URL, or unset it to use https://kubb.dev/registry.',\n })\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Turns `owner/slug`, or a bare `slug` meaning `kubb-labs/<slug>`, into a registry id.\n *\n * @throws when the id has another shape, so it never reaches a URL unchecked.\n */\nexport function toRegistryId(input: string): string {\n if (!ID.test(input))\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `\"${input}\" is not a registry id. Use owner/slug, such as kubb-labs/plugin-zod, or a slug, such as plugin-zod.`,\n })\n return input.includes('/') ? input : `kubb-labs/${input}`\n}\n\n/** The shortest id `kubb add` and `kubb update` accept: the slug for an official extension, else `owner/slug`. */\nexport function toShortId(id: string): string {\n return id.startsWith('kubb-labs/') ? id.slice('kubb-labs/'.length) : id\n}\n\n/**\n * GETs `url` as JSON. A non-2xx answer or a body that is not JSON returns no `body`.\n * A network error throws with the URL.\n */\nasync function fetchJSON(url: string): Promise<{ status: number; body?: unknown }> {\n let response: Response\n try {\n response = await globalThis.fetch(url, { headers: { accept: 'application/json' } })\n } catch (cause) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Could not read ${url}: ${getErrorMessage(cause)}`,\n help: 'Check your network connection and that the registry is reachable.',\n cause: toError(cause),\n })\n }\n if (!response.ok) return { status: response.status }\n return { status: response.status, body: await response.json().catch(() => undefined) }\n}\n\n/** Fetches the registry index, leaving out entries that fail validation. */\nexport async function fetchRegistryIndex({ registry }: { registry: string }): Promise<Array<RegistryEntry>> {\n const { status, body } = await fetchJSON(`${registry}/index.json`)\n const index = body as { version?: unknown; extensions?: unknown } | null | undefined\n if (status !== 200 || index?.version !== 1 || !Array.isArray(index.extensions)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequestFailed,\n severity: 'error',\n message: `The registry at ${registry} sent an invalid index (HTTP ${status}).`,\n help: 'Try again later, or check that `KUBB_REGISTRY` points at a Kubb registry.',\n })\n }\n return index.extensions.filter(isRegistryEntry)\n}\n\n/** What the package manager installs: `<package>@<version>`, or a GitHub release's commit, so the install cannot move with the tag. */\nexport function installSpec(artifact: RegistryArtifact): string {\n return artifact.kind === 'github' ? `github:${artifact.owner}/${artifact.repo}#${artifact.commit}` : `${artifact.package}@${artifact.version}`\n}\n\n/** Why the running Kubb or Node.js version cannot use this extension, or `undefined` when it can. */\nexport function incompatibility(manifest: ExtensionManifest): string | undefined {\n try {\n checkCompatibility({ name: manifest.name, compatibility: manifest.compatibility })\n return undefined\n } catch (error) {\n return getErrorMessage(error)\n }\n}\n\n/**\n * Whether `latest` is newer than `installed`. An unknown installed version counts as outdated, and an\n * invalid `latest` never does.\n */\nexport function isOutdated({ installed, latest }: { installed: string | undefined; latest: string }): boolean {\n if (!isValid(latest)) return false\n return !installed || !isValid(installed) || isLessThan(installed, latest)\n}\n\n/** `major`, `minor`, or `patch` from `installed` to `latest`, or `undefined` when either is unknown or invalid. */\nexport function bumpOf({ installed, latest }: { installed: string | undefined; latest: string }): 'major' | 'minor' | 'patch' | undefined {\n if (!installed || !isValid(installed) || !isValid(latest)) return undefined\n const kind = difference(installed, latest)\n if (!kind) return undefined\n if (kind.endsWith('major')) return 'major'\n return kind.endsWith('minor') ? 'minor' : 'patch'\n}\n\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0]!\n row[0] = i\n for (let j = 1; j <= b.length; j++) {\n const current = row[j]!\n row[j] = Math.min(row[j]! + 1, row[j - 1]! + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))\n previous = current\n }\n }\n return row[b.length]!\n}\n\n/** Words every extension shares, so they never make two ids look alike. */\nconst COMMON_TOKENS = new Set(['kubb', 'plugin', 'adapter', 'parser'])\n\n/**\n * The ids closest to a mistyped `input`, best first, at most three: those within a few edits of it,\n * or sharing a word such as `zod` in any order. Compares slugs, so the owner may be left out.\n */\nexport function closestIds({ input, ids }: { input: string; ids: Array<string> }): Array<string> {\n const slug = (id: string) => id.slice(id.indexOf('/') + 1)\n const tokens = new Set(\n slug(input)\n .split('-')\n .filter((token) => !COMMON_TOKENS.has(token)),\n )\n return ids\n .map((id) => ({\n id,\n distance: editDistance(slug(input), slug(id)),\n shared: slug(id)\n .split('-')\n .some((token) => tokens.has(token)),\n }))\n .filter(({ distance, shared }) => shared || distance <= Math.max(2, Math.floor(slug(input).length / 4)))\n .sort((a, b) => Number(b.shared) - Number(a.shared) || a.distance - b.distance)\n .slice(0, 3)\n .map(({ id }) => id)\n}\n"],"mappings":";;;;;;;;;;AAMA,SAAS,YAAY,SAAiB,YAAwB,SAAyB;CACrF,OAAO,SAAS;EAAE,OAAO;EAA0C,aAAa,QAAQ;EAAW;EAAS;CAAW,CAAC;AAC1H;;AAGA,SAAS,cAAc,SAAiB,SAA0B;CAChE,IAAI,CAAC,aAAa,KAAK,CAAC,QAAQ,OAAO,UAAU,GAAG,GAAG,OAAO;CAE9D,OAAO,yBAAyB,YAAY,SAAS,QAAQ,OAAO,CAAC,CAAC,CACnE,MAAM,IAAI,CAAC,CACX,OAAO,SAAS,KAAK,UAAU,QAAQ,OAAO,OAAO;AAC1D;;;;;;AAOA,SAAgB,YAAY,EAAE,aAAa,UAA4F;CACrI,MAAM,CAAC,SAAS,cAAc;CAC9B,IAAI,OAAO,QAAQ,OAAO,SAAS,OAAO;CAC1C,IAAI,YAAY,UAAU,OAAO,eAAe,KAAA,KAAa,eAAe,aAAa,eAAe;CACxG,IAAI,YAAY,SAAS,YAAY,YAAY,YAAY,QAAQ,OAAO,iBAAiB;EAAE,KAAK,OAAO;EAAK,QAAQ,OAAO,UAAU,OAAO;CAAW,CAAC;CAE5J,OAAO,YAAY,KAAA,KAAa,YAAY;AAC9C;;;;;;AAOA,SA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CAAC;EAC5C,QAAQ,KAAK,EAAE,CAAC,CACb,MAAM,GAAG,CAAC,CACV,MAAM,UAAU,OAAO,IAAI,KAAK,CAAC;CACtC,EAAE,CAAC,CACF,QAAQ,EAAE,UAAU,aAAa,UAAU,YAAY,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CACvG,MAAM,GAAG,MAAM,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,CAC9E,MAAM,GAAG,CAAC,CAAC,CACX,KAAK,EAAE,SAAS,EAAE;AACvB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-9fs2T2Je.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/copyToClipboard.ts","../../../internals/utils/src/openInBrowser.ts","../src/runners/studio/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst COMMANDS: Partial<Record<NodeJS.Platform, [string, ...Array<string>]>> = {\n darwin: ['pbcopy'],\n win32: ['clip.exe'],\n linux: ['xclip', '-selection', 'clipboard'],\n}\n\n/**\n * Copies text to the system clipboard with the platform's own tool. Resolves `false` in CI, on a\n * platform without a known tool, or when the tool is missing or fails.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n // Wayland sessions have no X selection for xclip to serve, so they use `wl-copy`.\n const command = process.platform === 'linux' && process.env.WAYLAND_DISPLAY ? (['wl-copy'] as const) : COMMANDS[process.platform]\n if (!command || isCIEnvironment()) return false\n\n const [name, ...args] = command\n // stdout and stderr are ignored: xclip and wl-copy stay alive to serve the selection and would hold open pipes until the timeout.\n const run = x(name, args, { timeout: 2_000, nodeOptions: { stdio: ['pipe', 'ignore', 'ignore'] } })\n // A missing tool closes stdin before the write lands; the rejection below reports it.\n run.process?.stdin?.once('error', () => {})\n run.process?.stdin?.end(text)\n\n return run.then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","import { hostname } from 'node:os'\nimport { toPermissionFlag } from '../../ui/text.ts'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { copyToClipboard, isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { connectAgent, defaultStudioUrl, InvalidAgentTokenError, pairAgent, PairingCanceledError } from '@kubb/studio'\nimport { AgentPermission } from '@kubb/studio/protocol'\nimport { trackRun } from '../../Telemetry.ts'\nimport { plainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { logIntro, logOutro, logTip } from '../../ui/intro.ts'\nimport { logBlock, logStep } from '../../ui/log.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { canUseTTY, isRichOutput } from '../../utils/env.ts'\nimport { getConfigs } from '../../config.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getMachineId, readCredentials, writeCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\nexport type StudioOptions = {\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<AgentPermission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport type SnapshotOptions = Pick<StudioOptions, 'configPath' | 'studioUrl' | 'logLevel'> & {\n /**\n * Organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * Stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /** Identity of another CI agent to also compare with. Falls back to CI auto-detection. */\n baseId?: string\n /**\n * Package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * Package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/** The flags a `kubb studio` subcommand parsed; each one is optional since a subcommand declares only the flags it uses. */\nexport type StudioValues = {\n config?: string\n url?: string\n allowRead?: boolean\n allowReadAst?: boolean\n allowWrite?: boolean\n allowConfigEdit?: boolean\n allowInstall?: boolean\n allowUpdate?: boolean\n allowRemove?: boolean\n allowSaveInput?: boolean\n allowExec?: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nexport async function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const spinner = createSpinner()\n // A retry notice stays on screen a while before the countdown takes the line back.\n let retryUntil = 0\n // The spinner only starts once a code is shown.\n let waiting = false\n let countdown: NodeJS.Timeout | undefined\n\n try {\n const { token, agent } = await pairAgent({\n studioUrl,\n type: 'cli',\n name: path.basename(process.cwd()),\n hostname: hostname(),\n machineId: await getMachineId(),\n signal,\n onCode: (session) => {\n logStep(\n [\n 'Pair this machine',\n `${styleText('dim', 'Open')} ${styleText('cyan', session.verification_uri)}`,\n `${styleText('dim', 'Code')} ${styleText('bold', session.user_code)}`,\n ].join('\\n'),\n )\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n // Same fallback as the poll in `@kubb/studio`, so the countdown ends when polling does.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let copied = false\n const waitingText = () =>\n `Waiting for approval ${styleText('dim', `expires in ${formatCountdown(deadline - Date.now())}${copied ? ' · code copied' : ''} · ctrl+c to cancel`)}`\n clearInterval(countdown)\n spinner.start(waitingText())\n waiting = true\n // Plain output prints every message, so only an animated spinner ticks.\n if (isRichOutput()) countdown = setInterval(() => Date.now() > retryUntil && spinner.message(waitingText()), 1000)\n // Not awaited: the code shows at once, and the spinner picks up the copy when it lands.\n void copyToClipboard(session.user_code).then((done) => {\n copied = done\n })\n },\n onRetry: (error) => {\n retryUntil = Date.now() + 5000\n spinner.message(`Could not reach Kubb Studio, retrying: ${error.message}`)\n },\n })\n clearInterval(countdown)\n spinner.stop(`Paired as ${agent.name}${agent.organizationSlug ? ` · org ${agent.organizationSlug}` : ''}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}),\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n clearInterval(countdown)\n if (waiting) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n }\n throw error\n }\n}\n\n/** Time left on a pairing code as `m:ss`, never below `0:00`. */\nexport function formatCountdown(ms: number): string {\n const seconds = Math.max(0, Math.ceil(ms / 1000))\n\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`\n}\n\n/**\n * What each permission is asked as, in the order the list shows them.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: AgentPermission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n title: (configPath: string) => string\n hint: string\n}> = [\n { key: AgentPermission.READ, label: 'read source', title: () => 'Read generated files', hint: 'show code in the browser' },\n { key: AgentPermission.READ_AST, label: 'read spec', title: () => 'Read the parsed spec', hint: 'browse schemas and operations' },\n { key: AgentPermission.WRITE, label: 'write files', title: () => 'Write files to disk', hint: 'generate from the browser' },\n { key: AgentPermission.CONFIG_EDIT, label: 'edit config', title: (configPath) => `Change ${configPath}`, hint: 'edit plugin options' },\n { key: AgentPermission.INSTALL, label: 'add plugins', title: () => 'Install extensions from the registry', hint: 'kubb add from the browser' },\n { key: AgentPermission.UPDATE, label: 'update plugins', title: () => 'Update installed extensions', hint: 'kubb update from the browser' },\n { key: AgentPermission.REMOVE, label: 'remove plugins', title: () => 'Remove extensions', hint: 'kubb remove from the browser' },\n {\n key: AgentPermission.SAVE_INPUT,\n label: 'save input',\n title: (configPath) => `Save the spec from Studio as the input in ${configPath}`,\n hint: 'keep a pasted spec, URL, or git file',\n },\n { key: AgentPermission.EXEC, label: 'run tools', title: () => 'Run the formatter, linter, and postGenerate', hint: 'after each generation' },\n]\n\n/**\n * Two permissions per row, each marked granted or not, with the flags that grant the missing ones\n * after the last row. For `kubb studio status`.\n */\nexport function formatPermissionRows(granted: Partial<Record<AgentPermission, boolean>>): Array<string> {\n const width = Math.max(...PERMISSIONS.map(({ label }) => label.length))\n const cells = PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✓') : styleText('red', '✖')} ${label.padEnd(width)}`)\n const rows = Array.from({ length: Math.ceil(cells.length / 2) }, (_, index) => cells.slice(index * 2, index * 2 + 2).join(' '))\n const flags = PERMISSIONS.filter(({ key }) => !granted[key])\n .map(({ key }) => toPermissionFlag(key))\n .join(' ')\n\n return flags ? [...rows.slice(0, -1), `${rows.at(-1)} ${styleText('dim', flags)}`] : rows\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and the rest are asked in one list whose answers are stored\n * in `~/.kubb/credentials.json`.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n): Promise<Record<AgentPermission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted = Object.fromEntries(PERMISSIONS.map(({ key }) => [key, options.permission[key] || remembered?.[key] === true])) as Record<\n AgentPermission,\n boolean\n >\n const pending = PERMISSIONS.filter(({ key }) => !options.permission[key] && typeof remembered?.[key] !== 'boolean')\n\n if (!pending.length || isCIEnvironment() || !canUseTTY()) return granted\n\n prompts.updateSettings({ withGuide: true })\n const selected = await prompts.multiselect({\n message: 'What may Kubb Studio do in this project?',\n options: pending.map(({ key, title, hint }) => ({ value: key, label: title(configPath), hint })),\n required: false,\n })\n // A canceled list grants nothing and saves nothing, so the next run asks again.\n if (prompts.isCancel(selected)) return granted\n\n const answers = Object.fromEntries(pending.map(({ key }) => [key, selected.includes(key)]))\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n\n return { ...granted, ...answers }\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does, one entry per `defineConfig(...)` entry.\n */\nexport async function loadConfigs(options: Pick<StudioOptions, 'configPath' | 'logLevel'>): Promise<{ configPath: string; configs: Array<Config> }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n\n if (!configs.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Config not defined, create a kubb.config.ts or pass it with --config',\n })\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, configs }\n}\n\nexport type PreparedConnection = {\n configPath: string\n credentials: Credentials\n permissions: StudioOptions['permission']\n}\n\n/** Validates the project and resolves pairing and permissions before starting its worker. */\nexport async function prepareConnection(options: StudioOptions, signal?: AbortSignal): Promise<PreparedConnection> {\n const { configPath } = await loadConfigs(options)\n const stored = await readCredentials()\n const credentials = await (async () => {\n if (stored?.studioUrl === options.studioUrl) return stored\n if (isCIEnvironment()) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Not paired with ${options.studioUrl}. In CI, run \\`kubb studio snapshot\\` instead, or run \\`kubb studio login\\` on a machine with a browser.`,\n })\n }\n return login(options, { signal })\n })()\n const permissions = await resolvePermissions(options, credentials, configPath)\n return { configPath, credentials, permissions }\n}\n\nexport type WorkerState = 'starting' | 'connected' | 'reconnecting' | 'authentication required' | 'stopped'\n\n/** Runs the same project connection in the foreground or in a background worker. */\nexport async function connect(\n options: StudioOptions,\n context: {\n prepared?: PreparedConnection\n signal?: AbortSignal\n onState?: (state: WorkerState) => void | Promise<void>\n } = {},\n): Promise<void> {\n const shutdown = new AbortController()\n const signal = context.signal ?? shutdown.signal\n const stop = () => shutdown.abort()\n const events = process as unknown as NodeJS.EventEmitter\n if (!context.signal) {\n events.once('SIGINT', stop)\n events.once('SIGTERM', stop)\n }\n let unwatch: (() => void) | undefined\n try {\n if (!context.prepared) {\n const { getWorkerStatus } = await import('./background.ts')\n const worker = await getWorkerStatus()\n if (worker.running)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'This project is running in the background. Run `kubb studio stop` first.',\n })\n }\n const prepared = context.prepared ?? (await prepareConnection(options, signal))\n let { credentials, permissions } = prepared\n const { configPath } = prepared\n let hinted = false\n // Set by a fresh pairing until it connects, so a token rejected right after approval fails the run instead of looping.\n let pairedAgain = false\n\n // The background worker writes to a log file, so it gets the plain logger rather than the\n // animated one. The logger also covers the `studio:*` events and each generation run.\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, {\n logLevel: logLevelMap[options.logLevel ?? 'info'],\n reporters: [cliReporter],\n ...(context.onState ? { writer: plainWriter } : {}),\n })\n // `b` hands the session to the background worker; only a foreground run in a terminal listens.\n const listens = !context.onState && process.stdin.isTTY === true && canUseTTY()\n let background = false\n hooks.hook('studio:connected', async () => {\n pairedAgain = false\n await context.onState?.('connected')\n if (listens && !unwatch) {\n unwatch = watchKeys({\n onBackground: () => {\n background = true\n stop()\n },\n onStop: stop,\n })\n }\n if (hinted || context.onState || options.logLevel === 'silent') return\n hinted = true\n logBlock([\n `${styleText('dim', 'Project')} ${path.basename(process.cwd())} ${styleText(\n 'dim',\n PERMISSIONS.filter(({ key }) => permissions[key])\n .map(({ label }) => label)\n .join(' · ') || 'no permissions',\n )}`,\n styleText('dim', listens ? 'Press b to keep running in the background, Ctrl+C to disconnect' : 'Press Ctrl+C to disconnect'),\n ])\n logTip()\n })\n hooks.hook('studio:reconnecting', () => context.onState?.('reconnecting'))\n\n for (;;) {\n try {\n await connectAgent({\n token: credentials.token,\n studioUrl: options.studioUrl,\n configPath,\n version: options.version,\n root: process.cwd(),\n permissions,\n loadConfigs: async () => (await loadConfigs(options)).configs,\n hooks,\n signal,\n })\n break\n } catch (error) {\n if (!(error instanceof InvalidAgentTokenError)) throw error\n await context.onState?.('authentication required')\n await clearCredentials()\n if (pairedAgain) throw new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n if (context.onState || isCIEnvironment() || !canUseTTY()) throw new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n\n // The pairing prompts need stdin back.\n unwatch?.()\n unwatch = undefined\n console.log(styleText('yellow', `${error.message} Pairing again...`))\n credentials = await login(options, { signal, previousCredentials: credentials })\n pairedAgain = true\n permissions = await resolvePermissions(options, credentials, configPath)\n }\n }\n // Stops the \"Ready for jobs\" spinner, which would otherwise keep drawing under the closing line.\n await hooks.callHook('kubb:lifecycle:end')\n unwatch?.()\n if (background) {\n const { startWorker } = await import('./background.ts')\n await startWorker(options)\n if (options.logLevel !== 'silent') logOutro('Running in the background · kubb studio stop')\n return\n }\n if (!context.onState && signal.aborted && options.logLevel !== 'silent') logOutro('Disconnected')\n } catch (error) {\n if (!(error instanceof PairingCanceledError)) throw error\n } finally {\n unwatch?.()\n events.off('SIGINT', stop)\n events.off('SIGTERM', stop)\n }\n}\n\n/**\n * Listens for single keys on a TTY stdin. Raw mode turns Ctrl+C into a key instead of SIGINT, so it\n * is handled here too. Returns the function that restores the terminal, safe to call twice.\n */\nexport function watchKeys({ onBackground, onStop }: { onBackground: () => void; onStop: () => void }): () => void {\n const stdin = process.stdin\n const onData = (data: Buffer) => {\n const key = data.toString()\n if (key === 'b' || key === 'B') onBackground()\n if (key === '\\u0003') onStop()\n }\n // A clack spinner reads stdin too and exits the process on Ctrl+C, before the session can close\n // its socket, so its Ctrl+C alias is lifted while these keys are read.\n const cancelAlias = prompts.settings.aliases.get('\\u0003')\n prompts.settings.aliases.delete('\\u0003')\n stdin.setRawMode(true)\n stdin.on('data', onData)\n stdin.resume()\n let restored = false\n\n return () => {\n if (restored) return\n restored = true\n if (cancelAlias) prompts.settings.aliases.set('\\u0003', cancelAlias)\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n }\n}\n\n/**\n * Runs a Studio command from its parsed flags: builds the {@link StudioOptions}, prints the intro,\n * and reports the run to telemetry. A failure is printed and sets the exit code instead of throwing.\n */\nexport async function runStudio(\n values: StudioValues,\n action: (options: StudioOptions) => Promise<unknown>,\n { block = false, json = false }: { block?: boolean; json?: boolean } = {},\n): Promise<void> {\n const options: StudioOptions = {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: Object.fromEntries(Object.values(AgentPermission).map((key) => [key, values[key] ?? false])) as Record<AgentPermission, boolean>,\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\n const report = trackRun({ command: 'studio', hrStart: process.hrtime() })\n\n try {\n if (options.logLevel !== 'silent' && !json) {\n logIntro({\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n block,\n })\n }\n\n await action(options)\n\n await report({ status: 'success' })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,WAAyE;CAC7E,QAAQ,CAAC,QAAQ;CACjB,OAAO,CAAC,UAAU;CAClB,OAAO;EAAC;EAAS;EAAc;CAAW;AAC5C;;;;;AAMA,eAAsB,gBAAgB,MAAgC;CAEpE,MAAM,UAAU,QAAQ,aAAa,WAAW,QAAQ,IAAI,kBAAmB,CAAC,SAAS,IAAc,SAAS,QAAQ;CACxH,IAAI,CAAC,WAAW,gBAAgB,GAAG,OAAO;CAE1C,MAAM,CAAC,MAAM,GAAG,QAAQ;CAExB,MAAM,MAAM,EAAE,MAAM,MAAM;EAAE,SAAS;EAAO,aAAa,EAAE,OAAO;GAAC;GAAQ;GAAU;EAAQ,EAAE;CAAE,CAAC;CAElG,IAAI,SAAS,OAAO,KAAK,eAAe,CAAC,CAAC;CAC1C,IAAI,SAAS,OAAO,IAAI,IAAI;CAE5B,OAAO,IAAI,MACR,EAAE,eAAe,aAAa,SACzB,KACR;AACF;;;AC1BA,MAAM,eAAe,CAAC;;;;AAKtB,SAAgB,cAAc,QAAsB;CAClD,IAAI,gBAAgB,GAAG;CAEvB,IAAI,QAAQ,aAAa,SAAS;EAChC,EAAE,OAAO;GAAC;GAAM;GAAS;GAAI;EAA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zB,UAAU,OAAO;CACnB;CACA,MAAM,SAAS,SAAS;EAAE,SAAS;EAAU,SAAS,QAAQ,OAAO;CAAE,CAAC;CAExE,IAAI;EACF,IAAI,QAAQ,aAAa,YAAY,CAAC,MACpC,SAAS;GACP,SAAS,UAAU,UAAU,2DAA2D;GACxF;EACF,CAAC;EAGH,MAAM,OAAO,OAAO;EAEpB,MAAM,OAAO,EAAE,QAAQ,UAAU,CAAC;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-C8Prej7s.cjs","names":["process","isCIEnvironment","x","isCIEnvironment","process","createSpinner","pairAgent","path","process","hostname","getMachineId","styleText","isRichOutput","writeCredentials","getCredentialsPath","PairingCanceledError","AgentPermission","toPermissionFlag","KUBB_CONFIG_FILENAME","isCIEnvironment","canUseTTY","prompts","getConfigs","Diagnostics","readCredentials","Hookable","logLevelMap","cliReporter","plainWriter","connectAgent","InvalidAgentTokenError","clearCredentials","defaultStudioUrl","trackRun","toError"],"sources":["../../../internals/utils/src/copyToClipboard.ts","../../../internals/utils/src/openInBrowser.ts","../src/runners/studio/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst COMMANDS: Partial<Record<NodeJS.Platform, [string, ...Array<string>]>> = {\n darwin: ['pbcopy'],\n win32: ['clip.exe'],\n linux: ['xclip', '-selection', 'clipboard'],\n}\n\n/**\n * Copies text to the system clipboard with the platform's own tool. Resolves `false` in CI, on a\n * platform without a known tool, or when the tool is missing or fails.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n // Wayland sessions have no X selection for xclip to serve, so they use `wl-copy`.\n const command = process.platform === 'linux' && process.env.WAYLAND_DISPLAY ? (['wl-copy'] as const) : COMMANDS[process.platform]\n if (!command || isCIEnvironment()) return false\n\n const [name, ...args] = command\n // stdout and stderr are ignored: xclip and wl-copy stay alive to serve the selection and would hold open pipes until the timeout.\n const run = x(name, args, { timeout: 2_000, nodeOptions: { stdio: ['pipe', 'ignore', 'ignore'] } })\n // A missing tool closes stdin before the write lands; the rejection below reports it.\n run.process?.stdin?.once('error', () => {})\n run.process?.stdin?.end(text)\n\n return run.then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","import { hostname } from 'node:os'\nimport { toPermissionFlag } from '../../ui/text.ts'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { copyToClipboard, isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { connectAgent, defaultStudioUrl, InvalidAgentTokenError, pairAgent, PairingCanceledError } from '@kubb/studio'\nimport { AgentPermission } from '@kubb/studio/protocol'\nimport { trackRun } from '../../Telemetry.ts'\nimport { plainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { logIntro, logOutro, logTip } from '../../ui/intro.ts'\nimport { logBlock, logStep } from '../../ui/log.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { canUseTTY, isRichOutput } from '../../utils/env.ts'\nimport { getConfigs } from '../../config.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getMachineId, readCredentials, writeCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\nexport type StudioOptions = {\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<AgentPermission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport type SnapshotOptions = Pick<StudioOptions, 'configPath' | 'studioUrl' | 'logLevel'> & {\n /**\n * Organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * Stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /** Identity of another CI agent to also compare with. Falls back to CI auto-detection. */\n baseId?: string\n /**\n * Package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * Package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/** The flags a `kubb studio` subcommand parsed; each one is optional since a subcommand declares only the flags it uses. */\nexport type StudioValues = {\n config?: string\n url?: string\n allowRead?: boolean\n allowReadAst?: boolean\n allowWrite?: boolean\n allowConfigEdit?: boolean\n allowInstall?: boolean\n allowUpdate?: boolean\n allowRemove?: boolean\n allowSaveInput?: boolean\n allowExec?: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nexport async function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const spinner = createSpinner()\n // A retry notice stays on screen a while before the countdown takes the line back.\n let retryUntil = 0\n // The spinner only starts once a code is shown.\n let waiting = false\n let countdown: NodeJS.Timeout | undefined\n\n try {\n const { token, agent } = await pairAgent({\n studioUrl,\n type: 'cli',\n name: path.basename(process.cwd()),\n hostname: hostname(),\n machineId: await getMachineId(),\n signal,\n onCode: (session) => {\n logStep(\n [\n 'Pair this machine',\n `${styleText('dim', 'Open')} ${styleText('cyan', session.verification_uri)}`,\n `${styleText('dim', 'Code')} ${styleText('bold', session.user_code)}`,\n ].join('\\n'),\n )\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n // Same fallback as the poll in `@kubb/studio`, so the countdown ends when polling does.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let copied = false\n const waitingText = () =>\n `Waiting for approval ${styleText('dim', `expires in ${formatCountdown(deadline - Date.now())}${copied ? ' · code copied' : ''} · ctrl+c to cancel`)}`\n clearInterval(countdown)\n spinner.start(waitingText())\n waiting = true\n // Plain output prints every message, so only an animated spinner ticks.\n if (isRichOutput()) countdown = setInterval(() => Date.now() > retryUntil && spinner.message(waitingText()), 1000)\n // Not awaited: the code shows at once, and the spinner picks up the copy when it lands.\n void copyToClipboard(session.user_code).then((done) => {\n copied = done\n })\n },\n onRetry: (error) => {\n retryUntil = Date.now() + 5000\n spinner.message(`Could not reach Kubb Studio, retrying: ${error.message}`)\n },\n })\n clearInterval(countdown)\n spinner.stop(`Paired as ${agent.name}${agent.organizationSlug ? ` · org ${agent.organizationSlug}` : ''}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}),\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n clearInterval(countdown)\n if (waiting) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n }\n throw error\n }\n}\n\n/** Time left on a pairing code as `m:ss`, never below `0:00`. */\nexport function formatCountdown(ms: number): string {\n const seconds = Math.max(0, Math.ceil(ms / 1000))\n\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`\n}\n\n/**\n * What each permission is asked as, in the order the list shows them.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: AgentPermission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n title: (configPath: string) => string\n hint: string\n}> = [\n { key: AgentPermission.READ, label: 'read source', title: () => 'Read generated files', hint: 'show code in the browser' },\n { key: AgentPermission.READ_AST, label: 'read spec', title: () => 'Read the parsed spec', hint: 'browse schemas and operations' },\n { key: AgentPermission.WRITE, label: 'write files', title: () => 'Write files to disk', hint: 'generate from the browser' },\n { key: AgentPermission.CONFIG_EDIT, label: 'edit config', title: (configPath) => `Change ${configPath}`, hint: 'edit plugin options' },\n { key: AgentPermission.INSTALL, label: 'add plugins', title: () => 'Install extensions from the registry', hint: 'kubb add from the browser' },\n { key: AgentPermission.UPDATE, label: 'update plugins', title: () => 'Update installed extensions', hint: 'kubb update from the browser' },\n { key: AgentPermission.REMOVE, label: 'remove plugins', title: () => 'Remove extensions', hint: 'kubb remove from the browser' },\n {\n key: AgentPermission.SAVE_INPUT,\n label: 'save input',\n title: (configPath) => `Save the spec from Studio as the input in ${configPath}`,\n hint: 'keep a pasted spec, URL, or git file',\n },\n { key: AgentPermission.EXEC, label: 'run tools', title: () => 'Run the formatter, linter, and postGenerate', hint: 'after each generation' },\n]\n\n/**\n * Two permissions per row, each marked granted or not, with the flags that grant the missing ones\n * after the last row. For `kubb studio status`.\n */\nexport function formatPermissionRows(granted: Partial<Record<AgentPermission, boolean>>): Array<string> {\n const width = Math.max(...PERMISSIONS.map(({ label }) => label.length))\n const cells = PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✓') : styleText('red', '✖')} ${label.padEnd(width)}`)\n const rows = Array.from({ length: Math.ceil(cells.length / 2) }, (_, index) => cells.slice(index * 2, index * 2 + 2).join(' '))\n const flags = PERMISSIONS.filter(({ key }) => !granted[key])\n .map(({ key }) => toPermissionFlag(key))\n .join(' ')\n\n return flags ? [...rows.slice(0, -1), `${rows.at(-1)} ${styleText('dim', flags)}`] : rows\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and the rest are asked in one list whose answers are stored\n * in `~/.kubb/credentials.json`.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n): Promise<Record<AgentPermission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted = Object.fromEntries(PERMISSIONS.map(({ key }) => [key, options.permission[key] || remembered?.[key] === true])) as Record<\n AgentPermission,\n boolean\n >\n const pending = PERMISSIONS.filter(({ key }) => !options.permission[key] && typeof remembered?.[key] !== 'boolean')\n\n if (!pending.length || isCIEnvironment() || !canUseTTY()) return granted\n\n prompts.updateSettings({ withGuide: true })\n const selected = await prompts.multiselect({\n message: 'What may Kubb Studio do in this project?',\n options: pending.map(({ key, title, hint }) => ({ value: key, label: title(configPath), hint })),\n required: false,\n })\n // A canceled list grants nothing and saves nothing, so the next run asks again.\n if (prompts.isCancel(selected)) return granted\n\n const answers = Object.fromEntries(pending.map(({ key }) => [key, selected.includes(key)]))\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n\n return { ...granted, ...answers }\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does, one entry per `defineConfig(...)` entry.\n */\nexport async function loadConfigs(options: Pick<StudioOptions, 'configPath' | 'logLevel'>): Promise<{ configPath: string; configs: Array<Config> }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n\n if (!configs.length) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Config not defined, create a kubb.config.ts or pass it with --config',\n })\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, configs }\n}\n\nexport type PreparedConnection = {\n configPath: string\n credentials: Credentials\n permissions: StudioOptions['permission']\n}\n\n/** Validates the project and resolves pairing and permissions before starting its worker. */\nexport async function prepareConnection(options: StudioOptions, signal?: AbortSignal): Promise<PreparedConnection> {\n const { configPath } = await loadConfigs(options)\n const stored = await readCredentials()\n const credentials = await (async () => {\n if (stored?.studioUrl === options.studioUrl) return stored\n if (isCIEnvironment()) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Not paired with ${options.studioUrl}. In CI, run \\`kubb studio snapshot\\` instead, or run \\`kubb studio login\\` on a machine with a browser.`,\n })\n }\n return login(options, { signal })\n })()\n const permissions = await resolvePermissions(options, credentials, configPath)\n return { configPath, credentials, permissions }\n}\n\nexport type WorkerState = 'starting' | 'connected' | 'reconnecting' | 'authentication required' | 'stopped'\n\n/** Runs the same project connection in the foreground or in a background worker. */\nexport async function connect(\n options: StudioOptions,\n context: {\n prepared?: PreparedConnection\n signal?: AbortSignal\n onState?: (state: WorkerState) => void | Promise<void>\n } = {},\n): Promise<void> {\n const shutdown = new AbortController()\n const signal = context.signal ?? shutdown.signal\n const stop = () => shutdown.abort()\n const events = process as unknown as NodeJS.EventEmitter\n if (!context.signal) {\n events.once('SIGINT', stop)\n events.once('SIGTERM', stop)\n }\n let unwatch: (() => void) | undefined\n try {\n if (!context.prepared) {\n const { getWorkerStatus } = await import('./background.ts')\n const worker = await getWorkerStatus()\n if (worker.running)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'This project is running in the background. Run `kubb studio stop` first.',\n })\n }\n const prepared = context.prepared ?? (await prepareConnection(options, signal))\n let { credentials, permissions } = prepared\n const { configPath } = prepared\n let hinted = false\n // Set by a fresh pairing until it connects, so a token rejected right after approval fails the run instead of looping.\n let pairedAgain = false\n\n // The background worker writes to a log file, so it gets the plain logger rather than the\n // animated one. The logger also covers the `studio:*` events and each generation run.\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, {\n logLevel: logLevelMap[options.logLevel ?? 'info'],\n reporters: [cliReporter],\n ...(context.onState ? { writer: plainWriter } : {}),\n })\n // `b` hands the session to the background worker; only a foreground run in a terminal listens.\n const listens = !context.onState && process.stdin.isTTY === true && canUseTTY()\n let background = false\n hooks.hook('studio:connected', async () => {\n pairedAgain = false\n await context.onState?.('connected')\n if (listens && !unwatch) {\n unwatch = watchKeys({\n onBackground: () => {\n background = true\n stop()\n },\n onStop: stop,\n })\n }\n if (hinted || context.onState || options.logLevel === 'silent') return\n hinted = true\n logBlock([\n `${styleText('dim', 'Project')} ${path.basename(process.cwd())} ${styleText(\n 'dim',\n PERMISSIONS.filter(({ key }) => permissions[key])\n .map(({ label }) => label)\n .join(' · ') || 'no permissions',\n )}`,\n styleText('dim', listens ? 'Press b to keep running in the background, Ctrl+C to disconnect' : 'Press Ctrl+C to disconnect'),\n ])\n logTip()\n })\n hooks.hook('studio:reconnecting', () => context.onState?.('reconnecting'))\n\n for (;;) {\n try {\n await connectAgent({\n token: credentials.token,\n studioUrl: options.studioUrl,\n configPath,\n version: options.version,\n root: process.cwd(),\n permissions,\n loadConfigs: async () => (await loadConfigs(options)).configs,\n hooks,\n signal,\n })\n break\n } catch (error) {\n if (!(error instanceof InvalidAgentTokenError)) throw error\n await context.onState?.('authentication required')\n await clearCredentials()\n if (pairedAgain) throw new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n if (context.onState || isCIEnvironment() || !canUseTTY()) throw new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n\n // The pairing prompts need stdin back.\n unwatch?.()\n unwatch = undefined\n console.log(styleText('yellow', `${error.message} Pairing again...`))\n credentials = await login(options, { signal, previousCredentials: credentials })\n pairedAgain = true\n permissions = await resolvePermissions(options, credentials, configPath)\n }\n }\n // Stops the \"Ready for jobs\" spinner, which would otherwise keep drawing under the closing line.\n await hooks.callHook('kubb:lifecycle:end')\n unwatch?.()\n if (background) {\n const { startWorker } = await import('./background.ts')\n await startWorker(options)\n if (options.logLevel !== 'silent') logOutro('Running in the background · kubb studio stop')\n return\n }\n if (!context.onState && signal.aborted && options.logLevel !== 'silent') logOutro('Disconnected')\n } catch (error) {\n if (!(error instanceof PairingCanceledError)) throw error\n } finally {\n unwatch?.()\n events.off('SIGINT', stop)\n events.off('SIGTERM', stop)\n }\n}\n\n/**\n * Listens for single keys on a TTY stdin. Raw mode turns Ctrl+C into a key instead of SIGINT, so it\n * is handled here too. Returns the function that restores the terminal, safe to call twice.\n */\nexport function watchKeys({ onBackground, onStop }: { onBackground: () => void; onStop: () => void }): () => void {\n const stdin = process.stdin\n const onData = (data: Buffer) => {\n const key = data.toString()\n if (key === 'b' || key === 'B') onBackground()\n if (key === '\\u0003') onStop()\n }\n // A clack spinner reads stdin too and exits the process on Ctrl+C, before the session can close\n // its socket, so its Ctrl+C alias is lifted while these keys are read.\n const cancelAlias = prompts.settings.aliases.get('\\u0003')\n prompts.settings.aliases.delete('\\u0003')\n stdin.setRawMode(true)\n stdin.on('data', onData)\n stdin.resume()\n let restored = false\n\n return () => {\n if (restored) return\n restored = true\n if (cancelAlias) prompts.settings.aliases.set('\\u0003', cancelAlias)\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n }\n}\n\n/**\n * Runs a Studio command from its parsed flags: builds the {@link StudioOptions}, prints the intro,\n * and reports the run to telemetry. A failure is printed and sets the exit code instead of throwing.\n */\nexport async function runStudio(\n values: StudioValues,\n action: (options: StudioOptions) => Promise<unknown>,\n { block = false, json = false }: { block?: boolean; json?: boolean } = {},\n): Promise<void> {\n const options: StudioOptions = {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: Object.fromEntries(Object.values(AgentPermission).map((key) => [key, values[key] ?? false])) as Record<AgentPermission, boolean>,\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\n const report = trackRun({ command: 'studio', hrStart: process.hrtime() })\n\n try {\n if (options.logLevel !== 'silent' && !json) {\n logIntro({\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n block,\n })\n }\n\n await action(options)\n\n await report({ status: 'success' })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,WAAyE;CAC7E,QAAQ,CAAC,QAAQ;CACjB,OAAO,CAAC,UAAU;CAClB,OAAO;EAAC;EAAS;EAAc;CAAW;AAC5C;;;;;AAMA,eAAsB,gBAAgB,MAAgC;CAEpE,MAAM,UAAUA,aAAAA,QAAQ,aAAa,WAAWA,aAAAA,QAAQ,IAAI,kBAAmB,CAAC,SAAS,IAAc,SAASA,aAAAA,QAAQ;CACxH,IAAI,CAAC,WAAWC,kBAAAA,gBAAgB,GAAG,OAAO;CAE1C,MAAM,CAAC,MAAM,GAAG,QAAQ;CAExB,MAAM,OAAA,GAAMC,SAAAA,EAAAA,CAAE,MAAM,MAAM;EAAE,SAAS;EAAO,aAAa,EAAE,OAAO;GAAC;GAAQ;GAAU;EAAQ,EAAE;C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AK,QAAQ,CAAC,KAAK,OAAO,QAAQ,KAAK,CAAC,CAAC;EACvG,UAAU,OAAO,QAAQ;EACzB,UAAU,OAAO;CACnB;CACA,MAAM,SAASiB,kBAAAA,SAAS;EAAE,SAAS;EAAU,SAASzB,aAAAA,QAAQ,OAAO;CAAE,CAAC;CAExE,IAAI;EACF,IAAI,QAAQ,aAAa,YAAY,CAAC,MACpC,aAAA,SAAS;GACP,UAAA,GAASG,UAAAA,UAAAA,CAAU,UAAU,2DAA2D;GACxF;EACF,CAAC;EAGH,MAAM,OAAO,OAAO;EAEpB,MAAM,OAAO,EAAE,QAAQ,UAAU,CAAC;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAMuB,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF"}
@@ -1 +0,0 @@
1
- export { t as connect, a as login, c as runStudio } from "./run-9fs2T2Je.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-DC_xH5H3.cjs","names":["trackRun","process","memoryStorage","createKubb","isOutdated","version","Diagnostics","styleText","pluralize","formatMs","logLevelMap","Hookable","cliReporter","createPlainWriter","logBanner","getConfigs","createSpinner","path","jsonReporter","fileReporter","htmlReporter","selectReporters","trackBuild","getInputKind","diffBuilds","getElapsedMs","listenForKeys","startWatcher","logInfo","logError"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, formatters, getElapsedMs, linters } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { trackRun } from '../../Telemetry.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport { logIntro, logOutro, logSpacer, logTip } from '../../ui/intro.ts'\nimport { logError, logInfo, logStep, logWarn } from '../../ui/log.ts'\nimport { logBanner } from '../../ui/mascot.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, listenForKeys, startWatcher, trackBuild } from './utils.ts'\n\n/** NPM registry endpoint used to check for @kubb/cli updates. */\nconst KUBB_NPM_PACKAGE_URL = 'https://registry.npmjs.org/@kubb/cli/latest' as const\n\n/** Upper bound in milliseconds for the npm update check, so a slow registry never stalls a run. */\nconst UPDATE_CHECK_TIMEOUT_MS = 3_000\n\n/** The formatter names from `Config['output'].format`, without `'auto'` (detection, not a tool) and `false` (skip). */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned here, not in `@internals/utils` (which must not import `@kubb/core`): a tool added to the union without a descriptor fails to compile.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n /**\n * When `true`, generates in memory instead of writing to disk, skips formatting, linting, and\n * post-generate commands, and prints what would change on disk.\n */\n dryRun?: boolean\n}\n\nexport async function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, dryRun = false } = options\n\n const report = trackRun({ command: 'generate', hrStart: process.hrtime() })\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // Core formats, lints and runs `output.postGenerate` after an error-free build, and reports\n // their failures as coded diagnostics that reach the summary, the json report and the exit code.\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n\n await report({\n // A setup that threw leaves no driver, so read the configured plugins instead.\n plugins: kubb.config.plugins.flatMap((p) =>\n p && typeof p === 'object' ? [{ name: p.meta?.name ?? p.name ?? '', options: (p.options ?? {}) as Record<string, unknown> }] : [],\n ),\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n })\n\n return result.success\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time. Never rejects. */\nasync function fetchLatestVersion(): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n return data.version\n } catch {\n // Ignore network errors\n return undefined\n }\n}\n\nasync function checkForUpdate({ hooks, latest }: { hooks: Hookable<KubbHooks>; latest: Promise<string | undefined> }): Promise<void> {\n const latestVersion = await latest\n if (latestVersion && isOutdated({ installed: version, latest: latestVersion })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion }))\n }\n}\n\n/** Prints `Rebuilt in 1.2s · +1 schema -2 operations`, without the names part when the spec kept the same names. */\nfunction logRebuild({ diff: { schemas, operations }, durationMs }: { diff: BuildDiff; durationMs: number }): void {\n const specChange = [\n schemas.added && styleText('green', `+${pluralize(schemas.added, 'schema')}`),\n schemas.removed && styleText('red', `-${pluralize(schemas.removed, 'schema')}`),\n operations.added && styleText('green', `+${pluralize(operations.added, 'operation')}`),\n operations.removed && styleText('red', `-${pluralize(operations.removed, 'operation')}`),\n ]\n .filter(Boolean)\n .join(' ')\n logStep([`Rebuilt in ${formatMs(durationMs)}`, specChange].filter(Boolean).join(styleText('dim', ' · ')))\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n // Started first so the registry request overlaps the banner and the config load.\n const latest = fetchLatestVersion()\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. `defineConfig`\n // registers the built-in reporters on the config; a config exported without it falls back to them below.\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const json = requestedNames.includes('json')\n const quiet = logLevel <= logLevelMap.silent || json\n\n // Errors raised outside a build have no report entry. In `json` mode they go to a stderr logger,\n // so they are never silent and stdout stays one JSON document.\n const errorHooks = json ? new Hookable<KubbHooks>() : hooks\n if (json) setupReporters(errorHooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays; the output still prints in order once the banner is done.\n const banner = quiet ? undefined : logBanner(version)\n const loading = getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n // Handled below; this keeps a rejection during the banner from counting as unhandled.\n loading.catch(() => undefined)\n await banner\n\n if (!quiet) {\n logIntro({ title: 'Configuration' })\n }\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\n const loaded = await loading\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n if (!json) setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n // A diagnostic thrown while the config file runs, such as invalid extension options, sits in the cause chain.\n await Diagnostics.emit(errorHooks, error)\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n // Without a reporter nothing is printed, not even an error, so a config written without\n // `defineConfig` gets the same built-ins it would have registered.\n const available = configs[0]?.reporters?.length ? configs[0].reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter]\n const reporters = selectReporters(available, requestedNames)\n setupReporters(hooks, { logLevel, reporters, dryRun })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate({ hooks, latest })\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n // One tracker, one key listener and one build queue serve every watched config, so several configs never mix diffs or answer `r` twice.\n const tracker = watch ? trackBuild(hooks) : undefined\n const rebuilds: Array<() => Promise<void>> = []\n let armKeys: (() => void) | undefined\n // Configs share the hooks emitter, so every build, from any watcher or the `r` key, waits for the one before it.\n let queue = Promise.resolve()\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' ? (effectiveInput as string) : undefined\n if (watchPath && tracker) {\n const label = styleText('yellow', `Watching ${path.relative(process.cwd(), watchPath)}`)\n let previous: BuildSnapshot | undefined\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async () => {\n const hrStart = process.hrtime()\n const succeeded = await generate({ input, config, hooks, dryRun })\n const snapshot = tracker.take()\n if (previous) logRebuild({ diff: diffBuilds(previous, snapshot), durationMs: getElapsedMs(hrStart) })\n previous = snapshot\n\n logStep(armKeys ? `${label} ${styleText('dim', 'r rebuild · q quit')}` : label)\n armKeys?.()\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n // A trigger that lands while this config's build is queued joins it; one that lands during the build queues one more. Never rejects.\n let pending = false\n const rebuild = (): Promise<void> => {\n if (pending) return queue\n pending = true\n queue = queue\n .then(() => {\n pending = false\n return build()\n })\n .catch((error) => void Diagnostics.emit(errorHooks, error))\n return queue\n }\n rebuilds.push(rebuild)\n if (!quiet) {\n armKeys ??= listenForKeys({\n rebuild: () => rebuilds.forEach((trigger) => void trigger()),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n }\n\n // The watcher ignores its startup state, so run the first build here; a failing one keeps watching so the user can fix the input.\n await rebuild()\n\n await startWatcher([watchPath], rebuild, { info: logInfo, error: logError })\n } else {\n if (tracker && !quiet) logWarn('Watch mode only follows a local `input` file, so this config is generated once.')\n try {\n const succeeded = await generate({ input, config, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await Diagnostics.emit(errorHooks, configError)\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await Diagnostics.emit(errorHooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAqBhC,eAAsB,SAAS,SAA0C;CACvE,MAAM,EAAE,OAAO,OAAO,SAAS,UAAU;CAEzC,MAAM,SAASA,kBAAAA,SAAS;EAAE,SAAS;EAAY,SAASC,aAAAA,QAAQ,OAAO;CAAE,CAAC;CAE1E,MAAM,SAAiB;EACrB,GAAG,QAAQ;EACX,OAAO,SAAS,QAAQ,OAAO;EAE/B,SAAS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B,aAAAA,QAAQ,KAAK,IAAI,CAAC;IAC7G,CAAC;IAIH,MAAM,QAAQ;IAEd,MAAM0B,cAAAA,aAAa,CAAC,SAAS,GAAG,SAAS;KAAE,MAAMC,aAAAA;KAAS,OAAOC,aAAAA;IAAS,CAAC;GAC7E,OAAO;IACL,IAAI,WAAW,CAAC,OAAO,aAAA,QAAQ,iFAAiF;IAChH,IAAI;KAEF,IAAI,CAAC,MADmB,SAAS;MAAE;MAAO;MAAQ;MAAO;KAAO,CAAC,GACjD,YAAY;IAC9B,SAAS,aAAa;KACpB,MAAMvB,WAAAA,YAAY,KAAK,YAAY,WAAW;KAC9C,YAAY;IACd;GACF;EACF;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAIzC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,WACvB,aAAA,OAAO;EAGT,IAAI,WACF,aAAA,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAMA,WAAAA,YAAY,KAAK,YAAY,KAAK;EACxC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-EJtgdIin.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, formatters, getElapsedMs, linters } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n Diagnostics,\n fileReporter,\n getInputKind,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { trackRun } from '../../Telemetry.ts'\nimport { pluralize } from '../../ui/text.ts'\nimport setupReporters, { selectReporters } from '../../loggers/reporters.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport { logIntro, logOutro, logSpacer, logTip } from '../../ui/intro.ts'\nimport { logError, logInfo, logStep, logWarn } from '../../ui/log.ts'\nimport { logBanner } from '../../ui/mascot.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { getConfigs } from '../../config.ts'\nimport { isOutdated } from '../../utils/registry.ts'\nimport { type BuildDiff, type BuildSnapshot, diffBuilds, listenForKeys, startWatcher, trackBuild } from './utils.ts'\n\n/** NPM registry endpoint used to check for @kubb/cli updates. */\nconst KUBB_NPM_PACKAGE_URL = 'https://registry.npmjs.org/@kubb/cli/latest' as const\n\n/** Upper bound in milliseconds for the npm update check, so a slow registry never stalls a run. */\nconst UPDATE_CHECK_TIMEOUT_MS = 3_000\n\n/** The formatter names from `Config['output'].format`, without `'auto'` (detection, not a tool) and `false` (skip). */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned here, not in `@internals/utils` (which must not import `@kubb/core`): a tool added to the union without a descriptor fails to compile.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n /**\n * When `true`, generates in memory instead of writing to disk, skips formatting, linting, and\n * post-generate commands, and prints what would change on disk.\n */\n dryRun?: boolean\n}\n\nexport async function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, dryRun = false } = options\n\n const report = trackRun({ command: 'generate', hrStart: process.hrtime() })\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // Core formats, lints and runs `output.postGenerate` after an error-free build, and reports\n // their failures as coded diagnostics that reach the summary, the json report and the exit code.\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n\n await report({\n // A setup that threw leaves no driver, so read the configured plugins instead.\n plugins: kubb.config.plugins.flatMap((p) =>\n p && typeof p === 'object' ? [{ name: p.meta?.name ?? p.name ?? '', options: (p.options ?? {}) as Record<string, unknown> }] : [],\n ),\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n })\n\n return result.success\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\n/** The latest published version, `undefined` when the registry does not answer in time. Never rejects. */\nasync function fetchLatestVersion(): Promise<string | undefined> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n return data.version\n } catch {\n // Ignore network errors\n return undefined\n }\n}\n\nasync function checkForUpdate({ hooks, latest }: { hooks: Hookable<KubbHooks>; latest: Promise<string | undefined> }): Promise<void> {\n const latestVersion = await latest\n if (latestVersion && isOutdated({ installed: version, latest: latestVersion })) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion }))\n }\n}\n\n/** Prints `Rebuilt in 1.2s · +1 schema -2 operations`, without the names part when the spec kept the same names. */\nfunction logRebuild({ diff: { schemas, operations }, durationMs }: { diff: BuildDiff; durationMs: number }): void {\n const specChange = [\n schemas.added && styleText('green', `+${pluralize(schemas.added, 'schema')}`),\n schemas.removed && styleText('red', `-${pluralize(schemas.removed, 'schema')}`),\n operations.added && styleText('green', `+${pluralize(operations.added, 'operation')}`),\n operations.removed && styleText('red', `-${pluralize(operations.removed, 'operation')}`),\n ]\n .filter(Boolean)\n .join(' ')\n logStep([`Rebuilt in ${formatMs(durationMs)}`, specChange].filter(Boolean).join(styleText('dim', ' · ')))\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n // Started first so the registry request overlaps the banner and the config load.\n const latest = fetchLatestVersion()\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. `defineConfig`\n // registers the built-in reporters on the config; a config exported without it falls back to them below.\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n\n // The `json` reporter owns stdout, so the command writes nothing of its own around it.\n const json = requestedNames.includes('json')\n const quiet = logLevel <= logLevelMap.silent || json\n\n // Errors raised outside a build have no report entry. In `json` mode they go to a stderr logger,\n // so they are never silent and stdout stays one JSON document.\n const errorHooks = json ? new Hookable<KubbHooks>() : hooks\n if (json) setupReporters(errorHooks, { logLevel, reporters: [cliReporter], writer: createPlainWriter(console.error) })\n\n // The config loads while the banner plays; the output still prints in order once the banner is done.\n const banner = quiet ? undefined : logBanner(version)\n const loading = getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n // Handled below; this keeps a rejection during the banner from counting as unhandled.\n loading.catch(() => undefined)\n await banner\n\n if (!quiet) {\n logIntro({ title: 'Configuration' })\n }\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n const configSpinner = createSpinner()\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n if (!quiet) configSpinner.start('Loading config')\n\n const loaded = await loading\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n\n if (!quiet) configSpinner.stop(`Loaded ${styleText('dim', path.relative(process.cwd(), resolvedConfigPath))}`)\n } catch (error) {\n if (!quiet) configSpinner.error('Config failed loading')\n\n if (!json) setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n // A diagnostic thrown while the config file runs, such as invalid extension options, sits in the cause chain.\n await Diagnostics.emit(errorHooks, error)\n\n if (!quiet) logOutro(styleText('red', '✗ Configuration failed'))\n process.exit(1)\n }\n\n // Without a reporter nothing is printed, not even an error, so a config written without\n // `defineConfig` gets the same built-ins it would have registered.\n const available = configs[0]?.reporters?.length ? configs[0].reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter]\n const reporters = selectReporters(available, requestedNames)\n setupReporters(hooks, { logLevel, reporters, dryRun })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n // Inside the bootstrap group, so an update notice reads as part of the setup rather than as part\n // of the first config's generation.\n await checkForUpdate({ hooks, latest })\n\n if (!quiet) logOutro(`${pluralize(configs.length, 'config')} ready`)\n\n try {\n let anyFailed = false\n // One tracker, one key listener and one build queue serve every watched config, so several configs never mix diffs or answer `r` twice.\n const tracker = watch ? trackBuild(hooks) : undefined\n const rebuilds: Array<() => Promise<void>> = []\n let armKeys: (() => void) | undefined\n // Configs share the hooks emitter, so every build, from any watcher or the `r` key, waits for the one before it.\n let queue = Promise.resolve()\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' ? (effectiveInput as string) : undefined\n if (watchPath && tracker) {\n const label = styleText('yellow', `Watching ${path.relative(process.cwd(), watchPath)}`)\n let previous: BuildSnapshot | undefined\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async () => {\n const hrStart = process.hrtime()\n const succeeded = await generate({ input, config, hooks, dryRun })\n const snapshot = tracker.take()\n if (previous) logRebuild({ diff: diffBuilds(previous, snapshot), durationMs: getElapsedMs(hrStart) })\n previous = snapshot\n\n logStep(armKeys ? `${label} ${styleText('dim', 'r rebuild · q quit')}` : label)\n armKeys?.()\n if (succeeded) {\n logSpacer()\n logTip()\n }\n }\n // A trigger that lands while this config's build is queued joins it; one that lands during the build queues one more. Never rejects.\n let pending = false\n const rebuild = (): Promise<void> => {\n if (pending) return queue\n pending = true\n queue = queue\n .then(() => {\n pending = false\n return build()\n })\n .catch((error) => void Diagnostics.emit(errorHooks, error))\n return queue\n }\n rebuilds.push(rebuild)\n if (!quiet) {\n armKeys ??= listenForKeys({\n rebuild: () => rebuilds.forEach((trigger) => void trigger()),\n quit: (code) => void Promise.resolve(hooks.callHook('kubb:lifecycle:end')).finally(() => process.exit(code)),\n })\n }\n\n // The watcher ignores its startup state, so run the first build here; a failing one keeps watching so the user can fix the input.\n await rebuild()\n\n await startWatcher([watchPath], rebuild, { info: logInfo, error: logError })\n } else {\n if (tracker && !quiet) logWarn('Watch mode only follows a local `input` file, so this config is generated once.')\n try {\n const succeeded = await generate({ input, config, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await Diagnostics.emit(errorHooks, configError)\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n // Watch mode prints a tip after each successful build. Regular generate commands need to\n // print one explicitly after the lifecycle group has closed so it stays outside the group.\n if (!quiet && !watch && !anyFailed) {\n logTip()\n }\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await Diagnostics.emit(errorHooks, error)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAM,uBAAuB;;AAG7B,MAAM,0BAA0B;AAqBhC,eAAsB,SAAS,SAA0C;CACvE,MAAM,EAAE,OAAO,OAAO,SAAS,UAAU;CAEzC,MAAM,SAAS,SAAS;EAAE,SAAS;EAAY,SAAS,QAAQ,OAAO;CAAE,CAAC;CAE1E,MAAM,SAAiB;EACrB,GAAG,QAAQ;EACX,OAAO,SAAS,QAAQ,OAAO;EAE/B,SAAS,SAAS,cAAc,IAAI,QAAQ,OAAO;EAEnD,QAAQ,SAAS;GAAE,GAAG,QAAQ,OAAO;GAAQ,QAAQ;GAAO,MAAM;GAAO,cAAc,CAAC;EAAE,IAAI,QAAQ,OAAO;CAC/G;CAIA,MAA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AAO;KACT;IACF;IAEA,IAAI,UAAU;IACd,MAAM,gBAA+B;KACnC,IAAI,SAAS,OAAO;KACpB,UAAU;KACV,QAAQ,MACL,WAAW;MACV,UAAU;MACV,OAAO,MAAM;KACf,CAAC,CAAC,CACD,OAAO,UAAU,KAAK,YAAY,KAAK,YAAY,KAAK,CAAC;KAC5D,OAAO;IACT;IACA,SAAS,KAAK,OAAO;IACrB,IAAI,CAAC,OACH,YAAY,cAAc;KACxB,eAAe,SAAS,SAAS,YAAY,KAAK,QAAQ,CAAC;KAC3D,OAAO,SAAS,KAAK,QAAQ,QAAQ,MAAM,SAAS,oBAAoB,CAAC,CAAC,CAAC,cAAc,QAAQ,KAAK,IAAI,CAAC;IAC7G,CAAC;IAIH,MAAM,QAAQ;IAEd,MAAM,aAAa,CAAC,SAAS,GAAG,SAAS;KAAE,MAAM;KAAS,OAAO;IAAS,CAAC;GAC7E,OAAO;IACL,IAAI,WAAW,CAAC,OAAO,QAAQ,iFAAiF;IAChH,IAAI;KAEF,IAAI,CAAC,MADmB,SAAS;MAAE;MAAO;MAAQ;MAAO;KAAO,CAAC,GACjD,YAAY;IAC9B,SAAS,aAAa;KACpB,MAAM,YAAY,KAAK,YAAY,WAAW;KAC9C,YAAY;IACd;GACF;EACF;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAIzC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,WACvB,OAAO;EAGT,IAAI,WACF,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,YAAY,KAAK,YAAY,KAAK;EACxC,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"text-CL6N6yPS.js","names":[],"sources":["../src/utils/env.ts","../src/loggers/clackWriter.ts","../src/loggers/plainWriter.ts","../src/ui/log.ts","../src/ui/intro.ts","../src/ui/text.ts"],"sourcesContent":["import { isCIEnvironment } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\n\n/**\n * Returns `true` when the process has an interactive TTY with a valid terminal\n * width and is not running in CI.\n *\n * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,\n * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`\n * with a negative count and throw a `RangeError`). A positive column count is\n * required before the TTY counts as usable.\n *\n * @example\n * ```ts\n * if (canUseTTY()) {\n * renderProgressBar()\n * }\n * ```\n */\nexport function canUseTTY(): boolean {\n return process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment()\n}\n\n/**\n * Returns `true` when output can carry spinners and clack's gutter: an interactive TTY that no AI\n * coding agent is reading. Cursor-movement escapes are hard for an agent to parse even over a\n * pseudo-TTY, so it gets the plain writer.\n */\nexport function isRichOutput(): boolean {\n return canUseTTY() && !getAgentProfile().isAgent\n}\n","import { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { LoggerWriter } from './types.ts'\n\n/**\n * Draws with clack for local development: a gutter bar per group, animated steps, and a progress\n * bar for the writes.\n */\nexport const clackWriter: LoggerWriter = {\n audience: 'human',\n group: (title) => clack.intro(title),\n groupEnd: (text) => clack.outro(text),\n step: (text) => clack.log.step(text, { spacing: 0 }),\n info: (text) => clack.log.info(text),\n success: (text) => clack.log.success(text),\n warn: (text) => clack.log.warn(text),\n error: (text) => clack.log.error(text),\n block: (lines) => clack.log.message(lines, { spacing: 0 }),\n // A subprocess's output is not Kubb's tree, so it goes out past clack and its gutter bar. The\n // step above it is already stopped by the time this runs.\n raw: (lines) => console.log(styleText('dim', lines.join('\\n'))),\n // The diagnostic carries its own code and indented rows, so clear clack's gutter and bar and let\n // the block stand on its own.\n diagnostic: (lines) => clack.log.message(lines, { symbol: '', secondarySymbol: '' }),\n update: (lines, title) =>\n clack.box(lines.join('\\n'), title, {\n width: 'auto',\n formatBorder: (border: string) => styleText('yellow', border),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n }),\n spinner: () => clack.spinner(),\n progress(max) {\n const bar = clack.progress({ style: 'block', max, size: 30 })\n\n return {\n start: (text) => bar.start(text),\n advance: (text) => bar.advance(1, text),\n stop: (text) => bar.stop(text),\n }\n },\n}\n","import type { LoggerWriter } from './types.ts'\n\n/**\n * Prefixes that stand in for the symbols clack draws, so plain output reads the same way.\n */\nexport const SYMBOLS = { info: 'ℹ', warn: '⚠', error: '✗', step: '◇' } as const\n\n/**\n * Draws with one `write` call per line, e.g. `console.error` so stdout carries only JSON. Nothing\n * animates, so a step prints at start and end.\n */\nexport function createPlainWriter(write: (line: string) => void): LoggerWriter {\n return {\n audience: 'agent',\n group: write,\n groupEnd: write,\n step: (text) => write(`${SYMBOLS.step} ${text}`),\n info: write,\n success: write,\n warn: write,\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n block: (lines) => write(lines.join('\\n')),\n raw: (lines) => write(lines.join('\\n')),\n diagnostic: (lines) => write(lines.join('\\n')),\n update: (lines, title) => write([title, ...lines].join('\\n')),\n spinner: () => ({\n start: write,\n message: write,\n clear: () => {},\n stop: (text) => text && write(text),\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n }),\n progress: () => ({\n start: write,\n advance: write,\n stop: (text) => text && write(text),\n }),\n }\n}\n\n/**\n * Draws on the console, for non-TTY environments and for an AI coding agent reading the output.\n * Reports the same run in the same order as `clackWriter`, without the animation.\n */\nexport const plainWriter = createPlainWriter((line) => console.log(line))\n","import * as prompts from '@clack/prompts'\nimport { isRichOutput } from '../utils/env.ts'\nimport { clackWriter } from '../loggers/clackWriter.ts'\nimport { plainWriter, SYMBOLS } from '../loggers/plainWriter.ts'\nimport type { LoggerWriter } from '../loggers/types.ts'\n\n/** The writer the loggers draw with on this terminal, so a command's own lines look like its run. */\nexport function writer(): LoggerWriter {\n return isRichOutput() ? clackWriter : plainWriter\n}\n\ntype Level = keyof typeof SYMBOLS\n\n// Not through the writers: in plain output a command's own info and warning carry their symbol, and clack's step keeps its spacing.\nfunction write(level: Level, message: string): void {\n if (isRichOutput()) {\n prompts.log[level](message)\n\n return\n }\n\n console.log(`${SYMBOLS[level]} ${message}`)\n}\n\n/** Prints lines as one block, without a symbol in front of them. Not the writer's block, which drops clack's spacing around it. */\nexport function logBlock(lines: string | Array<string>): void {\n if (isRichOutput()) {\n prompts.log.message(lines)\n\n return\n }\n\n console.log([lines].flat().join('\\n'))\n}\n\nexport function logInfo(message: string): void {\n write('info', message)\n}\n\nexport function logWarn(message: string): void {\n write('warn', message)\n}\n\nexport function logError(message: string): void {\n write('error', message)\n}\n\n/**\n * Reports a step the command is taking, rather than something it found.\n */\nexport function logStep(message: string): void {\n write('step', message)\n}\n","import { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { isRichOutput } from '../utils/env.ts'\nimport { writer } from './log.ts'\n\nconst SPONSOR_TIPS = [\n 'Your sponsorship keeps Kubb codegen, plugins, and docs maintained',\n 'Sponsor faster generators and better Kubb Studio workflows',\n 'Help keep Kubb free for TypeScript teams building APIs',\n 'Support React Query, Zod, Faker, and MSW integrations',\n 'Back open-source tools that turn OpenAPI into TypeScript',\n 'Sponsor fixes, releases, and new plugins for your API workflow',\n 'Help Kubb stay independent and focused on developer tools',\n] as const\n\nconst SPONSOR_LINKS = ['https://github.com/sponsors/stijnvanhulle', 'https://opencollective.com/kubb', 'https://kubb.dev/sponsors'] as const\n\nfunction nextTip(): string {\n const tip = SPONSOR_TIPS[Math.floor(Math.random() * SPONSOR_TIPS.length)]!\n const link = SPONSOR_LINKS[Math.floor(Math.random() * SPONSOR_LINKS.length)]!\n return `${tip}: ${link}`\n}\n\nfunction formatTip(tip: string): string {\n return styleText('magenta', ' Tip ') + styleText('yellow', tip)\n}\n\n/**\n * Prints one random tip outside every group. Rich terminals get the styled variant;\n * plain/CI output gets a stable text-only line so the tip is still visible as final output.\n */\nexport function logTip(): void {\n const tip = nextTip()\n if (!isRichOutput()) {\n console.log(`Tip: ${tip}`)\n return\n }\n\n console.log(`${styleText('magenta', '✦')}${formatTip(tip)}`)\n}\n\ntype IntroOptions = {\n title?: string\n /**\n * Printed under the title, for a command that has a caveat to lead with.\n */\n warning?: string\n /**\n * Whether to open a block a later {@link logOutro} closes. Pass `false` for a command that\n * prints and exits, since nothing would ever close the block.\n *\n * @default true\n */\n block?: boolean\n}\n\n/**\n * Opens a command's output. A command the banner already names passes no title.\n */\nexport function logIntro({ title, warning, block = true }: IntroOptions): void {\n if (block && isRichOutput()) {\n if (title) prompts.intro(title)\n\n if (warning) {\n prompts.log.warn(warning)\n }\n\n return\n }\n\n if (title) {\n console.log(title)\n }\n\n if (warning) {\n console.warn(warning)\n }\n\n if (title || warning) {\n console.log()\n }\n}\n\n/**\n * Closes the block {@link logIntro} opened. The closing gutter is not a written line, so plain\n * output prints the text on its own.\n */\nexport function logOutro(text: string): void {\n writer().groupEnd(text)\n}\n\n/**\n * Prints one empty line between two groups, without clack's gutter bar, since the bar belongs to a\n * group and a spacer sits outside every one.\n */\nexport function logSpacer(): void {\n console.log('')\n}\n\n/** Whether a run stops to ask something: no `--yes`, no `--dry-run`, and a person at a terminal. */\nexport function isInteractiveRun({ yes, dryRun }: { yes?: unknown; dryRun?: unknown }): boolean {\n return !yes && !dryRun && process.stdin.isTTY === true\n}\n","/** Counts a noun, so a message never reads `1 files`. */\nexport function pluralize(count: number, noun: string): string {\n return `${count} ${count === 1 ? noun : `${noun}s`}`\n}\n\n/** The flag that grants a permission, such as `--allow-read-ast`. */\nexport function toPermissionFlag(key: string): string {\n return `--${key.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAqB;CACnC,OAAO,QAAQ,OAAO,UAAU,QAAQ,OAAO,WAAW,KAAK,KAAK,CAAC,gBAAgB;AACvF;;;;;;AAOA,SAAgB,eAAwB;CACtC,OAAO,UAAU,KAAK,CAAC,gBAAgB,CAAC,CAAC;AAC3C;;;;;;;ACtBA,MAAa,cAA4B;CACvC,UAAU;CACV,QAAQ,UAAU,MAAM,MAAM,KAAK;C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Y,GAAG;AACtE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"text-DrsG1EDN.cjs","names":["isCIEnvironment","getAgentProfile","clack","styleText","styleText"],"sources":["../src/utils/env.ts","../src/loggers/clackWriter.ts","../src/loggers/plainWriter.ts","../src/ui/log.ts","../src/ui/intro.ts","../src/ui/text.ts"],"sourcesContent":["import { isCIEnvironment } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\n\n/**\n * Returns `true` when the process has an interactive TTY with a valid terminal\n * width and is not running in CI.\n *\n * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,\n * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`\n * with a negative count and throw a `RangeError`). A positive column count is\n * required before the TTY counts as usable.\n *\n * @example\n * ```ts\n * if (canUseTTY()) {\n * renderProgressBar()\n * }\n * ```\n */\nexport function canUseTTY(): boolean {\n return process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment()\n}\n\n/**\n * Returns `true` when output can carry spinners and clack's gutter: an interactive TTY that no AI\n * coding agent is reading. Cursor-movement escapes are hard for an agent to parse even over a\n * pseudo-TTY, so it gets the plain writer.\n */\nexport function isRichOutput(): boolean {\n return canUseTTY() && !getAgentProfile().isAgent\n}\n","import { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { LoggerWriter } from './types.ts'\n\n/**\n * Draws with clack for local development: a gutter bar per group, animated steps, and a progress\n * bar for the writes.\n */\nexport const clackWriter: LoggerWriter = {\n audience: 'human',\n group: (title) => clack.intro(title),\n groupEnd: (text) => clack.outro(text),\n step: (text) => clack.log.step(text, { spacing: 0 }),\n info: (text) => clack.log.info(text),\n success: (text) => clack.log.success(text),\n warn: (text) => clack.log.warn(text),\n error: (text) => clack.log.error(text),\n block: (lines) => clack.log.message(lines, { spacing: 0 }),\n // A subprocess's output is not Kubb's tree, so it goes out past clack and its gutter bar. The\n // step above it is already stopped by the time this runs.\n raw: (lines) => console.log(styleText('dim', lines.join('\\n'))),\n // The diagnostic carries its own code and indented rows, so clear clack's gutter and bar and let\n // the block stand on its own.\n diagnostic: (lines) => clack.log.message(lines, { symbol: '', secondarySymbol: '' }),\n update: (lines, title) =>\n clack.box(lines.join('\\n'), title, {\n width: 'auto',\n formatBorder: (border: string) => styleText('yellow', border),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n }),\n spinner: () => clack.spinner(),\n progress(max) {\n const bar = clack.progress({ style: 'block', max, size: 30 })\n\n return {\n start: (text) => bar.start(text),\n advance: (text) => bar.advance(1, text),\n stop: (text) => bar.stop(text),\n }\n },\n}\n","import type { LoggerWriter } from './types.ts'\n\n/**\n * Prefixes that stand in for the symbols clack draws, so plain output reads the same way.\n */\nexport const SYMBOLS = { info: 'ℹ', warn: '⚠', error: '✗', step: '◇' } as const\n\n/**\n * Draws with one `write` call per line, e.g. `console.error` so stdout carries only JSON. Nothing\n * animates, so a step prints at start and end.\n */\nexport function createPlainWriter(write: (line: string) => void): LoggerWriter {\n return {\n audience: 'agent',\n group: write,\n groupEnd: write,\n step: (text) => write(`${SYMBOLS.step} ${text}`),\n info: write,\n success: write,\n warn: write,\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n block: (lines) => write(lines.join('\\n')),\n raw: (lines) => write(lines.join('\\n')),\n diagnostic: (lines) => write(lines.join('\\n')),\n update: (lines, title) => write([title, ...lines].join('\\n')),\n spinner: () => ({\n start: write,\n message: write,\n clear: () => {},\n stop: (text) => text && write(text),\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n }),\n progress: () => ({\n start: write,\n advance: write,\n stop: (text) => text && write(text),\n }),\n }\n}\n\n/**\n * Draws on the console, for non-TTY environments and for an AI coding agent reading the output.\n * Reports the same run in the same order as `clackWriter`, without the animation.\n */\nexport const plainWriter = createPlainWriter((line) => console.log(line))\n","import * as prompts from '@clack/prompts'\nimport { isRichOutput } from '../utils/env.ts'\nimport { clackWriter } from '../loggers/clackWriter.ts'\nimport { plainWriter, SYMBOLS } from '../loggers/plainWriter.ts'\nimport type { LoggerWriter } from '../loggers/types.ts'\n\n/** The writer the loggers draw with on this terminal, so a command's own lines look like its run. */\nexport function writer(): LoggerWriter {\n return isRichOutput() ? clackWriter : plainWriter\n}\n\ntype Level = keyof typeof SYMBOLS\n\n// Not through the writers: in plain output a command's own info and warning carry their symbol, and clack's step keeps its spacing.\nfunction write(level: Level, message: string): void {\n if (isRichOutput()) {\n prompts.log[level](message)\n\n return\n }\n\n console.log(`${SYMBOLS[level]} ${message}`)\n}\n\n/** Prints lines as one block, without a symbol in front of them. Not the writer's block, which drops clack's spacing around it. */\nexport function logBlock(lines: string | Array<string>): void {\n if (isRichOutput()) {\n prompts.log.message(lines)\n\n return\n }\n\n console.log([lines].flat().join('\\n'))\n}\n\nexport function logInfo(message: string): void {\n write('info', message)\n}\n\nexport function logWarn(message: string): void {\n write('warn', message)\n}\n\nexport function logError(message: string): void {\n write('error', message)\n}\n\n/**\n * Reports a step the command is taking, rather than something it found.\n */\nexport function logStep(message: string): void {\n write('step', message)\n}\n","import { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { isRichOutput } from '../utils/env.ts'\nimport { writer } from './log.ts'\n\nconst SPONSOR_TIPS = [\n 'Your sponsorship keeps Kubb codegen, plugins, and docs maintained',\n 'Sponsor faster generators and better Kubb Studio workflows',\n 'Help keep Kubb free for TypeScript teams building APIs',\n 'Support React Query, Zod, Faker, and MSW integrations',\n 'Back open-source tools that turn OpenAPI into TypeScript',\n 'Sponsor fixes, releases, and new plugins for your API workflow',\n 'Help Kubb stay independent and focused on developer tools',\n] as const\n\nconst SPONSOR_LINKS = ['https://github.com/sponsors/stijnvanhulle', 'https://opencollective.com/kubb', 'https://kubb.dev/sponsors'] as const\n\nfunction nextTip(): string {\n const tip = SPONSOR_TIPS[Math.floor(Math.random() * SPONSOR_TIPS.length)]!\n const link = SPONSOR_LINKS[Math.floor(Math.random() * SPONSOR_LINKS.length)]!\n return `${tip}: ${link}`\n}\n\nfunction formatTip(tip: string): string {\n return styleText('magenta', ' Tip ') + styleText('yellow', tip)\n}\n\n/**\n * Prints one random tip outside every group. Rich terminals get the styled variant;\n * plain/CI output gets a stable text-only line so the tip is still visible as final output.\n */\nexport function logTip(): void {\n const tip = nextTip()\n if (!isRichOutput()) {\n console.log(`Tip: ${tip}`)\n return\n }\n\n console.log(`${styleText('magenta', '✦')}${formatTip(tip)}`)\n}\n\ntype IntroOptions = {\n title?: string\n /**\n * Printed under the title, for a command that has a caveat to lead with.\n */\n warning?: string\n /**\n * Whether to open a block a later {@link logOutro} closes. Pass `false` for a command that\n * prints and exits, since nothing would ever close the block.\n *\n * @default true\n */\n block?: boolean\n}\n\n/**\n * Opens a command's output. A command the banner already names passes no title.\n */\nexport function logIntro({ title, warning, block = true }: IntroOptions): void {\n if (block && isRichOutput()) {\n if (title) prompts.intro(title)\n\n if (warning) {\n prompts.log.warn(warning)\n }\n\n return\n }\n\n if (title) {\n console.log(title)\n }\n\n if (warning) {\n console.warn(warning)\n }\n\n if (title || warning) {\n console.log()\n }\n}\n\n/**\n * Closes the block {@link logIntro} opened. The closing gutter is not a written line, so plain\n * output prints the text on its own.\n */\nexport function logOutro(text: string): void {\n writer().groupEnd(text)\n}\n\n/**\n * Prints one empty line between two groups, without clack's gutter bar, since the bar belongs to a\n * group and a spacer sits outside every one.\n */\nexport function logSpacer(): void {\n console.log('')\n}\n\n/** Whether a run stops to ask something: no `--yes`, no `--dry-run`, and a person at a terminal. */\nexport function isInteractiveRun({ yes, dryRun }: { yes?: unknown; dryRun?: unknown }): boolean {\n return !yes && !dryRun && process.stdin.isTTY === true\n}\n","/** Counts a noun, so a message never reads `1 files`. */\nexport function pluralize(count: number, noun: string): string {\n return `${count} ${count === 1 ? noun : `${noun}s`}`\n}\n\n/** The flag that grants a permission, such as `--allow-read-ast`. */\nexport function toPermissionFlag(key: string): string {\n return `--${key.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`\n}\n"],"mappings":";;;;;;;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