@kubb/cli 5.9.5 → 5.10.0

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 (53) hide show
  1. package/dist/{Telemetry-BFKg5ZFx.js → Telemetry-BmdDiGPs.js} +2 -2
  2. package/dist/{Telemetry-BFKg5ZFx.js.map → Telemetry-BmdDiGPs.js.map} +1 -1
  3. package/dist/{Telemetry-iUSXePwR.cjs → Telemetry-DuLxs5c3.cjs} +2 -2
  4. package/dist/{Telemetry-iUSXePwR.cjs.map → Telemetry-DuLxs5c3.cjs.map} +1 -1
  5. package/dist/{background-BA5mxYa1.cjs → background-CK9olfbv.cjs} +2 -2
  6. package/dist/{background-BA5mxYa1.cjs.map → background-CK9olfbv.cjs.map} +1 -1
  7. package/dist/{background-Dtk2M5B8.js → background-DWasKvSw.js} +2 -2
  8. package/dist/{background-Dtk2M5B8.js.map → background-DWasKvSw.js.map} +1 -1
  9. package/dist/{background-uX93zloA.js → background-y0JpYwlj.js} +1 -1
  10. package/dist/{config-66zh0aCP.js → config-BPuFepc5.js} +2 -2
  11. package/dist/{config-66zh0aCP.js.map → config-BPuFepc5.js.map} +1 -1
  12. package/dist/{config-cb2nhvBt.cjs → config-CGUQ39wR.cjs} +2 -2
  13. package/dist/{config-cb2nhvBt.cjs.map → config-CGUQ39wR.cjs.map} +1 -1
  14. package/dist/credentials-CZK6zPLv.js.map +1 -1
  15. package/dist/credentials-DDaKqtJn.cjs.map +1 -1
  16. package/dist/index.cjs +22 -15
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.js +22 -15
  19. package/dist/index.js.map +1 -1
  20. package/dist/{output-DOC3zu6i.cjs → output-Ck7iT223.cjs} +2 -2
  21. package/dist/{output-DOC3zu6i.cjs.map → output-Ck7iT223.cjs.map} +1 -1
  22. package/dist/{output-CCiHzIPS.js → output-DIJsbXzW.js} +2 -2
  23. package/dist/{output-CCiHzIPS.js.map → output-DIJsbXzW.js.map} +1 -1
  24. package/dist/{registry-O3AelRfj.js → registry-CHJCPOAR.js} +2 -2
  25. package/dist/{registry-O3AelRfj.js.map → registry-CHJCPOAR.js.map} +1 -1
  26. package/dist/{registry-DTPOQwZN.cjs → registry-gERiCBje.cjs} +2 -2
  27. package/dist/{registry-DTPOQwZN.cjs.map → registry-gERiCBje.cjs.map} +1 -1
  28. package/dist/{run-CWWSCB8I.js → run-B2kL57dE.js} +1 -1
  29. package/dist/{run-S-4lnViv.js → run-B33l-Tx7.js} +19 -21
  30. package/dist/run-B33l-Tx7.js.map +1 -0
  31. package/dist/{run-CB3YAq5e.js → run-BUZPvsbR.js} +2 -2
  32. package/dist/{run-CB3YAq5e.js.map → run-BUZPvsbR.js.map} +1 -1
  33. package/dist/{run-CfBk4wgw.cjs → run-Bqy3HW6o.cjs} +19 -21
  34. package/dist/run-Bqy3HW6o.cjs.map +1 -0
  35. package/dist/{run--pbGQ3Rm.cjs → run-C3v9G5i3.cjs} +2 -2
  36. package/dist/{run--pbGQ3Rm.cjs.map → run-C3v9G5i3.cjs.map} +1 -1
  37. package/dist/{run-Dut1ksMl.js → run-DNa_bKZE.js} +5 -5
  38. package/dist/{run-Dut1ksMl.js.map → run-DNa_bKZE.js.map} +1 -1
  39. package/dist/{run-BzoydGZo.js → run-DORetnI8.js} +2 -2
  40. package/dist/{run-BzoydGZo.js.map → run-DORetnI8.js.map} +1 -1
  41. package/dist/{run-BehbQsS7.cjs → run-DPqVZIX_.cjs} +2 -2
  42. package/dist/{run-BehbQsS7.cjs.map → run-DPqVZIX_.cjs.map} +1 -1
  43. package/dist/{run-DIeXldF6.cjs → run-Ds-xI766.cjs} +5 -5
  44. package/dist/{run-DIeXldF6.cjs.map → run-Ds-xI766.cjs.map} +1 -1
  45. package/dist/{snapshot-CFyEQsu-.cjs → snapshot-C4TMtjON.cjs} +5 -5
  46. package/dist/{snapshot-CFyEQsu-.cjs.map → snapshot-C4TMtjON.cjs.map} +1 -1
  47. package/dist/{snapshot-Cv_SImjr.js → snapshot-zznDcPYo.js} +5 -5
  48. package/dist/{snapshot-Cv_SImjr.js.map → snapshot-zznDcPYo.js.map} +1 -1
  49. package/dist/studioWorker.js +3 -3
  50. package/dist/studioWorker.js.map +1 -1
  51. package/package.json +7 -7
  52. package/dist/run-CfBk4wgw.cjs.map +0 -1
  53. package/dist/run-S-4lnViv.js.map +0 -1
@@ -105,7 +105,7 @@ function formatMs(ms) {
105
105
  }
106
106
  //#endregion
107
107
  //#region package.json
108
- var version = "5.9.5";
108
+ var version = "5.10.0";
109
109
  //#endregion
110
110
  //#region src/Telemetry.ts
111
111
  /** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */
@@ -256,4 +256,4 @@ async function sendTelemetry(payload) {
256
256
  //#endregion
257
257
  export { getElapsedMs as a, getErrorMessage as c, formatMs as i, toError as l, trackRun as n, runtime as o, version as r, isCIEnvironment as s, isDisabled as t };
258
258
 
259
- //# sourceMappingURL=Telemetry-BFKg5ZFx.js.map
259
+ //# sourceMappingURL=Telemetry-BmdDiGPs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Telemetry-BFKg5ZFx.js","names":["process","process"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","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\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({ command, duration, status, plugins = [], filesCreated = 0 }: 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 ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\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":";;;;;;;;;;;;;;;;;AAWA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;ACpBA,SAAgB,kBAA2B;CACzC,MAAM,KAAKA,UAAQ,IAAI;CACvB,OAAO,CAAC,EACL,MAAM,OAAO,WAAW,OAAO,OAChCA,UAAQ,IAAI,kBACZA,UAAQ,IAAI,aACZA,UAAQ,IAAI,0BACZA,UAAQ,IAAI,eACZA,UAAQ,IAAI,YACZA,UAAQ,IAAI,UACZA,UAAQ,IAAI,oBACZA,UAAQ,IAAI,aACZA,UAAQ,IAAI;AAEhB;;;ACnBA,MAAM,QAAQ,OAAO,QAAQ;AAC7B,MAAM,SAAS,UAAU;;;;;;;;;AAUzB,MAAa,UAAU;CAAE;CAAO,GAAG,OAAO;AAAE;AAE5C,SAAS,SAA6D;CACpE,IAAI,OAAO,OAAO;EAAE,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AQ,CACN;IAAE,KAAK;IAAQ,OAAO,EAAE,aAAa,EAAE,KAAK;GAAE,GAC9C;IACE,KAAK;IACL,OAAO,EACL,aAAa,KAAK,UAAU;KAC1B,GAAG,EAAE;KACL,eAAe,KAAA;IACjB,CAAC,EACH;GACF,CACF,EACF,EACF,EAAE,EACJ,EACF;EACF;CACF;CAEA,OAAO,EACL,eAAe,CACb;EACE,UAAU,EACR,YAAY;GACV;IAAE,KAAK;IAAgB,OAAO,EAAE,aAAa,OAAO;GAAE;GACtD;IAAE,KAAK;IAAmB,OAAO,EAAE,aAAa,QAAQ;GAAE;GAC1D;IAAE,KAAK;IAA0B,OAAO,EAAE,aAAa,SAAS;GAAE;EACpE,EACF;EACA,YAAY,CACV;GACE,OAAO;IAAE,MAAM;IAAa;GAAQ;GACpC,OAAO,CACL;IACE;IACA;IACA,MAAM;IACN,MAAM;IACN,mBAAmB,OAAO,WAAW;IACrC,iBAAiB,OAAO,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
+ {"version":3,"file":"Telemetry-BmdDiGPs.js","names":["process","process"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","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\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({ command, duration, status, plugins = [], filesCreated = 0 }: 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 ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\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":";;;;;;;;;;;;;;;;;AAWA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;ACpBA,SAAgB,kBAA2B;CACzC,MAAM,KAAKA,UAAQ,IAAI;CACvB,OAAO,CAAC,EACL,MAAM,OAAO,WAAW,OAAO,OAChCA,UAAQ,IAAI,kBACZA,UAAQ,IAAI,a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,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
@@ -107,7 +107,7 @@ function formatMs(ms) {
107
107
  }
108
108
  //#endregion
109
109
  //#region package.json
110
- var version = "5.9.5";
110
+ var version = "5.10.0";
111
111
  //#endregion
112
112
  //#region src/Telemetry.ts
113
113
  /** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */
@@ -311,4 +311,4 @@ Object.defineProperty(exports, "version", {
311
311
  }
312
312
  });
313
313
 
314
- //# sourceMappingURL=Telemetry-iUSXePwR.cjs.map
314
+ //# sourceMappingURL=Telemetry-DuLxs5c3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Telemetry-iUSXePwR.cjs","names":["process","process","randomBytes","getAgentProfile","os"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","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\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({ command, duration, status, plugins = [], filesCreated = 0 }: 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 ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\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":";;;;;;;;;;;;;;;;;;;AAWA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;ACpBA,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;AAEhB;;;ACnBA,MAAM,QAAQ,OAAO,QAAQ;AAC7B,MAAM,SAAS,UAAU;;;;;;;;;AAUzB,MAAa,UAAU;CAAE;CAAO,GAAG,OAAO;AAAE;AAE5C,SAAS,SAA6D;CACpE,IAAI,OAAO,OAAO;EAAE,MAAM;EAAO,SAAS,QAAQ,SAAS,OAAO;CAAG;CACrE,IAAI,QAAQ,OAAO;EAAE,MAAM;EAAQ,SAAU,WAA0D,MAAM,SAAS,QAAQ;CAAG;CACjI,OAAO;EAAE,MAAM;EAAQ,SAAS,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AAK;IACL,OAAO,EACL,aAAa,KAAK,UAAU;KAC1B,GAAG,EAAE;KACL,eAAe,KAAA;IACjB,CAAC,EACH;GACF,CACF,EACF,EACF,EAAE,EACJ,EACF;EACF;CACF;CAEA,OAAO,EACL,eAAe,CACb;EACE,UAAU,EACR,YAAY;GACV;IAAE,KAAK;IAAgB,OAAO,EAAE,aAAa,OAAO;GAAE;GACtD;IAAE,KAAK;IAAmB,OAAO,EAAE,aAAa,QAAQ;GAAE;GAC1D;IAAE,KAAK;IAA0B,OAAO,EAAE,aAAa,SAAS;GAAE;EACpE,EACF;EACA,YAAY,CACV;GACE,OAAO;IAAE,MAAM;IAAa;GAAQ;GACpC,OAAO,CACL;IACE;IACA;IACA,MAAM;IACN,MAAM;IACN,mBAAmB,OAAO,WAAW;IACrC,iBAAiB,OAAO,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
+ {"version":3,"file":"Telemetry-DuLxs5c3.cjs","names":["process","process","randomBytes","getAgentProfile","os"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/time.ts","../package.json","../src/Telemetry.ts"],"sourcesContent":["/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","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\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({ command, duration, status, plugins = [], filesCreated = 0 }: 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 ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\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":";;;;;;;;;;;;;;;;;;;AAWA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;ACpBA,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,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ACP,gBAAgB;IAChB,0BAA0B;IAC1B,yBAAyB;GAC3B;GACA,MAAM,KAAK,UAAU,OAAO;GAC5B,QAAQ,YAAY,QAAQ,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
@@ -1,6 +1,6 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
2
2
  const require_credentials = require("./credentials-DDaKqtJn.cjs");
3
- const require_run = require("./run-CfBk4wgw.cjs");
3
+ const require_run = require("./run-Bqy3HW6o.cjs");
4
4
  require("node:crypto");
5
5
  let tinyexec = require("tinyexec");
6
6
  let node_fs_promises = require("node:fs/promises");
@@ -170,4 +170,4 @@ exports.getWorkerStatus = getWorkerStatus;
170
170
  exports.startWorker = startWorker;
171
171
  exports.stopWorker = stopWorker;
172
172
 
173
- //# sourceMappingURL=background-BA5mxYa1.cjs.map
173
+ //# sourceMappingURL=background-CK9olfbv.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"background-BA5mxYa1.cjs","names":["path","getProjectKubbHome","readFile","connectSocket","delay","prepareConnection","createRequire","x"],"sources":["../src/runners/studio/background.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport { readFile, rename, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { connect as connectSocket, createServer } from 'node:net'\nimport path from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = { id: string; pid: number; port: number; state: WorkerState }\nconst states: Array<WorkerState> = ['starting', 'connected', 'reconnecting', 'authentication required', 'stopped']\nexport const getWorkerLogPath = () => path.join(getProjectKubbHome(), 'worker.log')\nconst statePath = () => path.join(getProjectKubbHome(), 'worker.json')\n\nasync function readWorker(): Promise<WorkerRecord | null> {\n try {\n const value: unknown = JSON.parse(await readFile(statePath(), 'utf8'))\n if (!value || typeof value !== 'object') return null\n const record = value as Partial<WorkerRecord>\n return typeof record.id === 'string' &&\n /^[a-f0-9]{32}$/.test(record.id) &&\n Number.isInteger(record.pid) &&\n (record.pid ?? 0) > 1 &&\n Number.isInteger(record.port) &&\n (record.port ?? 0) > 0 &&\n (record.port ?? 0) <= 65535 &&\n states.includes(record.state as WorkerState)\n ? (record as WorkerRecord)\n : null\n } catch {\n return null\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Authenticated loopback IPC; a stored PID never authorizes sending a process signal. */\nfunction requestWorker(record: WorkerRecord, command: 'status' | 'stop'): Promise<WorkerRecord> {\n return new Promise((resolve, reject) => {\n const socket = connectSocket({ host: '127.0.0.1', port: record.port })\n let received = ''\n socket.setTimeout(2_000, () => socket.destroy(new Error('Worker control timed out')))\n socket.once('error', reject)\n socket.once('connect', () => socket.write(JSON.stringify({ id: record.id, command }) + '\\n'))\n socket.on('data', (chunk: Buffer) => {\n received += chunk.toString()\n if (received.length > 4096) socket.destroy(new Error('Invalid worker response'))\n })\n socket.once('end', () => {\n try {\n const response = JSON.parse(received) as WorkerRecord\n if (response.id !== record.id || response.pid !== record.pid || !states.includes(response.state)) throw new Error('Worker identity changed')\n resolve(response)\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nexport async function getWorkerStatus(): Promise<{ running: boolean; state: WorkerState; pid?: number }> {\n const record = await readWorker()\n if (!record) return { running: false, state: 'stopped' }\n try {\n const response = await requestWorker(record, 'status')\n return { running: true, state: response.state, pid: response.pid }\n } catch {\n return { running: false, state: record.state === 'authentication required' ? record.state : 'stopped' }\n }\n}\n\nexport async function stopWorker(): Promise<void> {\n const record = await readWorker()\n if (!record) return\n try {\n await requestWorker(record, 'stop')\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code !== 'ECONNREFUSED' &&\n isAlive(record.pid) &&\n record.state !== 'stopped' &&\n record.state !== 'authentication required'\n ) {\n throw new Error('Cannot verify the background worker. No process was signaled.')\n }\n return\n }\n const deadline = Date.now() + 15_000\n while (Date.now() < deadline) {\n try {\n await requestWorker(record, 'status')\n } catch {\n return\n }\n await delay(100)\n }\n throw new Error('The worker has not finished shutting down. Check worker.log and try again.')\n}\n\n/** The listening port is the project lock, so stale state never needs a PID-based takeover. */\nexport async function serveWorker(shutdown: AbortController) {\n const record: WorkerRecord = { id: randomBytes(16).toString('hex'), pid: process.pid, port: 0, state: 'starting' }\n const server = createServer((socket) => {\n let input = ''\n socket.setTimeout(2_000, () => socket.destroy())\n socket.on('error', () => {})\n socket.on('data', (chunk: Buffer) => {\n input += chunk.toString()\n if (input.length > 4096) {\n socket.destroy()\n return\n }\n if (!input.includes('\\n')) return\n try {\n const request = JSON.parse(input) as { id?: unknown; command?: unknown }\n if (request.id !== record.id || !['status', 'stop'].includes(String(request.command))) {\n socket.destroy()\n return\n }\n socket.end(JSON.stringify(record))\n if (request.command === 'stop') shutdown.abort()\n } catch {\n socket.destroy()\n }\n })\n })\n // Hash the project directory to choose its loopback port; fail on collisions.\n const port = 20_000 + (Number.parseInt(hash('sha256', getProjectKubbHome()).slice(0, 8), 16) % 30_000)\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', resolve)\n })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error\n // Let a simultaneous starter finish writing its record before checking ownership.\n await delay(100)\n const existing = await readWorker()\n if (existing?.port === port) {\n try {\n return { existing: await requestWorker(existing, 'status') }\n } catch {\n /* Refuse an unverified listener. */\n }\n }\n throw new Error('The project control port is occupied or another worker is starting. Try again after stopping that listener.')\n }\n record.port = port\n let saving = Promise.resolve()\n const save = () => {\n const value = JSON.stringify(record)\n saving = saving.then(async () => {\n const temporary = `${statePath()}.${record.id}`\n await writeFile(temporary, value, { mode: 0o600 })\n await rename(temporary, statePath())\n })\n return saving\n }\n try {\n await save()\n } catch (error) {\n server.close()\n throw error\n }\n return {\n async state(state: WorkerState) {\n record.state = state\n await save()\n },\n async close() {\n try {\n if (record.state !== 'authentication required') {\n record.state = 'stopped'\n await save()\n }\n } finally {\n await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))\n }\n },\n }\n}\n\nexport type WorkerLaunch = { options: StudioOptions; prepared: PreparedConnection }\n\nexport async function startWorker(options: StudioOptions): Promise<void> {\n const current = await getWorkerStatus()\n if (current.running) {\n console.log(`Already running (${current.state}, PID ${current.pid}).`)\n return\n }\n const prepared = await prepareConnection(options)\n const entry = path.join(path.dirname(createRequire(import.meta.url).resolve('@kubb/cli/package.json')), 'dist', 'studioWorker.js')\n const child = x(process.execPath, [...process.execArgv, entry], {\n nodeOptions: { cwd: process.cwd(), detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] },\n }).process\n if (!child) throw new Error('Background worker failed to start')\n try {\n const started = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => done(new Error('Background worker startup timed out')), 20_000)\n const done = (error?: Error) => {\n clearTimeout(timer)\n child.removeListener('error', failed)\n child.removeListener('exit', exited)\n child.removeListener('message', ready)\n if (error) reject(error)\n else resolve()\n }\n const failed = (error: Error) => done(error)\n const exited = () => done(new Error(`Background worker exited during startup. Check ${getWorkerLogPath()}`))\n child.once('error', failed)\n child.once('exit', exited)\n const ready = (message: unknown) => {\n if (!message || typeof message !== 'object' || !('started' in message) || message.started !== true)\n return done(new Error('Invalid worker startup response'))\n done()\n }\n child.once('message', ready)\n child.send({ options: { ...options, autoOpen: false }, prepared } satisfies WorkerLaunch, (error) => {\n if (error) done(error)\n })\n })\n await started\n if (child.connected) child.disconnect()\n child.unref()\n const status = await getWorkerStatus()\n console.log(`Background worker ${status.state} (PID ${status.pid ?? child.pid}). Logs: ${getWorkerLogPath()}`)\n } catch (error) {\n // This is the child we just spawned, not a PID recovered from disk.\n child.kill('SIGTERM')\n throw error\n }\n}\n"],"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YAAY,QAAQ,YAAY,MAC5F,OAAO,qBAAK,IAAI,MAAM,iCAAiC,CAAC;IAC1D,KAAK;GACP;GACA,MAAM,KAAK,WAAW,KAAK;GAC3B,MAAM,KAAK;IAAE,SAAS;KAAE,GAAG;KAAS,UAAU;IAAM;IAAG;GAAS,IAA2B,UAAU;IACnG,IAAI,OAAO,KAAK,KAAK;GACvB,CAAC;EACH,CACY;EACZ,IAAI,MAAM,WAAW,MAAM,WAAW;EACtC,MAAM,MAAM;EACZ,MAAM,SAAS,MAAM,gBAAgB;EACrC,QAAQ,IAAI,qBAAqB,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,IAAI,WAAW,iBAAiB,GAAG;CAC/G,SAAS,OAAO;EAEd,MAAM,KAAK,SAAS;EACpB,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"background-CK9olfbv.cjs","names":["path","getProjectKubbHome","readFile","connectSocket","delay","prepareConnection","createRequire","x"],"sources":["../src/runners/studio/background.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport { readFile, rename, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { connect as connectSocket, createServer } from 'node:net'\nimport path from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = { id: string; pid: number; port: number; state: WorkerState }\nconst states: Array<WorkerState> = ['starting', 'connected', 'reconnecting', 'authentication required', 'stopped']\nexport const getWorkerLogPath = () => path.join(getProjectKubbHome(), 'worker.log')\nconst statePath = () => path.join(getProjectKubbHome(), 'worker.json')\n\nasync function readWorker(): Promise<WorkerRecord | null> {\n try {\n const value: unknown = JSON.parse(await readFile(statePath(), 'utf8'))\n if (!value || typeof value !== 'object') return null\n const record = value as Partial<WorkerRecord>\n return typeof record.id === 'string' &&\n /^[a-f0-9]{32}$/.test(record.id) &&\n Number.isInteger(record.pid) &&\n (record.pid ?? 0) > 1 &&\n Number.isInteger(record.port) &&\n (record.port ?? 0) > 0 &&\n (record.port ?? 0) <= 65535 &&\n states.includes(record.state as WorkerState)\n ? (record as WorkerRecord)\n : null\n } catch {\n return null\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Authenticated loopback IPC; a stored PID never authorizes sending a process signal. */\nfunction requestWorker(record: WorkerRecord, command: 'status' | 'stop'): Promise<WorkerRecord> {\n return new Promise((resolve, reject) => {\n const socket = connectSocket({ host: '127.0.0.1', port: record.port })\n let received = ''\n socket.setTimeout(2_000, () => socket.destroy(new Error('Worker control timed out')))\n socket.once('error', reject)\n socket.once('connect', () => socket.write(JSON.stringify({ id: record.id, command }) + '\\n'))\n socket.on('data', (chunk: Buffer) => {\n received += chunk.toString()\n if (received.length > 4096) socket.destroy(new Error('Invalid worker response'))\n })\n socket.once('end', () => {\n try {\n const response = JSON.parse(received) as WorkerRecord\n if (response.id !== record.id || response.pid !== record.pid || !states.includes(response.state)) throw new Error('Worker identity changed')\n resolve(response)\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nexport async function getWorkerStatus(): Promise<{ running: boolean; state: WorkerState; pid?: number }> {\n const record = await readWorker()\n if (!record) return { running: false, state: 'stopped' }\n try {\n const response = await requestWorker(record, 'status')\n return { running: true, state: response.state, pid: response.pid }\n } catch {\n return { running: false, state: record.state === 'authentication required' ? record.state : 'stopped' }\n }\n}\n\nexport async function stopWorker(): Promise<void> {\n const record = await readWorker()\n if (!record) return\n try {\n await requestWorker(record, 'stop')\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code !== 'ECONNREFUSED' &&\n isAlive(record.pid) &&\n record.state !== 'stopped' &&\n record.state !== 'authentication required'\n ) {\n throw new Error('Cannot verify the background worker. No process was signaled.')\n }\n return\n }\n const deadline = Date.now() + 15_000\n while (Date.now() < deadline) {\n try {\n await requestWorker(record, 'status')\n } catch {\n return\n }\n await delay(100)\n }\n throw new Error('The worker has not finished shutting down. Check worker.log and try again.')\n}\n\n/** The listening port is the project lock, so stale state never needs a PID-based takeover. */\nexport async function serveWorker(shutdown: AbortController) {\n const record: WorkerRecord = { id: randomBytes(16).toString('hex'), pid: process.pid, port: 0, state: 'starting' }\n const server = createServer((socket) => {\n let input = ''\n socket.setTimeout(2_000, () => socket.destroy())\n socket.on('error', () => {})\n socket.on('data', (chunk: Buffer) => {\n input += chunk.toString()\n if (input.length > 4096) {\n socket.destroy()\n return\n }\n if (!input.includes('\\n')) return\n try {\n const request = JSON.parse(input) as { id?: unknown; command?: unknown }\n if (request.id !== record.id || !['status', 'stop'].includes(String(request.command))) {\n socket.destroy()\n return\n }\n socket.end(JSON.stringify(record))\n if (request.command === 'stop') shutdown.abort()\n } catch {\n socket.destroy()\n }\n })\n })\n // Hash the project directory to choose its loopback port; fail on collisions.\n const port = 20_000 + (Number.parseInt(hash('sha256', getProjectKubbHome()).slice(0, 8), 16) % 30_000)\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', resolve)\n })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error\n // Let a simultaneous starter finish writing its record before checking ownership.\n await delay(100)\n const existing = await readWorker()\n if (existing?.port === port) {\n try {\n return { existing: await requestWorker(existing, 'status') }\n } catch {\n /* Refuse an unverified listener. */\n }\n }\n throw new Error('The project control port is occupied or another worker is starting. Try again after stopping that listener.')\n }\n record.port = port\n let saving = Promise.resolve()\n const save = () => {\n const value = JSON.stringify(record)\n saving = saving.then(async () => {\n const temporary = `${statePath()}.${record.id}`\n await writeFile(temporary, value, { mode: 0o600 })\n await rename(temporary, statePath())\n })\n return saving\n }\n try {\n await save()\n } catch (error) {\n server.close()\n throw error\n }\n return {\n async state(state: WorkerState) {\n record.state = state\n await save()\n },\n async close() {\n try {\n if (record.state !== 'authentication required') {\n record.state = 'stopped'\n await save()\n }\n } finally {\n await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))\n }\n },\n }\n}\n\nexport type WorkerLaunch = { options: StudioOptions; prepared: PreparedConnection }\n\nexport async function startWorker(options: StudioOptions): Promise<void> {\n const current = await getWorkerStatus()\n if (current.running) {\n console.log(`Already running (${current.state}, PID ${current.pid}).`)\n return\n }\n const prepared = await prepareConnection(options)\n const entry = path.join(path.dirname(createRequire(import.meta.url).resolve('@kubb/cli/package.json')), 'dist', 'studioWorker.js')\n const child = x(process.execPath, [...process.execArgv, entry], {\n nodeOptions: { cwd: process.cwd(), detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] },\n }).process\n if (!child) throw new Error('Background worker failed to start')\n try {\n const started = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => done(new Error('Background worker startup timed out')), 20_000)\n const done = (error?: Error) => {\n clearTimeout(timer)\n child.removeListener('error', failed)\n child.removeListener('exit', exited)\n child.removeListener('message', ready)\n if (error) reject(error)\n else resolve()\n }\n const failed = (error: Error) => done(error)\n const exited = () => done(new Error(`Background worker exited during startup. Check ${getWorkerLogPath()}`))\n child.once('error', failed)\n child.once('exit', exited)\n const ready = (message: unknown) => {\n if (!message || typeof message !== 'object' || !('started' in message) || message.started !== true)\n return done(new Error('Invalid worker startup response'))\n done()\n }\n child.once('message', ready)\n child.send({ options: { ...options, autoOpen: false }, prepared } satisfies WorkerLaunch, (error) => {\n if (error) done(error)\n })\n })\n await started\n if (child.connected) child.disconnect()\n child.unref()\n const status = await getWorkerStatus()\n console.log(`Background worker ${status.state} (PID ${status.pid ?? child.pid}). Logs: ${getWorkerLogPath()}`)\n } catch (error) {\n // This is the child we just spawned, not a PID recovered from disk.\n child.kill('SIGTERM')\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,SAA6B;CAAC;CAAY;CAAa;CAAgB;CAA2B;AAAS;AACjH,MAAa,yBAAyBA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AK,WAAW,KAAK;GAC3B,MAAM,KAAK;IAAE,SAAS;KAAE,GAAG;KAAS,UAAU;IAAM;IAAG;GAAS,IAA2B,UAAU;IACnG,IAAI,OAAO,KAAK,KAAK;GACvB,CAAC;EACH,CACY;EACZ,IAAI,MAAM,WAAW,MAAM,WAAW;EACtC,MAAM,MAAM;EACZ,MAAM,SAAS,MAAM,gBAAgB;EACrC,QAAQ,IAAI,qBAAqB,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,IAAI,WAAW,iBAAiB,GAAG;CAC/G,SAAS,OAAO;EAEd,MAAM,KAAK,SAAS;EACpB,MAAM;CACR;AACF"}
@@ -1,5 +1,5 @@
1
1
  import "./rolldown-runtime-CRm0XQPb.js";
2
- import { a as prepareConnection } from "./run-S-4lnViv.js";
2
+ import { a as prepareConnection } from "./run-B33l-Tx7.js";
3
3
  import { i as getProjectKubbHome } from "./credentials-CZK6zPLv.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { hash, randomBytes } from "node:crypto";
@@ -247,4 +247,4 @@ async function startWorker(options) {
247
247
  //#endregion
248
248
  export { stopWorker as a, startWorker as i, getWorkerStatus as n, serveWorker as r, getWorkerLogPath as t };
249
249
 
250
- //# sourceMappingURL=background-Dtk2M5B8.js.map
250
+ //# sourceMappingURL=background-DWasKvSw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"background-Dtk2M5B8.js","names":["connectSocket","delay"],"sources":["../src/runners/studio/background.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport { readFile, rename, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { connect as connectSocket, createServer } from 'node:net'\nimport path from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = { id: string; pid: number; port: number; state: WorkerState }\nconst states: Array<WorkerState> = ['starting', 'connected', 'reconnecting', 'authentication required', 'stopped']\nexport const getWorkerLogPath = () => path.join(getProjectKubbHome(), 'worker.log')\nconst statePath = () => path.join(getProjectKubbHome(), 'worker.json')\n\nasync function readWorker(): Promise<WorkerRecord | null> {\n try {\n const value: unknown = JSON.parse(await readFile(statePath(), 'utf8'))\n if (!value || typeof value !== 'object') return null\n const record = value as Partial<WorkerRecord>\n return typeof record.id === 'string' &&\n /^[a-f0-9]{32}$/.test(record.id) &&\n Number.isInteger(record.pid) &&\n (record.pid ?? 0) > 1 &&\n Number.isInteger(record.port) &&\n (record.port ?? 0) > 0 &&\n (record.port ?? 0) <= 65535 &&\n states.includes(record.state as WorkerState)\n ? (record as WorkerRecord)\n : null\n } catch {\n return null\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Authenticated loopback IPC; a stored PID never authorizes sending a process signal. */\nfunction requestWorker(record: WorkerRecord, command: 'status' | 'stop'): Promise<WorkerRecord> {\n return new Promise((resolve, reject) => {\n const socket = connectSocket({ host: '127.0.0.1', port: record.port })\n let received = ''\n socket.setTimeout(2_000, () => socket.destroy(new Error('Worker control timed out')))\n socket.once('error', reject)\n socket.once('connect', () => socket.write(JSON.stringify({ id: record.id, command }) + '\\n'))\n socket.on('data', (chunk: Buffer) => {\n received += chunk.toString()\n if (received.length > 4096) socket.destroy(new Error('Invalid worker response'))\n })\n socket.once('end', () => {\n try {\n const response = JSON.parse(received) as WorkerRecord\n if (response.id !== record.id || response.pid !== record.pid || !states.includes(response.state)) throw new Error('Worker identity changed')\n resolve(response)\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nexport async function getWorkerStatus(): Promise<{ running: boolean; state: WorkerState; pid?: number }> {\n const record = await readWorker()\n if (!record) return { running: false, state: 'stopped' }\n try {\n const response = await requestWorker(record, 'status')\n return { running: true, state: response.state, pid: response.pid }\n } catch {\n return { running: false, state: record.state === 'authentication required' ? record.state : 'stopped' }\n }\n}\n\nexport async function stopWorker(): Promise<void> {\n const record = await readWorker()\n if (!record) return\n try {\n await requestWorker(record, 'stop')\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code !== 'ECONNREFUSED' &&\n isAlive(record.pid) &&\n record.state !== 'stopped' &&\n record.state !== 'authentication required'\n ) {\n throw new Error('Cannot verify the background worker. No process was signaled.')\n }\n return\n }\n const deadline = Date.now() + 15_000\n while (Date.now() < deadline) {\n try {\n await requestWorker(record, 'status')\n } catch {\n return\n }\n await delay(100)\n }\n throw new Error('The worker has not finished shutting down. Check worker.log and try again.')\n}\n\n/** The listening port is the project lock, so stale state never needs a PID-based takeover. */\nexport async function serveWorker(shutdown: AbortController) {\n const record: WorkerRecord = { id: randomBytes(16).toString('hex'), pid: process.pid, port: 0, state: 'starting' }\n const server = createServer((socket) => {\n let input = ''\n socket.setTimeout(2_000, () => socket.destroy())\n socket.on('error', () => {})\n socket.on('data', (chunk: Buffer) => {\n input += chunk.toString()\n if (input.length > 4096) {\n socket.destroy()\n return\n }\n if (!input.includes('\\n')) return\n try {\n const request = JSON.parse(input) as { id?: unknown; command?: unknown }\n if (request.id !== record.id || !['status', 'stop'].includes(String(request.command))) {\n socket.destroy()\n return\n }\n socket.end(JSON.stringify(record))\n if (request.command === 'stop') shutdown.abort()\n } catch {\n socket.destroy()\n }\n })\n })\n // Hash the project directory to choose its loopback port; fail on collisions.\n const port = 20_000 + (Number.parseInt(hash('sha256', getProjectKubbHome()).slice(0, 8), 16) % 30_000)\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', resolve)\n })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error\n // Let a simultaneous starter finish writing its record before checking ownership.\n await delay(100)\n const existing = await readWorker()\n if (existing?.port === port) {\n try {\n return { existing: await requestWorker(existing, 'status') }\n } catch {\n /* Refuse an unverified listener. */\n }\n }\n throw new Error('The project control port is occupied or another worker is starting. Try again after stopping that listener.')\n }\n record.port = port\n let saving = Promise.resolve()\n const save = () => {\n const value = JSON.stringify(record)\n saving = saving.then(async () => {\n const temporary = `${statePath()}.${record.id}`\n await writeFile(temporary, value, { mode: 0o600 })\n await rename(temporary, statePath())\n })\n return saving\n }\n try {\n await save()\n } catch (error) {\n server.close()\n throw error\n }\n return {\n async state(state: WorkerState) {\n record.state = state\n await save()\n },\n async close() {\n try {\n if (record.state !== 'authentication required') {\n record.state = 'stopped'\n await save()\n }\n } finally {\n await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))\n }\n },\n }\n}\n\nexport type WorkerLaunch = { options: StudioOptions; prepared: PreparedConnection }\n\nexport async function startWorker(options: StudioOptions): Promise<void> {\n const current = await getWorkerStatus()\n if (current.running) {\n console.log(`Already running (${current.state}, PID ${current.pid}).`)\n return\n }\n const prepared = await prepareConnection(options)\n const entry = path.join(path.dirname(createRequire(import.meta.url).resolve('@kubb/cli/package.json')), 'dist', 'studioWorker.js')\n const child = x(process.execPath, [...process.execArgv, entry], {\n nodeOptions: { cwd: process.cwd(), detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] },\n }).process\n if (!child) throw new Error('Background worker failed to start')\n try {\n const started = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => done(new Error('Background worker startup timed out')), 20_000)\n const done = (error?: Error) => {\n clearTimeout(timer)\n child.removeListener('error', failed)\n child.removeListener('exit', exited)\n child.removeListener('message', ready)\n if (error) reject(error)\n else resolve()\n }\n const failed = (error: Error) => done(error)\n const exited = () => done(new Error(`Background worker exited during startup. Check ${getWorkerLogPath()}`))\n child.once('error', failed)\n child.once('exit', exited)\n const ready = (message: unknown) => {\n if (!message || typeof message !== 'object' || !('started' in message) || message.started !== true)\n return done(new Error('Invalid worker startup response'))\n done()\n }\n child.once('message', ready)\n child.send({ options: { ...options, autoOpen: false }, prepared } satisfies WorkerLaunch, (error) => {\n if (error) done(error)\n })\n })\n await started\n if (child.connected) child.disconnect()\n child.unref()\n const status = await getWorkerStatus()\n console.log(`Background worker ${status.state} (PID ${status.pid ?? child.pid}). Logs: ${getWorkerLogPath()}`)\n } catch (error) {\n // This is the child we just spawned, not a PID recovered from disk.\n child.kill('SIGTERM')\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,SAA6B;CAAC;CAAY;CAAa;CAAgB;CAA2B;AAAS;AACjH,MAAa,yBAAyB,KAAK,KAAK,mBAAmB,GAAG,YAAY;AAClF,MAAM,kBAAkB,KAAK,KAAK,mBAAmB,GAAG,aAAa;AAErE,eAAe,aAA2C;CACxD,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,MAAM,SAAS,UAAU,GAAG,MAAM,CAAC;EACrE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;EAChD,MAAM,SAAS;EACf,OAAO,OAAO,OAAO,OAAO,YAC1B,iBAAiB,KAAK,OAAO,EAAE,KAC/B,OAAO,UAAU,OAAO,GAAG,MAC1B,OAAO,OAAO,KAAK,KACpB,OAAO,UAAU,OAAO,IAAI,MAC3B,OAAO,QAAQ,KAAK,MACpB,OAAO,QAAQ,MAAM,SACtB,OAAO,SAAS,OAAO,KAAoB,IACxC,SACD;CACN,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,QAAQ,KAAsB;CACrC,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,SAAS,OAAO;EACd,OAAQ,MAAgC,SAAS;CACnD;AACF;;AAGA,SAAS,cAAc,QAAsB,SAAmD;CAC9F,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAASA,QAAc;GAAE,MAAM;GAAa,MAAM,OAAO;EAAK,CAAC;EACrE,IAAI,WAAW;EACf,OAAO,WAAW,WAAa,OAAO,wBAAQ,IAAI,MAAM,0BAA0B,CAAC,CAAC;EACpF,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,KAAK,iBAA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","delay"],"sources":["../src/runners/studio/background.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport { readFile, rename, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { connect as connectSocket, createServer } from 'node:net'\nimport path from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = { id: string; pid: number; port: number; state: WorkerState }\nconst states: Array<WorkerState> = ['starting', 'connected', 'reconnecting', 'authentication required', 'stopped']\nexport const getWorkerLogPath = () => path.join(getProjectKubbHome(), 'worker.log')\nconst statePath = () => path.join(getProjectKubbHome(), 'worker.json')\n\nasync function readWorker(): Promise<WorkerRecord | null> {\n try {\n const value: unknown = JSON.parse(await readFile(statePath(), 'utf8'))\n if (!value || typeof value !== 'object') return null\n const record = value as Partial<WorkerRecord>\n return typeof record.id === 'string' &&\n /^[a-f0-9]{32}$/.test(record.id) &&\n Number.isInteger(record.pid) &&\n (record.pid ?? 0) > 1 &&\n Number.isInteger(record.port) &&\n (record.port ?? 0) > 0 &&\n (record.port ?? 0) <= 65535 &&\n states.includes(record.state as WorkerState)\n ? (record as WorkerRecord)\n : null\n } catch {\n return null\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/** Authenticated loopback IPC; a stored PID never authorizes sending a process signal. */\nfunction requestWorker(record: WorkerRecord, command: 'status' | 'stop'): Promise<WorkerRecord> {\n return new Promise((resolve, reject) => {\n const socket = connectSocket({ host: '127.0.0.1', port: record.port })\n let received = ''\n socket.setTimeout(2_000, () => socket.destroy(new Error('Worker control timed out')))\n socket.once('error', reject)\n socket.once('connect', () => socket.write(JSON.stringify({ id: record.id, command }) + '\\n'))\n socket.on('data', (chunk: Buffer) => {\n received += chunk.toString()\n if (received.length > 4096) socket.destroy(new Error('Invalid worker response'))\n })\n socket.once('end', () => {\n try {\n const response = JSON.parse(received) as WorkerRecord\n if (response.id !== record.id || response.pid !== record.pid || !states.includes(response.state)) throw new Error('Worker identity changed')\n resolve(response)\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nexport async function getWorkerStatus(): Promise<{ running: boolean; state: WorkerState; pid?: number }> {\n const record = await readWorker()\n if (!record) return { running: false, state: 'stopped' }\n try {\n const response = await requestWorker(record, 'status')\n return { running: true, state: response.state, pid: response.pid }\n } catch {\n return { running: false, state: record.state === 'authentication required' ? record.state : 'stopped' }\n }\n}\n\nexport async function stopWorker(): Promise<void> {\n const record = await readWorker()\n if (!record) return\n try {\n await requestWorker(record, 'stop')\n } catch (error) {\n if (\n (error as NodeJS.ErrnoException).code !== 'ECONNREFUSED' &&\n isAlive(record.pid) &&\n record.state !== 'stopped' &&\n record.state !== 'authentication required'\n ) {\n throw new Error('Cannot verify the background worker. No process was signaled.')\n }\n return\n }\n const deadline = Date.now() + 15_000\n while (Date.now() < deadline) {\n try {\n await requestWorker(record, 'status')\n } catch {\n return\n }\n await delay(100)\n }\n throw new Error('The worker has not finished shutting down. Check worker.log and try again.')\n}\n\n/** The listening port is the project lock, so stale state never needs a PID-based takeover. */\nexport async function serveWorker(shutdown: AbortController) {\n const record: WorkerRecord = { id: randomBytes(16).toString('hex'), pid: process.pid, port: 0, state: 'starting' }\n const server = createServer((socket) => {\n let input = ''\n socket.setTimeout(2_000, () => socket.destroy())\n socket.on('error', () => {})\n socket.on('data', (chunk: Buffer) => {\n input += chunk.toString()\n if (input.length > 4096) {\n socket.destroy()\n return\n }\n if (!input.includes('\\n')) return\n try {\n const request = JSON.parse(input) as { id?: unknown; command?: unknown }\n if (request.id !== record.id || !['status', 'stop'].includes(String(request.command))) {\n socket.destroy()\n return\n }\n socket.end(JSON.stringify(record))\n if (request.command === 'stop') shutdown.abort()\n } catch {\n socket.destroy()\n }\n })\n })\n // Hash the project directory to choose its loopback port; fail on collisions.\n const port = 20_000 + (Number.parseInt(hash('sha256', getProjectKubbHome()).slice(0, 8), 16) % 30_000)\n try {\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', resolve)\n })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error\n // Let a simultaneous starter finish writing its record before checking ownership.\n await delay(100)\n const existing = await readWorker()\n if (existing?.port === port) {\n try {\n return { existing: await requestWorker(existing, 'status') }\n } catch {\n /* Refuse an unverified listener. */\n }\n }\n throw new Error('The project control port is occupied or another worker is starting. Try again after stopping that listener.')\n }\n record.port = port\n let saving = Promise.resolve()\n const save = () => {\n const value = JSON.stringify(record)\n saving = saving.then(async () => {\n const temporary = `${statePath()}.${record.id}`\n await writeFile(temporary, value, { mode: 0o600 })\n await rename(temporary, statePath())\n })\n return saving\n }\n try {\n await save()\n } catch (error) {\n server.close()\n throw error\n }\n return {\n async state(state: WorkerState) {\n record.state = state\n await save()\n },\n async close() {\n try {\n if (record.state !== 'authentication required') {\n record.state = 'stopped'\n await save()\n }\n } finally {\n await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))\n }\n },\n }\n}\n\nexport type WorkerLaunch = { options: StudioOptions; prepared: PreparedConnection }\n\nexport async function startWorker(options: StudioOptions): Promise<void> {\n const current = await getWorkerStatus()\n if (current.running) {\n console.log(`Already running (${current.state}, PID ${current.pid}).`)\n return\n }\n const prepared = await prepareConnection(options)\n const entry = path.join(path.dirname(createRequire(import.meta.url).resolve('@kubb/cli/package.json')), 'dist', 'studioWorker.js')\n const child = x(process.execPath, [...process.execArgv, entry], {\n nodeOptions: { cwd: process.cwd(), detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] },\n }).process\n if (!child) throw new Error('Background worker failed to start')\n try {\n const started = new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => done(new Error('Background worker startup timed out')), 20_000)\n const done = (error?: Error) => {\n clearTimeout(timer)\n child.removeListener('error', failed)\n child.removeListener('exit', exited)\n child.removeListener('message', ready)\n if (error) reject(error)\n else resolve()\n }\n const failed = (error: Error) => done(error)\n const exited = () => done(new Error(`Background worker exited during startup. Check ${getWorkerLogPath()}`))\n child.once('error', failed)\n child.once('exit', exited)\n const ready = (message: unknown) => {\n if (!message || typeof message !== 'object' || !('started' in message) || message.started !== true)\n return done(new Error('Invalid worker startup response'))\n done()\n }\n child.once('message', ready)\n child.send({ options: { ...options, autoOpen: false }, prepared } satisfies WorkerLaunch, (error) => {\n if (error) done(error)\n })\n })\n await started\n if (child.connected) child.disconnect()\n child.unref()\n const status = await getWorkerStatus()\n console.log(`Background worker ${status.state} (PID ${status.pid ?? child.pid}). Logs: ${getWorkerLogPath()}`)\n } catch (error) {\n // This is the child we just spawned, not a PID recovered from disk.\n child.kill('SIGTERM')\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,SAA6B;CAAC;CAAY;CAAa;CAAgB;CAA2B;AAAS;AACjH,MAAa,yBAAyB,KAAK,KAAK,mBAAmB,GAAG,YAAY;AAClF,MAAM,kBAAkB,KAAK,KAAK,mBAAmB,GAAG,aAAa;AAErE,eAAe,aAA2C;CACxD,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,MAAM,SAAS,UAAU,GAAG,MAAM,CAAC;EACrE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;EAChD,MAAM,SAAS;EACf,OAAO,OAAO,OAAO,OAAO,YAC1B,iBAAiB,KAAK,OAAO,EAAE,KAC/B,OAAO,UAAU,OAAO,GAAG,MAC1B,OAAO,OAAO,KAAK,KACpB,OAAO,UAAU,OAAO,IAAI,MAC3B,OAAO,QAAQ,KAAK,MACpB,OAAO,QAAQ,MAAM,SACtB,OAAO,SAAS,OAAO,KAAoB,IACxC,SACD;CACN,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,QAAQ,KAAsB;CACrC,IAAI;EACF,QAAQ,KA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G;GAAS,IAA2B,UAAU;IACnG,IAAI,OAAO,KAAK,KAAK;GACvB,CAAC;EACH,CACY;EACZ,IAAI,MAAM,WAAW,MAAM,WAAW;EACtC,MAAM,MAAM;EACZ,MAAM,SAAS,MAAM,gBAAgB;EACrC,QAAQ,IAAI,qBAAqB,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,IAAI,WAAW,iBAAiB,GAAG;CAC/G,SAAS,OAAO;EAEd,MAAM,KAAK,SAAS;EACpB,MAAM;CACR;AACF"}
@@ -1 +1 @@
1
- export { t as getWorkerLogPath, n as getWorkerStatus, i as startWorker, a as stopWorker } from "./background-Dtk2M5B8.js";
1
+ export { t as getWorkerLogPath, n as getWorkerStatus, i as startWorker, a as stopWorker } from "./background-DWasKvSw.js";
@@ -1,5 +1,5 @@
1
1
  import "./rolldown-runtime-CRm0XQPb.js";
2
- import { _ as isRichOutput, m as clackLogger, p as plainLogger, v as findConfigFile, y as loadConfigFile } from "./output-CCiHzIPS.js";
2
+ import { _ as isRichOutput, m as clackLogger, p as plainLogger, v as findConfigFile, y as loadConfigFile } from "./output-DIJsbXzW.js";
3
3
  import process from "node:process";
4
4
  import { resolve } from "node:path";
5
5
  import { createCliReporter } from "@kubb/core";
@@ -78,4 +78,4 @@ async function getConfigs({ configPath, input, watch, logLevel }) {
78
78
  //#endregion
79
79
  export { selectReporters as n, setupReporters as r, getConfigs as t };
80
80
 
81
- //# sourceMappingURL=config-66zh0aCP.js.map
81
+ //# sourceMappingURL=config-BPuFepc5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-66zh0aCP.js","names":[],"sources":["../src/loggers/reporters.ts","../src/config.ts"],"sourcesContent":["import process from 'node:process'\nimport type { Config, Hookable, KubbHooks, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter } from '@kubb/core'\nimport { isRichOutput } from '../utils/env.ts'\nimport type { Logger, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/** Bridges a {@link Reporter} onto the hook emitter: calls `report` with each config's {@link GenerationResult} on `kubb:generation:end`. */\nfunction installReporter(context: Hookable<KubbHooks>, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/** Installs the live logger and wires the selected reporters. `cli` renders its summary through the logger, and is skipped when `json` owns stdout. */\nfunction setupReporters(\n context: Hookable<KubbHooks>,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): void {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n const logger = forcedLogger ?? (isRichOutput() ? clackLogger : plainLogger)\n const handle = logger(context, { logLevel })\n\n // The summary belongs inside the group the logger opened for this config, so the logger writes it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n}\n\nexport default setupReporters\n\n/** Picks the reporters whose `name` is in `names`, in the given order (the CLI maps `--reporter` to this); duplicates and unknown names are skipped. */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n return [...new Set(names)].flatMap((name) => reporters.find((reporter) => reporter.name === name) ?? [])\n}\n","import { resolve } from 'node:path'\nimport { findConfigFile, loadConfigFile } from '@internals/shared'\nimport type { CLIOptions, Config } from '@kubb/core'\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 Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>(file, { config: configPath, input, watch, logLevel } satisfies CLIOptions)\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;AASA,SAAS,gBAAgB,SAA8B,UAAoB,KAA4B;CACrG,MAAM,cAAc,SAAS,mCAAmB,IAAI,IAAsC,IAAI,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3B,gBAAgB,SAAS,UAAU,GAAG;GACtC;EACF;EAEA,IAAI,SACF;EAIF,MAAM,UADS,iBAAiB,aAAa,IAAI,cAAc,aAAA,CACzC,SAAS,EAAE,SAAS,CAAC;EAG3C,gBAAgB,SAAS,kBAAkB,EAAE,QAAQ,QAAQ,cAAc,CAAC,GAAG,GAAG;CACpF;AACF;;AAKA,SAAgB,gBAAgB,WAAoC,OAA+C;CACjH,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,SAAS,SAAS,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI,KAAK,CAAC,CAAC;AACzG;;;;ACtDA,eAAsB,WAAW,EAAE,YAAY,OAAO,OAAO,YAA0D;CACrH,MAAM,OAAO,aAAa,QAAQ,UAAU,IAAI,eAAe;CAC/D,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,kGAAkG;CAGpH,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,eAAuB,MAAM;GAAE,QAAQ;GAAY;GAAO;GAAO;EAAS,CAAsB;CAClH,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC3D;CAEA,OAAO;EAAE,YAAY;EAAM,SAAS,QAAQ,KAAK,UAAU;GAAE,GAAG;GAAM,SAAS,KAAK,WAAW,CAAC;EAAE,EAAE;CAAE;AACxG"}
1
+ {"version":3,"file":"config-BPuFepc5.js","names":[],"sources":["../src/loggers/reporters.ts","../src/config.ts"],"sourcesContent":["import process from 'node:process'\nimport type { Config, Hookable, KubbHooks, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter } from '@kubb/core'\nimport { isRichOutput } from '../utils/env.ts'\nimport type { Logger, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/** Bridges a {@link Reporter} onto the hook emitter: calls `report` with each config's {@link GenerationResult} on `kubb:generation:end`. */\nfunction installReporter(context: Hookable<KubbHooks>, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/** Installs the live logger and wires the selected reporters. `cli` renders its summary through the logger, and is skipped when `json` owns stdout. */\nfunction setupReporters(\n context: Hookable<KubbHooks>,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): void {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n const logger = forcedLogger ?? (isRichOutput() ? clackLogger : plainLogger)\n const handle = logger(context, { logLevel })\n\n // The summary belongs inside the group the logger opened for this config, so the logger writes it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n}\n\nexport default setupReporters\n\n/** Picks the reporters whose `name` is in `names`, in the given order (the CLI maps `--reporter` to this); duplicates and unknown names are skipped. */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n return [...new Set(names)].flatMap((name) => reporters.find((reporter) => reporter.name === name) ?? [])\n}\n","import { resolve } from 'node:path'\nimport { findConfigFile, loadConfigFile } from '@internals/shared'\nimport type { CLIOptions, Config } from '@kubb/core'\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 Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>(file, { config: configPath, input, watch, logLevel } satisfies CLIOptions)\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;AASA,SAAS,gBAAgB,SAA8B,UAAoB,KAA4B;CACrG,MAAM,cAAc,SAAS,mCAAmB,IAAI,IAAsC,IAAI,KAAA;CAE9F,IAAI,aACF,QAAQ,KAAK,oBAAoB,EAAE,QAAQ,QAAQ,YAAY;EAC7D,MAAM,gBAAgB,YAAY,IA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AAA,CACzC,SAAS,EAAE,SAAS,CAAC;EAG3C,gBAAgB,SAAS,kBAAkB,EAAE,QAAQ,QAAQ,cAAc,CAAC,GAAG,GAAG;CACpF;AACF;;AAKA,SAAgB,gBAAgB,WAAoC,OAA+C;CACjH,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,SAAS,SAAS,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI,KAAK,CAAC,CAAC;AACzG;;;;ACtDA,eAAsB,WAAW,EAAE,YAAY,OAAO,OAAO,YAA0D;CACrH,MAAM,OAAO,aAAa,QAAQ,UAAU,IAAI,eAAe;CAC/D,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,kGAAkG;CAGpH,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,eAAuB,MAAM;GAAE,QAAQ;GAAY;GAAO;GAAO;EAAS,CAAsB;CAClH,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC3D;CAEA,OAAO;EAAE,YAAY;EAAM,SAAS,QAAQ,KAAK,UAAU;GAAE,GAAG;GAAM,SAAS,KAAK,WAAW,CAAC;EAAE,EAAE;CAAE;AACxG"}
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
2
- const require_output = require("./output-DOC3zu6i.cjs");
2
+ const require_output = require("./output-Ck7iT223.cjs");
3
3
  let node_process = require("node:process");
4
4
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
5
5
  let node_path = require("node:path");
@@ -96,4 +96,4 @@ Object.defineProperty(exports, "setupReporters", {
96
96
  }
97
97
  });
98
98
 
99
- //# sourceMappingURL=config-cb2nhvBt.cjs.map
99
+ //# sourceMappingURL=config-CGUQ39wR.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-cb2nhvBt.cjs","names":["process","isRichOutput","clackLogger","plainLogger","createCliReporter","resolve","findConfigFile","loadConfigFile"],"sources":["../src/loggers/reporters.ts","../src/config.ts"],"sourcesContent":["import process from 'node:process'\nimport type { Config, Hookable, KubbHooks, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter } from '@kubb/core'\nimport { isRichOutput } from '../utils/env.ts'\nimport type { Logger, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/** Bridges a {@link Reporter} onto the hook emitter: calls `report` with each config's {@link GenerationResult} on `kubb:generation:end`. */\nfunction installReporter(context: Hookable<KubbHooks>, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/** Installs the live logger and wires the selected reporters. `cli` renders its summary through the logger, and is skipped when `json` owns stdout. */\nfunction setupReporters(\n context: Hookable<KubbHooks>,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): void {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n const logger = forcedLogger ?? (isRichOutput() ? clackLogger : plainLogger)\n const handle = logger(context, { logLevel })\n\n // The summary belongs inside the group the logger opened for this config, so the logger writes it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n}\n\nexport default setupReporters\n\n/** Picks the reporters whose `name` is in `names`, in the given order (the CLI maps `--reporter` to this); duplicates and unknown names are skipped. */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n return [...new Set(names)].flatMap((name) => reporters.find((reporter) => reporter.name === name) ?? [])\n}\n","import { resolve } from 'node:path'\nimport { findConfigFile, loadConfigFile } from '@internals/shared'\nimport type { CLIOptions, Config } from '@kubb/core'\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 Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>(file, { config: configPath, input, watch, logLevel } satisfies CLIOptions)\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;;AASA,SAAS,gBAAgB,SAA8B,UAAoB,KAA4B;CACrG,MAAM,cAAc,SAAS,mCAAmB,IAAI,IAAsC,IAAI,KAAA;CAE9F,IAAI,aACF,QAAQ,KAAK,oBAAoB,EAAE,QAAQ,QAAQ,YAAY;EAC7D,MAAM,gBAAgB,YAAY,IAAI,MAAM,qBAAK,IAAI,IAAyB;EAC9E,MAAM,OAAO,IAAI,IAAI,CAAC,GAAG,cAAc,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,KAAK,CAAC,CAAC;EAC/E,MAAM,QAAQ,MAAM,QAAQ,SAAS,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,KAAK,IAAI;EAElF,IAAI,MAAM,QAAQ,cAAc,IAAI,OAAO,sBAAM,IAAI,IAAI,CAAC,GAAI,cAAc,IAAI,OAAO,IAAI,KAAK,CAAC,GAAI,GAAG,KAAK,CAAC,CAAC;EAE/G,YAAY,IAAI,QAAQ,aAAa;CACvC,CAAC;CAGH,QAAQ,KAAK,uBAAuB,OAAO,EAAE,QAAQ,cAAc,CAAC,GAAG,eAAe,GAAG,SAAS,WAAW,UAAUA,aAAAA,QAAQ,OAAO,QAAQ;EAC5I,MAAM,QAAQ,aAAa,IAAI,MAAM;EACrC,MAAM,UAA2C,SAAS,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ,OAAO,CAAC,GAAG,KAAK;EAAE,EAAE;EAE7H,MAAM,SAAS,OAAO;GAAE;GAAQ;GAAa;GAAc;GAAQ;GAAS,aAAa;EAAQ,GAAG,GAAG;EAEvG,aAAa,OAAO,MAAM;CAC5B,CAAC;CAED,IAAI,SAAS,OACX,QAAQ,KAAK,4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","plainLogger","createCliReporter","resolve","findConfigFile","loadConfigFile"],"sources":["../src/loggers/reporters.ts","../src/config.ts"],"sourcesContent":["import process from 'node:process'\nimport type { Config, Hookable, KubbHooks, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter } from '@kubb/core'\nimport { isRichOutput } from '../utils/env.ts'\nimport type { Logger, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/** Bridges a {@link Reporter} onto the hook emitter: calls `report` with each config's {@link GenerationResult} on `kubb:generation:end`. */\nfunction installReporter(context: Hookable<KubbHooks>, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/** Installs the live logger and wires the selected reporters. `cli` renders its summary through the logger, and is skipped when `json` owns stdout. */\nfunction setupReporters(\n context: Hookable<KubbHooks>,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): void {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n const logger = forcedLogger ?? (isRichOutput() ? clackLogger : plainLogger)\n const handle = logger(context, { logLevel })\n\n // The summary belongs inside the group the logger opened for this config, so the logger writes it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n}\n\nexport default setupReporters\n\n/** Picks the reporters whose `name` is in `names`, in the given order (the CLI maps `--reporter` to this); duplicates and unknown names are skipped. */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n return [...new Set(names)].flatMap((name) => reporters.find((reporter) => reporter.name === name) ?? [])\n}\n","import { resolve } from 'node:path'\nimport { findConfigFile, loadConfigFile } from '@internals/shared'\nimport type { CLIOptions, Config } from '@kubb/core'\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 Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n let configs: Array<Config>\n try {\n configs = await loadConfigFile<Config>(file, { config: configPath, input, watch, logLevel } satisfies CLIOptions)\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n return { configPath: file, configs: configs.map((item) => ({ ...item, plugins: item.plugins ?? [] })) }\n}\n"],"mappings":";;;;;;;;AASA,SAAS,gBAAgB,SAA8B,UAAoB,KAA4B;CACrG,MAAM,cAAc,SAAS,mCAAmB,IAAI,IAAsC,IAAI,KAAA;CAE9F,IAAI,aACF,QAAQ,KAAK,oBAAoB,EAAE,QAAQ,QAAQ,YAAY;EAC7D,MAAM,gBAAgB,YAAY,IAAI,MAAM,qBAAK,IAAI,IAAyB;EAC9E,MAAM,OAAO,IAAI,IAAI,CAAC,GAAG,cAAc,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,KAAK,CAAC,CAAC;EAC/E,MAAM,QAAQ,MAAM,QAAQ,SAAS,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,KAAK,IAAI;EAElF,IAAI,MAAM,QAAQ,cAAc,IAAI,OAAO,sBAAM,IAAI,IAAI,CAAC,GAAI,cAAc,IAAI,OAAO,IAAI,KAAK,CAAC,GAAI,GAAG,KAAK,CAAC,CAAC;EAE/G,YAAY,IAAI,QAAQ,aAAa;CACvC,CAAC;CAGH,QAAQ,KAAK,uBAAuB,OAAO,EAAE,QAAQ,cAAc,CAAC,GAAG,eAAe,GAAG,SAAS,WAAW,UAAUA,aAAAA,QAAQ,OAAO,QAAQ;EAC5I,MAAM,QAAQ,aAAa,IAAI,MAAM;EACrC,MAAM,UAA2C,SAAS,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,QAAQ,YAAY;GAAE;GAAQ,OAAO,CAAC,GAAG,KAAK;EAAE,EAAE;EAE7H,MAAM,SAAS,OAAO;GAAE;GAAQ;GAAa;GAAc;GAAQ;GAAS,aAAa;EAAQ,GAAG,GAAG;EAEvG,aAAa,OAAO,MA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 -1 +1 @@
1
- {"version":3,"file":"credentials-CZK6zPLv.js","names":[],"sources":["../src/runners/studio/credentials.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { kubbStorage, resolveKubbDir } from '@kubb/core'\n\nconst projectBase = (project = process.cwd()) => path.join('projects', hash('sha256', project))\n\n/**\n * Root for the credential and machine identity of the current project, inside `KUBB_HOME`.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n return resolveKubbDir(projectBase(project))\n}\n\nconst projectStorage = () => kubbStorage({ base: projectBase() })\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const stored = await projectStorage()\n .getItem<Credentials>(CREDENTIALS_FILENAME)\n .catch(() => null)\n\n return typeof stored?.token === 'string' && stored.token !== '' ? stored : null\n}\n\n/**\n * Writes the credential into the project folder, which only its owner can open.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n await projectStorage().setItem(CREDENTIALS_FILENAME, credentials)\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await projectStorage().removeItem(CREDENTIALS_FILENAME)\n}\n\n/**\n * Reads this project's machine secret, creating it on first use. Pairing sends its hash, so pairing\n * the same project again rotates one agent's token instead of creating a second agent. It lives\n * apart from the credential, which {@link clearCredentials} deletes.\n */\nexport async function getMachineId(): Promise<string> {\n const storage = projectStorage()\n const stored = await storage.getItem('machine-secret').catch(() => null)\n if (typeof stored === 'string' && stored.trim()) return stored.trim()\n\n const secret = randomBytes(32).toString('hex')\n await storage.setItem('machine-secret', secret)\n\n return secret\n}\n"],"mappings":";;;;;;AAKA,MAAM,eAAe,UAAU,QAAQ,IAAI,MAAM,KAAK,KAAK,YAAY,KAAK,UAAU,OAAO,CAAC;;;;;;;AAQ9F,SAAgB,mBAAmB,UAAU,QAAQ,IAAI,GAAW;CAClE,OAAO,eAAe,YAAY,OAAO,CAAC;AAC5C;AAEA,MAAM,uBAAuB,YAAY,EAAE,MAAM,YAAY,EAAE,CAAC;AAEhE,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAO,KAAK,KAAK,mBAAmB,GAAG,oBAAoB;AAC7D;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,SAAS,MAAM,eAAe,CAAC,CAClC,QAAqB,oBAAoB,CAAC,CAC1C,YAAY,IAAI;CAEnB,OAAO,OAAO,QAAQ,UAAU,YAAY,OAAO,UAAU,KAAK,SAAS;AAC7E;;;;AAKA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,eAAe,CAAC,CAAC,QAAQ,sBAAsB,WAAW;AAClE;;;;AAKA,eAAsB,mBAAkC;CACtD,MAAM,eAAe,CAAC,CAAC,WAAW,oBAAoB;AACxD;;;;;;AAOA,eAAsB,eAAgC;CACpD,MAAM,UAAU,eAAe;CAC/B,MAAM,SAAS,MAAM,QAAQ,QAAQ,gBAAgB,CAAC,CAAC,YAAY,IAAI;CACvE,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CAEpE,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC7C,MAAM,QAAQ,QAAQ,kBAAkB,MAAM;CAE9C,OAAO;AACT"}
1
+ {"version":3,"file":"credentials-CZK6zPLv.js","names":[],"sources":["../src/runners/studio/credentials.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { kubbStorage, resolveKubbDir } from '@kubb/core'\n\nconst projectBase = (project = process.cwd()) => path.join('projects', hash('sha256', project))\n\n/**\n * Root for the credential and machine identity of the current project, inside `KUBB_HOME`.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n return resolveKubbDir(projectBase(project))\n}\n\nconst projectStorage = () => kubbStorage({ base: projectBase() })\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowReadAst?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const stored = await projectStorage()\n .getItem<Credentials>(CREDENTIALS_FILENAME)\n .catch(() => null)\n\n return typeof stored?.token === 'string' && stored.token !== '' ? stored : null\n}\n\n/**\n * Writes the credential into the project folder, which only its owner can open.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n await projectStorage().setItem(CREDENTIALS_FILENAME, credentials)\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await projectStorage().removeItem(CREDENTIALS_FILENAME)\n}\n\n/**\n * Reads this project's machine secret, creating it on first use. Pairing sends its hash, so pairing\n * the same project again rotates one agent's token instead of creating a second agent. It lives\n * apart from the credential, which {@link clearCredentials} deletes.\n */\nexport async function getMachineId(): Promise<string> {\n const storage = projectStorage()\n const stored = await storage.getItem('machine-secret').catch(() => null)\n if (typeof stored === 'string' && stored.trim()) return stored.trim()\n\n const secret = randomBytes(32).toString('hex')\n await storage.setItem('machine-secret', secret)\n\n return secret\n}\n"],"mappings":";;;;;;AAKA,MAAM,eAAe,UAAU,QAAQ,IAAI,MAAM,KAAK,KAAK,YAAY,KAAK,UAAU,OAAO,CAAC;;;;;;;AAQ9F,SAAgB,mBAAmB,UAAU,QAAQ,IAAI,GAAW;CAClE,OAAO,eAAe,YAAY,OAAO,CAAC;AAC5C;AAEA,MAAM,uBAAuB,YAAY,EAAE,MAAM,YAAY,EAAE,CAAC;AAEhE,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAO,KAAK,KAAK,mBAAmB,GAAG,oBAAoB;AAC7D;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,SAAS,MAAM,eAAe,CAAC,CAClC,QAAqB,oBAAoB,CAAC,CAC1C,YAAY,IAAI;CAEnB,OAAO,OAAO,QAAQ,UAAU,YAAY,OAAO,UAAU,KAAK,SAAS;AAC7E;;;;AAKA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,eAAe,CAAC,CAAC,QAAQ,sBAAsB,WAAW;AAClE;;;;AAKA,eAAsB,mBAAkC;CACtD,MAAM,eAAe,CAAC,CAAC,WAAW,oBAAoB;AACxD;;;;;;AAOA,eAAsB,eAAgC;CACpD,MAAM,UAAU,eAAe;CAC/B,MAAM,SAAS,MAAM,QAAQ,QAAQ,gBAAgB,CAAC,CAAC,YAAY,IAAI;CACvE,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CAEpE,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC7C,MAAM,QAAQ,QAAQ,kBAAkB,MAAM;CAE9C,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"credentials-DDaKqtJn.cjs","names":["process","path","hash","resolveKubbDir","kubbStorage","randomBytes"],"sources":["../src/runners/studio/credentials.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { kubbStorage, resolveKubbDir } from '@kubb/core'\n\nconst projectBase = (project = process.cwd()) => path.join('projects', hash('sha256', project))\n\n/**\n * Root for the credential and machine identity of the current project, inside `KUBB_HOME`.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n return resolveKubbDir(projectBase(project))\n}\n\nconst projectStorage = () => kubbStorage({ base: projectBase() })\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const stored = await projectStorage()\n .getItem<Credentials>(CREDENTIALS_FILENAME)\n .catch(() => null)\n\n return typeof stored?.token === 'string' && stored.token !== '' ? stored : null\n}\n\n/**\n * Writes the credential into the project folder, which only its owner can open.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n await projectStorage().setItem(CREDENTIALS_FILENAME, credentials)\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await projectStorage().removeItem(CREDENTIALS_FILENAME)\n}\n\n/**\n * Reads this project's machine secret, creating it on first use. Pairing sends its hash, so pairing\n * the same project again rotates one agent's token instead of creating a second agent. It lives\n * apart from the credential, which {@link clearCredentials} deletes.\n */\nexport async function getMachineId(): Promise<string> {\n const storage = projectStorage()\n const stored = await storage.getItem('machine-secret').catch(() => null)\n if (typeof stored === 'string' && stored.trim()) return stored.trim()\n\n const secret = randomBytes(32).toString('hex')\n await storage.setItem('machine-secret', secret)\n\n return secret\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAKA,MAAM,eAAe,UAAUA,aAAAA,QAAQ,IAAI,MAAMC,UAAAA,QAAK,KAAK,aAAA,GAAYC,YAAAA,KAAAA,CAAK,UAAU,OAAO,CAAC;;;;;;;AAQ9F,SAAgB,mBAAmB,UAAUF,aAAAA,QAAQ,IAAI,GAAW;CAClE,QAAA,GAAOG,WAAAA,eAAAA,CAAe,YAAY,OAAO,CAAC;AAC5C;AAEA,MAAM,wBAAA,GAAuBC,WAAAA,YAAAA,CAAY,EAAE,MAAM,YAAY,EAAE,CAAC;AAEhE,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAOH,UAAAA,QAAK,KAAK,mBAAmB,GAAG,oBAAoB;AAC7D;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,SAAS,MAAM,eAAe,CAAC,CAClC,QAAqB,oBAAoB,CAAC,CAC1C,YAAY,IAAI;CAEnB,OAAO,OAAO,QAAQ,UAAU,YAAY,OAAO,UAAU,KAAK,SAAS;AAC7E;;;;AAKA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,eAAe,CAAC,CAAC,QAAQ,sBAAsB,WAAW;AAClE;;;;AAKA,eAAsB,mBAAkC;CACtD,MAAM,eAAe,CAAC,CAAC,WAAW,oBAAoB;AACxD;;;;;;AAOA,eAAsB,eAAgC;CACpD,MAAM,UAAU,eAAe;CAC/B,MAAM,SAAS,MAAM,QAAQ,QAAQ,gBAAgB,CAAC,CAAC,YAAY,IAAI;CACvE,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CAEpE,MAAM,UAAA,GAASI,YAAAA,YAAAA,CAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC7C,MAAM,QAAQ,QAAQ,kBAAkB,MAAM;CAE9C,OAAO;AACT"}
1
+ {"version":3,"file":"credentials-DDaKqtJn.cjs","names":["process","path","hash","resolveKubbDir","kubbStorage","randomBytes"],"sources":["../src/runners/studio/credentials.ts"],"sourcesContent":["import { hash, randomBytes } from 'node:crypto'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { kubbStorage, resolveKubbDir } from '@kubb/core'\n\nconst projectBase = (project = process.cwd()) => path.join('projects', hash('sha256', project))\n\n/**\n * Root for the credential and machine identity of the current project, inside `KUBB_HOME`.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n return resolveKubbDir(projectBase(project))\n}\n\nconst projectStorage = () => kubbStorage({ base: projectBase() })\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowReadAst?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const stored = await projectStorage()\n .getItem<Credentials>(CREDENTIALS_FILENAME)\n .catch(() => null)\n\n return typeof stored?.token === 'string' && stored.token !== '' ? stored : null\n}\n\n/**\n * Writes the credential into the project folder, which only its owner can open.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n await projectStorage().setItem(CREDENTIALS_FILENAME, credentials)\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await projectStorage().removeItem(CREDENTIALS_FILENAME)\n}\n\n/**\n * Reads this project's machine secret, creating it on first use. Pairing sends its hash, so pairing\n * the same project again rotates one agent's token instead of creating a second agent. It lives\n * apart from the credential, which {@link clearCredentials} deletes.\n */\nexport async function getMachineId(): Promise<string> {\n const storage = projectStorage()\n const stored = await storage.getItem('machine-secret').catch(() => null)\n if (typeof stored === 'string' && stored.trim()) return stored.trim()\n\n const secret = randomBytes(32).toString('hex')\n await storage.setItem('machine-secret', secret)\n\n return secret\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAKA,MAAM,eAAe,UAAUA,aAAAA,QAAQ,IAAI,MAAMC,UAAAA,QAAK,KAAK,aAAA,GAAYC,YAAAA,KAAAA,CAAK,UAAU,OAAO,CAAC;;;;;;;AAQ9F,SAAgB,mBAAmB,UAAUF,aAAAA,QAAQ,IAAI,GAAW;CAClE,QAAA,GAAOG,WAAAA,eAAAA,CAAe,YAAY,OAAO,CAAC;AAC5C;AAEA,MAAM,wBAAA,GAAuBC,WAAAA,YAAAA,CAAY,EAAE,MAAM,YAAY,EAAE,CAAC;AAEhE,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAOH,UAAAA,QAAK,KAAK,mBAAmB,GAAG,oBAAoB;AAC7D;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,SAAS,MAAM,eAAe,CAAC,CAClC,QAAqB,oBAAoB,CAAC,CAC1C,YAAY,IAAI;CAEnB,OAAO,OAAO,QAAQ,UAAU,YAAY,OAAO,UAAU,KAAK,SAAS;AAC7E;;;;AAKA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,eAAe,CAAC,CAAC,QAAQ,sBAAsB,WAAW;AAClE;;;;AAKA,eAAsB,mBAAkC;CACtD,MAAM,eAAe,CAAC,CAAC,WAAW,oBAAoB;AACxD;;;;;;AAOA,eAAsB,eAAgC;CACpD,MAAM,UAAU,eAAe;CAC/B,MAAM,SAAS,MAAM,QAAQ,QAAQ,gBAAgB,CAAC,CAAC,YAAY,IAAI;CACvE,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CAEpE,MAAM,UAAA,GAASI,YAAAA,YAAAA,CAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC7C,MAAM,QAAQ,QAAQ,kBAAkB,MAAM;CAE9C,OAAO;AACT"}