@kubb/cli 5.18.8 → 5.19.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.
- package/dist/{Telemetry-CBzCK4kO.cjs → Telemetry-B2TeLVo4.cjs} +2 -2
- package/dist/{Telemetry-CBzCK4kO.cjs.map → Telemetry-B2TeLVo4.cjs.map} +1 -1
- package/dist/{Telemetry-DUl_hxVn.js → Telemetry-Ctyp_EFO.js} +2 -2
- package/dist/{Telemetry-DUl_hxVn.js.map → Telemetry-Ctyp_EFO.js.map} +1 -1
- package/dist/{background-CA9lRKAK.js → background-CByahHYn.js} +2 -2
- package/dist/{background-CA9lRKAK.js.map → background-CByahHYn.js.map} +1 -1
- package/dist/{background-DK3HLyNk.js → background-D60rO2Lz.js} +1 -1
- package/dist/{background-fhpYDuSs.cjs → background-D6dQxXt6.cjs} +2 -2
- package/dist/{background-fhpYDuSs.cjs.map → background-D6dQxXt6.cjs.map} +1 -1
- package/dist/{configFile-BQ-Pp7i_.cjs → configFile-B_xrd2yx.cjs} +5 -5
- package/dist/configFile-B_xrd2yx.cjs.map +1 -0
- package/dist/{configFile-CPXDgTC2.js → configFile-Bh_5k4pf.js} +5 -5
- package/dist/configFile-Bh_5k4pf.js.map +1 -0
- package/dist/{fs-CmODfKN-.js → fs-CWRKTIst.js} +59 -2
- package/dist/fs-CWRKTIst.js.map +1 -0
- package/dist/index.cjs +11 -11
- package/dist/index.js +11 -11
- package/dist/{installWithSpinner-gv_OWgww.js → installWithSpinner-RJhWCsgh.js} +2 -2
- package/dist/{installWithSpinner-gv_OWgww.js.map → installWithSpinner-RJhWCsgh.js.map} +1 -1
- package/dist/{installWithSpinner-DZDlVp1J.cjs → installWithSpinner-qjIqjyiW.cjs} +3 -3
- package/dist/{installWithSpinner-DZDlVp1J.cjs.map → installWithSpinner-qjIqjyiW.cjs.map} +1 -1
- package/dist/{mcp-CQXp9pcW.js → mcp-BrB7TJZU.js} +2 -2
- package/dist/{mcp-CQXp9pcW.js.map → mcp-BrB7TJZU.js.map} +1 -1
- package/dist/{mcp-BBD4kdKF.cjs → mcp-D2gcpCcx.cjs} +2 -2
- package/dist/{mcp-BBD4kdKF.cjs.map → mcp-D2gcpCcx.cjs.map} +1 -1
- package/dist/package-CcsdQpSf.js +5 -0
- package/dist/package-CcsdQpSf.js.map +1 -0
- package/dist/{package-DXNoJQYa.cjs → package-DM5mr0Yc.cjs} +2 -2
- package/dist/package-DM5mr0Yc.cjs.map +1 -0
- package/dist/{reporters-DeruUk9K.js → reporters-B6p0n7s3.js} +8 -66
- package/dist/reporters-B6p0n7s3.js.map +1 -0
- package/dist/{reporters-CzxaQ_bD.js → reporters-BDzKLpyo.js} +1 -1
- package/dist/{reporters-CaJ8brYA.cjs → reporters-DLK4D0js.cjs} +10 -68
- package/dist/reporters-DLK4D0js.cjs.map +1 -0
- package/dist/{run-GdctJlXN.cjs → run-3OxB7Zxn.cjs} +5 -5
- package/dist/{run-GdctJlXN.cjs.map → run-3OxB7Zxn.cjs.map} +1 -1
- package/dist/{run-Bxqg0GuI.cjs → run-4MUhIiPj.cjs} +2 -2
- package/dist/{run-Bxqg0GuI.cjs.map → run-4MUhIiPj.cjs.map} +1 -1
- package/dist/{run-OqiJknWr.cjs → run-6qjg9Twy.cjs} +7 -7
- package/dist/{run-OqiJknWr.cjs.map → run-6qjg9Twy.cjs.map} +1 -1
- package/dist/{run-CYdKWpyH.js → run-B3TuKUr4.js} +5 -5
- package/dist/{run-CYdKWpyH.js.map → run-B3TuKUr4.js.map} +1 -1
- package/dist/{run-Bi8hhAzv.js → run-BJiP4ib3.js} +1 -1
- package/dist/{run-CmHjIMpd.js → run-BSsTBfse.js} +5 -5
- package/dist/{run-CmHjIMpd.js.map → run-BSsTBfse.js.map} +1 -1
- package/dist/{run-k-LqKkgU.cjs → run-C2lQXYrF.cjs} +5 -5
- package/dist/{run-k-LqKkgU.cjs.map → run-C2lQXYrF.cjs.map} +1 -1
- package/dist/{run-CIEKCdM-.cjs → run-C6tE9zTS.cjs} +6 -6
- package/dist/{run-CIEKCdM-.cjs.map → run-C6tE9zTS.cjs.map} +1 -1
- package/dist/{run-96_svbr3.js → run-CC9TBCph.js} +4 -4
- package/dist/{run-96_svbr3.js.map → run-CC9TBCph.js.map} +1 -1
- package/dist/{run-ixh050Ip.js → run-CcWmws1R.js} +2 -2
- package/dist/{run-ixh050Ip.js.map → run-CcWmws1R.js.map} +1 -1
- package/dist/{run-Df4PGOFX.js → run-Cxfs1SLQ.js} +4 -4
- package/dist/{run-Df4PGOFX.js.map → run-Cxfs1SLQ.js.map} +1 -1
- package/dist/{run-DLRu4z5Z.cjs → run-D0HO6_Yr.cjs} +4 -4
- package/dist/{run-DLRu4z5Z.cjs.map → run-D0HO6_Yr.cjs.map} +1 -1
- package/dist/{run-ORjkOWFp.js → run-D2tJP_b8.js} +2 -2
- package/dist/{run-ORjkOWFp.js.map → run-D2tJP_b8.js.map} +1 -1
- package/dist/{run-U2Ze_QP4.js → run-DFOjQVMO.js} +6 -6
- package/dist/{run-U2Ze_QP4.js.map → run-DFOjQVMO.js.map} +1 -1
- package/dist/{run-CpyFU0RM.js → run-Dyzva1xB.js} +6 -6
- package/dist/{run-CpyFU0RM.js.map → run-Dyzva1xB.js.map} +1 -1
- package/dist/{run-BIgV2zvB.cjs → run-ejmyJI37.cjs} +2 -2
- package/dist/{run-BIgV2zvB.cjs.map → run-ejmyJI37.cjs.map} +1 -1
- package/dist/{run-BSA2x4iE.cjs → run-lH8k2FY7.cjs} +6 -6
- package/dist/{run-BSA2x4iE.cjs.map → run-lH8k2FY7.cjs.map} +1 -1
- package/dist/{snapshot-C-ge8g3_.cjs → snapshot-DdRni_x5.cjs} +4 -4
- package/dist/{snapshot-C-ge8g3_.cjs.map → snapshot-DdRni_x5.cjs.map} +1 -1
- package/dist/{snapshot-CSacL1qI.js → snapshot-DnqAAzKE.js} +4 -4
- package/dist/{snapshot-CSacL1qI.js.map → snapshot-DnqAAzKE.js.map} +1 -1
- package/dist/{spinner-D584jFAz.cjs → spinner-BQgUoe7F.cjs} +70 -1
- package/dist/spinner-BQgUoe7F.cjs.map +1 -0
- package/dist/{status-Bq-Bjo2n.js → status-X9BNNp9F.js} +3 -3
- package/dist/{status-Bq-Bjo2n.js.map → status-X9BNNp9F.js.map} +1 -1
- package/dist/{status-D-Osmkhr.cjs → status-wHJjD3Fs.cjs} +3 -3
- package/dist/{status-D-Osmkhr.cjs.map → status-wHJjD3Fs.cjs.map} +1 -1
- package/dist/{studio-BZ53idqa.cjs → studio-j4As00N6.cjs} +11 -11
- package/dist/{studio-BZ53idqa.cjs.map → studio-j4As00N6.cjs.map} +1 -1
- package/dist/{studio-BBXKjMN-.js → studio-rRSg33RE.js} +11 -11
- package/dist/{studio-BBXKjMN-.js.map → studio-rRSg33RE.js.map} +1 -1
- package/dist/studioWorker.js +2 -2
- package/dist/{utils-BVccq6W0.js → utils-DnmjcKb0.js} +4 -10
- package/dist/utils-DnmjcKb0.js.map +1 -0
- package/dist/{utils-C9fYoqP2.cjs → utils-_hY0r-7x.cjs} +4 -10
- package/dist/utils-_hY0r-7x.cjs.map +1 -0
- package/dist/{validate-BuStuH_z.js → validate-CSbYneXo.js} +2 -2
- package/dist/{validate-BuStuH_z.js.map → validate-CSbYneXo.js.map} +1 -1
- package/dist/{validate-rr0LpFhN.cjs → validate-CyxoAzEK.cjs} +2 -2
- package/dist/{validate-rr0LpFhN.cjs.map → validate-CyxoAzEK.cjs.map} +1 -1
- package/package.json +7 -7
- package/dist/configFile-BQ-Pp7i_.cjs.map +0 -1
- package/dist/configFile-CPXDgTC2.js.map +0 -1
- package/dist/fs-CmODfKN-.js.map +0 -1
- package/dist/package-CdMFA8OG.js +0 -5
- package/dist/package-CdMFA8OG.js.map +0 -1
- package/dist/package-DXNoJQYa.cjs.map +0 -1
- package/dist/reporters-CaJ8brYA.cjs.map +0 -1
- package/dist/reporters-DeruUk9K.js.map +0 -1
- package/dist/spinner-D584jFAz.cjs.map +0 -1
- package/dist/utils-BVccq6W0.js.map +0 -1
- package/dist/utils-C9fYoqP2.cjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-BV8xUvPy.cjs");
|
|
2
2
|
const require_time = require("./time-D4xUq6tx.cjs");
|
|
3
3
|
const require_isCIEnvironment = require("./isCIEnvironment-jzKqdVwJ.cjs");
|
|
4
|
-
const require_package = require("./package-
|
|
4
|
+
const require_package = require("./package-DM5mr0Yc.cjs");
|
|
5
5
|
let node_crypto = require("node:crypto");
|
|
6
6
|
let node_os = require("node:os");
|
|
7
7
|
node_os = require_rolldown_runtime.__toESM(node_os, 1);
|
|
@@ -175,4 +175,4 @@ Object.defineProperty(exports, "trackRun", {
|
|
|
175
175
|
}
|
|
176
176
|
});
|
|
177
177
|
|
|
178
|
-
//# sourceMappingURL=Telemetry-
|
|
178
|
+
//# sourceMappingURL=Telemetry-B2TeLVo4.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Telemetry-
|
|
1
|
+
{"version":3,"file":"Telemetry-B2TeLVo4.cjs","names":["process","getElapsedMs","randomBytes","getAgentProfile","version","runtime","os","isCIEnvironment"],"sources":["../src/Telemetry.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { getElapsedMs, isCIEnvironment, runtime } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\nimport { version } from '../package.json'\n\n/** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */\nconst OTLP_ENDPOINT = 'https://otlp.kubb.dev' as const\n\ntype TelemetryCommand = 'generate' | 'mcp' | 'studio' | 'validate'\n\n/**\n * Anonymous plugin name and options snapshot sent with each telemetry event.\n */\nexport type TelemetryPlugin = {\n /**\n * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.\n */\n name: string\n /**\n * Anonymized snapshot of the plugin options. Values are included but cannot be traced back to a user.\n */\n options: Record<string, unknown>\n}\n\n/** How a command run ended, as the command reports it to the function {@link trackRun} returned. */\ntype RunResult = {\n status: 'success' | 'failed'\n plugins?: Array<TelemetryPlugin>\n filesCreated?: number\n /**\n * Name the MCP client sends in its `initialize` request, e.g. `'claude-code'`. Only set for `kubb mcp`.\n */\n mcpClient?: string\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isDisabled(): boolean {\n return ['DO_NOT_TRACK', 'KUBB_DISABLE_TELEMETRY'].some((name) => ['1', 'true'].includes(process.env[name] ?? ''))\n}\n\n/** Tracks one command run for the running CLI version; returns the reporter the command calls once it knows how it ended. */\nexport function trackRun({ command, hrStart }: { command: TelemetryCommand; hrStart: [number, number] }): (result: RunResult) => Promise<void> {\n return (result) => sendTelemetry(buildOtlpPayload({ command, duration: Math.round(getElapsedMs(hrStart)), ...result }))\n}\n\n/**\n * The OTLP trace payload for one run: a span named after the command whose attributes are the\n * anonymous run facts. The attribute keys are the contract with otlp.kubb.dev.\n *\n * @see https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload({\n command,\n duration,\n status,\n plugins = [],\n filesCreated = 0,\n mcpClient,\n}: RunResult & { command: TelemetryCommand; duration: number }) {\n const traceId = randomBytes(16).toString('hex')\n const spanId = randomBytes(8).toString('hex')\n const endTimeNs = BigInt(Date.now()) * 1_000_000n\n const startTimeNs = endTimeNs - BigInt(duration) * 1_000_000n\n const pluginNames = [...new Set(plugins.map((plugin) => plugin.name))].sort()\n const agent = getAgentProfile()\n\n const attributes = [\n { key: 'kubb.command', value: { stringValue: command } },\n { key: 'kubb.version', value: { stringValue: version } },\n { key: 'kubb.node_version', value: { stringValue: process.versions.node.split('.')[0] as string } },\n { key: 'kubb.runtime', value: { stringValue: runtime.name } },\n { key: 'kubb.runtime_version', value: { stringValue: runtime.version.split('.')[0] as string } },\n { key: 'kubb.platform', value: { stringValue: os.platform() } },\n { key: 'kubb.ci', value: { boolValue: isCIEnvironment() } },\n // A terminal on stdin means a person typed the command; agents, scripts, and CI pipe it.\n { key: 'kubb.tty', value: { boolValue: process.stdin.isTTY === true } },\n ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\n // The client picks this name, so cap its length before it leaves the machine.\n ...(mcpClient ? [{ key: 'kubb.mcp_client', value: { stringValue: mcpClient.slice(0, 64) } }] : []),\n { key: 'kubb.files_created', value: { intValue: filesCreated } },\n { key: 'kubb.status', value: { stringValue: status } },\n {\n key: 'kubb.plugins',\n value: { arrayValue: { values: pluginNames.map((name) => ({ stringValue: name })) } },\n },\n ...pluginNames.map((name) => ({ key: `kubb.plugin.${name}`, value: { boolValue: true } })),\n {\n key: 'kubb.plugin_options',\n value: {\n arrayValue: {\n values: plugins.map((p) => ({\n kvlistValue: {\n values: [\n { key: 'name', value: { stringValue: p.name } },\n {\n key: 'options',\n value: {\n stringValue: JSON.stringify({\n ...p.options,\n usedEnumNames: undefined,\n }),\n },\n },\n ],\n },\n })),\n },\n },\n },\n ]\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb' } },\n { key: 'service.version', value: { stringValue: version } },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-core', version },\n spans: [\n {\n traceId,\n spanId,\n name: command,\n kind: 1,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: status === 'success' ? 1 : 2,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an OTLP payload to the Kubb endpoint. Respects `DO_NOT_TRACK` and\n * `KUBB_DISABLE_TELEMETRY`, and fails silently so telemetry never interrupts a run. No file\n * paths, OpenAPI specs, or secrets are sent.\n */\nexport async function sendTelemetry(payload: ReturnType<typeof buildOtlpPayload>): Promise<void> {\n if (isDisabled()) {\n return\n }\n\n try {\n await fetch(`${OTLP_ENDPOINT}/v1/traces`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Kubb-Telemetry-Version': '1',\n 'Kubb-Telemetry-Source': 'kubb-cli',\n },\n body: JSON.stringify(payload),\n // Short, since an unfinished request keeps the process alive after the run.\n signal: AbortSignal.timeout(1_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the run\n }\n}\n"],"mappings":";;;;;;;;;;;;AAQA,MAAM,gBAAgB;;;;AAgCtB,SAAgB,aAAsB;CACpC,OAAO,CAAC,gBAAgB,wBAAwB,CAAC,CAAC,MAAM,SAAS,CAAC,KAAK,MAAM,CAAC,CAAC,SAASA,aAAAA,QAAQ,IAAI,SAAS,EAAE,CAAC;AAClH;;AAGA,SAAgB,SAAS,EAAE,SAAS,WAA2G;CAC7I,QAAQ,WAAW,cAAc,iBAAiB;EAAE;EAAS,UAAU,KAAK,MAAMC,aAAAA,aAAa,OAAO,CAAC;EAAG,GAAG;CAAO,CAAC,CAAC;AACxH;;;;;;;AAQA,SAAgB,iBAAiB,EAC/B,SACA,UACA,QACA,UAAU,CAAC,GACX,eAAe,GACf,aAC8D;CAC9D,MAAM,WAAA,GAAUC,YAAAA,YAAAA,CAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC9C,MAAM,UAAA,GAASA,YAAAA,YAAAA,CAAY,CAAC,CAAC,CAAC,SAAS,KAAK;CAC5C,MAAM,YAAY,OAAO,KAAK,IAAI,CAAC,IAAI;CACvC,MAAM,cAAc,YAAY,OAAO,QAAQ,IAAI;CACnD,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,QAAQ,KAAK,WAAW,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK;CAC5E,MAAM,SAAA,GAAQC,aAAAA,gBAAAA,CAAgB;CAE9B,MAAM,aAAa;EACjB;GAAE,KAAK;GAAgB,OAAO,EAAE,aAAa,QAAQ;EAAE;EACvD;GAAE,KAAK;GAAgB,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,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,aAAaI,gBAAAA,QAAQ;GAAE;GAC1D;IAAE,KAAK;IAA0B,OAAO,EAAE,aAAa,SAAS;GAAE;EACpE,EACF;EACA,YAAY,CACV;GACE,OAAO;IAAE,MAAM;IAAa,SAAA,gBAAA;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;GAE5B,QAAQ,YAAY,QAAQ,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
2
|
import { n as getElapsedMs, r as runtime } from "./time-D7ONPPZf.js";
|
|
3
3
|
import { t as isCIEnvironment } from "./isCIEnvironment-DAMZSlP2.js";
|
|
4
|
-
import { t as version } from "./package-
|
|
4
|
+
import { t as version } from "./package-CcsdQpSf.js";
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import process from "node:process";
|
|
@@ -162,4 +162,4 @@ async function sendTelemetry(payload) {
|
|
|
162
162
|
}
|
|
163
163
|
export { trackRun as n, isDisabled as t };
|
|
164
164
|
|
|
165
|
-
//# sourceMappingURL=Telemetry-
|
|
165
|
+
//# sourceMappingURL=Telemetry-Ctyp_EFO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Telemetry-
|
|
1
|
+
{"version":3,"file":"Telemetry-Ctyp_EFO.js","names":[],"sources":["../src/Telemetry.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { getElapsedMs, isCIEnvironment, runtime } from '@internals/utils'\nimport { getAgentProfile } from 'gunshi/agent'\nimport { version } from '../package.json'\n\n/** OpenTelemetry ingestion endpoint for anonymous usage telemetry. */\nconst OTLP_ENDPOINT = 'https://otlp.kubb.dev' as const\n\ntype TelemetryCommand = 'generate' | 'mcp' | 'studio' | 'validate'\n\n/**\n * Anonymous plugin name and options snapshot sent with each telemetry event.\n */\nexport type TelemetryPlugin = {\n /**\n * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.\n */\n name: string\n /**\n * Anonymized snapshot of the plugin options. Values are included but cannot be traced back to a user.\n */\n options: Record<string, unknown>\n}\n\n/** How a command run ended, as the command reports it to the function {@link trackRun} returned. */\ntype RunResult = {\n status: 'success' | 'failed'\n plugins?: Array<TelemetryPlugin>\n filesCreated?: number\n /**\n * Name the MCP client sends in its `initialize` request, e.g. `'claude-code'`. Only set for `kubb mcp`.\n */\n mcpClient?: string\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isDisabled(): boolean {\n return ['DO_NOT_TRACK', 'KUBB_DISABLE_TELEMETRY'].some((name) => ['1', 'true'].includes(process.env[name] ?? ''))\n}\n\n/** Tracks one command run for the running CLI version; returns the reporter the command calls once it knows how it ended. */\nexport function trackRun({ command, hrStart }: { command: TelemetryCommand; hrStart: [number, number] }): (result: RunResult) => Promise<void> {\n return (result) => sendTelemetry(buildOtlpPayload({ command, duration: Math.round(getElapsedMs(hrStart)), ...result }))\n}\n\n/**\n * The OTLP trace payload for one run: a span named after the command whose attributes are the\n * anonymous run facts. The attribute keys are the contract with otlp.kubb.dev.\n *\n * @see https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload({\n command,\n duration,\n status,\n plugins = [],\n filesCreated = 0,\n mcpClient,\n}: RunResult & { command: TelemetryCommand; duration: number }) {\n const traceId = randomBytes(16).toString('hex')\n const spanId = randomBytes(8).toString('hex')\n const endTimeNs = BigInt(Date.now()) * 1_000_000n\n const startTimeNs = endTimeNs - BigInt(duration) * 1_000_000n\n const pluginNames = [...new Set(plugins.map((plugin) => plugin.name))].sort()\n const agent = getAgentProfile()\n\n const attributes = [\n { key: 'kubb.command', value: { stringValue: command } },\n { key: 'kubb.version', value: { stringValue: version } },\n { key: 'kubb.node_version', value: { stringValue: process.versions.node.split('.')[0] as string } },\n { key: 'kubb.runtime', value: { stringValue: runtime.name } },\n { key: 'kubb.runtime_version', value: { stringValue: runtime.version.split('.')[0] as string } },\n { key: 'kubb.platform', value: { stringValue: os.platform() } },\n { key: 'kubb.ci', value: { boolValue: isCIEnvironment() } },\n // A terminal on stdin means a person typed the command; agents, scripts, and CI pipe it.\n { key: 'kubb.tty', value: { boolValue: process.stdin.isTTY === true } },\n ...(agent.isAgent && agent.name ? [{ key: 'kubb.agent', value: { stringValue: agent.name } }] : []),\n // The client picks this name, so cap its length before it leaves the machine.\n ...(mcpClient ? [{ key: 'kubb.mcp_client', value: { stringValue: mcpClient.slice(0, 64) } }] : []),\n { key: 'kubb.files_created', value: { intValue: filesCreated } },\n { key: 'kubb.status', value: { stringValue: status } },\n {\n key: 'kubb.plugins',\n value: { arrayValue: { values: pluginNames.map((name) => ({ stringValue: name })) } },\n },\n ...pluginNames.map((name) => ({ key: `kubb.plugin.${name}`, value: { boolValue: true } })),\n {\n key: 'kubb.plugin_options',\n value: {\n arrayValue: {\n values: plugins.map((p) => ({\n kvlistValue: {\n values: [\n { key: 'name', value: { stringValue: p.name } },\n {\n key: 'options',\n value: {\n stringValue: JSON.stringify({\n ...p.options,\n usedEnumNames: undefined,\n }),\n },\n },\n ],\n },\n })),\n },\n },\n },\n ]\n\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb' } },\n { key: 'service.version', value: { stringValue: version } },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-core', version },\n spans: [\n {\n traceId,\n spanId,\n name: command,\n kind: 1,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: status === 'success' ? 1 : 2,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an OTLP payload to the Kubb endpoint. Respects `DO_NOT_TRACK` and\n * `KUBB_DISABLE_TELEMETRY`, and fails silently so telemetry never interrupts a run. No file\n * paths, OpenAPI specs, or secrets are sent.\n */\nexport async function sendTelemetry(payload: ReturnType<typeof buildOtlpPayload>): Promise<void> {\n if (isDisabled()) {\n return\n }\n\n try {\n await fetch(`${OTLP_ENDPOINT}/v1/traces`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Kubb-Telemetry-Version': '1',\n 'Kubb-Telemetry-Source': 'kubb-cli',\n },\n body: JSON.stringify(payload),\n // Short, since an unfinished request keeps the process alive after the run.\n signal: AbortSignal.timeout(1_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the run\n }\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAM,gBAAgB;;;;AAgCtB,SAAgB,aAAsB;CACpC,OAAO,CAAC,gBAAgB,wBAAwB,CAAC,CAAC,MAAM,SAAS,CAAC,KAAK,MAAM,CA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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;GAE5B,QAAQ,YAAY,QAAQ,GAAK;EACnC,CAAC;CACH,SAAS,IAAI,CAEb;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
2
|
import { i as getProjectKubbHome } from "./credentials-LPHovWZe.js";
|
|
3
|
-
import { o as prepareConnection } from "./run-
|
|
3
|
+
import { o as prepareConnection } from "./run-DFOjQVMO.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { hash, randomBytes } from "node:crypto";
|
|
6
6
|
import { x } from "tinyexec";
|
|
@@ -271,4 +271,4 @@ async function startWorker(options) {
|
|
|
271
271
|
}
|
|
272
272
|
export { stopWorker as a, startWorker as i, getWorkerStatus as n, serveWorker as r, getWorkerLogPath as t };
|
|
273
273
|
|
|
274
|
-
//# sourceMappingURL=background-
|
|
274
|
+
//# sourceMappingURL=background-CByahHYn.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-CA9lRKAK.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 { Diagnostics } from '@kubb/core'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = {\n id: string\n pid: number\n port: number\n state: WorkerState\n /**\n * When the worker started, in epoch milliseconds. Absent in a record from an older CLI.\n */\n startedAt?: number\n}\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))\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '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; startedAt?: 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, startedAt: Number.isFinite(response.startedAt) ? response.startedAt : undefined }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Cannot verify the background worker. No process was signaled.',\n help: 'Check `worker.log`, then stop the process by hand if it is still running.',\n })\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The worker has not finished shutting down. Check worker.log and try again.',\n })\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', startedAt: Date.now() }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The project control port is occupied or another worker is starting. Try again after stopping that listener.',\n })\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)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Background worker failed to start',\n help: 'Run `kubb studio` in the foreground to see why it fails.',\n })\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":";;;;;;;;;;;;AAqBA,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,MAC3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,MAAM,eAAe,SAAS,MAAM;IACpC,MAAM,eAAe,QAAQ,MAAM;IACnC,MAAM,eAAe,WAAW,KAAK;IACrC,IAAI,OAAO,OAAO,KAAK;SAClB,QAAQ;GACf;GACA,MAAM,UAAU,UAAiB,KAAK,KAAK;GAC3C,MAAM,eAAe,qBAAK,IAAI,MAAM,kDAAkD,iBAAiB,GAAG,CAAC;GAC3G,MAAM,KAAK,SAAS,MAAM;GAC1B,MAAM,KAAK,QAAQ,MAAM;GACzB,MAAM,SAAS,YAAqB;IAClC,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,EAAE,aAAa,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-CByahHYn.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 { Diagnostics } from '@kubb/core'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = {\n id: string\n pid: number\n port: number\n state: WorkerState\n /**\n * When the worker started, in epoch milliseconds. Absent in a record from an older CLI.\n */\n startedAt?: number\n}\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))\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '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; startedAt?: 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, startedAt: Number.isFinite(response.startedAt) ? response.startedAt : undefined }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Cannot verify the background worker. No process was signaled.',\n help: 'Check `worker.log`, then stop the process by hand if it is still running.',\n })\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The worker has not finished shutting down. Check worker.log and try again.',\n })\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', startedAt: Date.now() }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The project control port is occupied or another worker is starting. Try again after stopping that listener.',\n })\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)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Background worker failed to start',\n help: 'Run `kubb studio` in the foreground to see why it fails.',\n })\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":";;;;;;;;;;;;AAqBA,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,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AAe,SAAS,MAAM;IACpC,MAAM,eAAe,QAAQ,MAAM;IACnC,MAAM,eAAe,WAAW,KAAK;IACrC,IAAI,OAAO,OAAO,KAAK;SAClB,QAAQ;GACf;GACA,MAAM,UAAU,UAAiB,KAAK,KAAK;GAC3C,MAAM,eAAe,qBAAK,IAAI,MAAM,kDAAkD,iBAAiB,GAAG,CAAC;GAC3G,MAAM,KAAK,SAAS,MAAM;GAC1B,MAAM,KAAK,QAAQ,MAAM;GACzB,MAAM,SAAS,YAAqB;IAClC,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,EAAE,aAAa,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 +1 @@
|
|
|
1
|
-
export { t as getWorkerLogPath, n as getWorkerStatus, i as startWorker, a as stopWorker } from "./background-
|
|
1
|
+
export { t as getWorkerLogPath, n as getWorkerStatus, i as startWorker, a as stopWorker } from "./background-CByahHYn.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-BV8xUvPy.cjs");
|
|
2
2
|
const require_credentials = require("./credentials-Cl3eOa8G.cjs");
|
|
3
|
-
const require_run = require("./run-
|
|
3
|
+
const require_run = require("./run-6qjg9Twy.cjs");
|
|
4
4
|
require("node:crypto");
|
|
5
5
|
let tinyexec = require("tinyexec");
|
|
6
6
|
let node_fs_promises = require("node:fs/promises");
|
|
@@ -189,4 +189,4 @@ exports.getWorkerStatus = getWorkerStatus;
|
|
|
189
189
|
exports.startWorker = startWorker;
|
|
190
190
|
exports.stopWorker = stopWorker;
|
|
191
191
|
|
|
192
|
-
//# sourceMappingURL=background-
|
|
192
|
+
//# sourceMappingURL=background-D6dQxXt6.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-fhpYDuSs.cjs","names":["path","getProjectKubbHome","readFile","connectSocket","Diagnostics","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 { Diagnostics } from '@kubb/core'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = {\n id: string\n pid: number\n port: number\n state: WorkerState\n /**\n * When the worker started, in epoch milliseconds. Absent in a record from an older CLI.\n */\n startedAt?: number\n}\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))\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '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; startedAt?: 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, startedAt: Number.isFinite(response.startedAt) ? response.startedAt : undefined }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Cannot verify the background worker. No process was signaled.',\n help: 'Check `worker.log`, then stop the process by hand if it is still running.',\n })\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The worker has not finished shutting down. Check worker.log and try again.',\n })\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', startedAt: Date.now() }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The project control port is occupied or another worker is starting. Try again after stopping that listener.',\n })\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)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Background worker failed to start',\n help: 'Run `kubb studio` in the foreground to see why it fails.',\n })\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":";;;;;;;;;;;;;AAqBA,MAAM,SAA6B;CAAC;CAAY;CAAa;CAAgB;CAA2B;AAAS;AACjH,MAAa,yBAAyBA,UAAAA,QAAK,KAAKC,oBAAAA,mBAAmB,GAAG,YAAY;AAClF,MAAM,kBAAkBD,UAAAA,QAAK,KAAKC,oBAAAA,mBAAmB,GAAG,aAAa;AAErE,eAAe,aAA2C;CACxD,IAAI;EACF,MAAM,QAAiB,KAAK,MAAM,OAAA,GAAMC,iBAAAA,SAAAA,CAAS,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,UAAA,GAASC,SAAAA,QAAAA,CAAc;GAAE,MAAM;GAAa,MAAM,OAAO;EAAK,CAAC;EACrE,IAAI,WAAW;EACf,OAAO,WAAW,WAAa,OAAO,wBA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AAS;EACT,MAAM;CACR,CAAC;CACH,IAAI;EAyBF,MAAM,IAxBc,SAAe,SAAS,WAAW;GACrD,MAAM,QAAQ,iBAAiB,qBAAK,IAAI,MAAM,qCAAqC,CAAC,GAAG,GAAM;GAC7F,MAAM,QAAQ,UAAkB;IAC9B,aAAa,KAAK;IAClB,MAAM,eAAe,SAAS,MAAM;IACpC,MAAM,eAAe,QAAQ,MAAM;IACnC,MAAM,eAAe,WAAW,KAAK;IACrC,IAAI,OAAO,OAAO,KAAK;SAClB,QAAQ;GACf;GACA,MAAM,UAAU,UAAiB,KAAK,KAAK;GAC3C,MAAM,eAAe,qBAAK,IAAI,MAAM,kDAAkD,iBAAiB,GAAG,CAAC;GAC3G,MAAM,KAAK,SAAS,MAAM;GAC1B,MAAM,KAAK,QAAQ,MAAM;GACzB,MAAM,SAAS,YAAqB;IAClC,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,EAAE,aAAa,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-D6dQxXt6.cjs","names":["path","getProjectKubbHome","readFile","connectSocket","Diagnostics","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 { Diagnostics } from '@kubb/core'\nimport { x } from 'tinyexec'\nimport { getProjectKubbHome } from './credentials.ts'\nimport { prepareConnection, type PreparedConnection, type StudioOptions, type WorkerState } from './run.ts'\n\nexport type WorkerRecord = {\n id: string\n pid: number\n port: number\n state: WorkerState\n /**\n * When the worker started, in epoch milliseconds. Absent in a record from an older CLI.\n */\n startedAt?: number\n}\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))\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '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; startedAt?: 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, startedAt: Number.isFinite(response.startedAt) ? response.startedAt : undefined }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Cannot verify the background worker. No process was signaled.',\n help: 'Check `worker.log`, then stop the process by hand if it is still running.',\n })\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The worker has not finished shutting down. Check worker.log and try again.',\n })\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', startedAt: Date.now() }\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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'The project control port is occupied or another worker is starting. Try again after stopping that listener.',\n })\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)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Background worker failed to start',\n help: 'Run `kubb studio` in the foreground to see why it fails.',\n })\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":";;;;;;;;;;;;;AAqBA,MAAM,SAA6B;CAAC;CAAY;CAAa;CAAgB;CAA2B;AAAS;AACjH,MAAa,yBAAyBA,UAAAA,QAAK,KAAKC,oBAAAA,mBAAmB,GAAG,YAAY;AAClF,MAAM,kBAAkBD,UAAAA,QAAK,KAAKC,oBAAAA,mBAAmB,GAAG,aAAa;AAErE,eAAe,aAA2C;CACxD,IAAI;EACF,MA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AM;GAC1B,MAAM,KAAK,QAAQ,MAAM;GACzB,MAAM,SAAS,YAAqB;IAClC,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,EAAE,aAAa,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,7 +1,7 @@
|
|
|
1
1
|
require("./rolldown-runtime-BV8xUvPy.cjs");
|
|
2
2
|
const require_errors = require("./errors-Bewwe8mY.cjs");
|
|
3
|
-
const require_spinner = require("./spinner-
|
|
4
|
-
const require_utils = require("./utils-
|
|
3
|
+
const require_spinner = require("./spinner-BQgUoe7F.cjs");
|
|
4
|
+
const require_utils = require("./utils-_hY0r-7x.cjs");
|
|
5
5
|
let _kubb_core = require("@kubb/core");
|
|
6
6
|
let yuku_parser = require("yuku-parser");
|
|
7
7
|
// ../../internals/shared/src/configFile/ast.ts
|
|
@@ -749,14 +749,14 @@ function addPlugin({ source, parsed, config, edit, quote, extensions }) {
|
|
|
749
749
|
if (array ? array.type !== nodeTypes.arrayExpression : !isParser) return { reason: `${key} is not an array literal` };
|
|
750
750
|
const defaults = isParser && !array ? DEFAULT_PARSERS.filter((parser) => parser.importName !== importName) : [];
|
|
751
751
|
const imports = getImports(parsed.program);
|
|
752
|
-
const missing =
|
|
752
|
+
const missing = require_spinner.memo.create();
|
|
753
753
|
for (const item of [...defaults, {
|
|
754
754
|
importName,
|
|
755
755
|
packageName: edit.plugin
|
|
756
756
|
}]) {
|
|
757
757
|
const from = imports.get(item.importName)?.from;
|
|
758
758
|
if (from && from !== item.packageName) return { reason: `${item.importName} is already imported from ${from}` };
|
|
759
|
-
if (!from)
|
|
759
|
+
if (!from) require_spinner.memo(missing, item.packageName, () => []).push(item.importName);
|
|
760
760
|
}
|
|
761
761
|
const call = `${importName}(${Object.keys(options).length ? printValue(options, quote) : ""})`;
|
|
762
762
|
const next = array?.type === nodeTypes.arrayExpression ? appendItem(source, array, call) : appendItem(source, config, `parsers: [${[...defaults.map((parser) => `${parser.importName}()`), call].join(", ")}]`);
|
|
@@ -989,4 +989,4 @@ Object.defineProperty(exports, "readImports", {
|
|
|
989
989
|
}
|
|
990
990
|
});
|
|
991
991
|
|
|
992
|
-
//# sourceMappingURL=configFile-
|
|
992
|
+
//# sourceMappingURL=configFile-B_xrd2yx.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configFile-B_xrd2yx.cjs","names":["parse","getErrorMessage","camelCase","isPackageName","memo","getErrorMessage","read","writeRaw"],"sources":["../../../internals/shared/src/configFile/ast.ts","../../../internals/shared/src/configFile/types.ts","../../../internals/shared/src/configFile/rules.ts","../../../internals/shared/src/configFile/text.ts","../../../internals/shared/src/configFile/configFile.ts"],"sourcesContent":["import { getErrorMessage } from '@internals/utils'\nimport { type Comment, type Expression, type Program, parse } from 'yuku-parser'\n\nexport type {\n ArrayExpression,\n AssignmentExpression,\n BindingProperty,\n CallExpression,\n Comment,\n Expression,\n ImportDeclaration,\n ObjectExpression,\n ObjectPropertyKind,\n Program,\n RestElement,\n SpreadElement,\n VariableDeclaration,\n} from 'yuku-parser'\n\n/** Node types the config editor reads from the yuku AST. */\nexport const nodeTypes = {\n arrayExpression: 'ArrayExpression',\n arrowFunctionExpression: 'ArrowFunctionExpression',\n assignmentExpression: 'AssignmentExpression',\n blockStatement: 'BlockStatement',\n callExpression: 'CallExpression',\n exportDefaultDeclaration: 'ExportDefaultDeclaration',\n expressionStatement: 'ExpressionStatement',\n functionExpression: 'FunctionExpression',\n identifier: 'Identifier',\n importDeclaration: 'ImportDeclaration',\n importSpecifier: 'ImportSpecifier',\n literal: 'Literal',\n memberExpression: 'MemberExpression',\n objectExpression: 'ObjectExpression',\n objectPattern: 'ObjectPattern',\n property: 'Property',\n returnStatement: 'ReturnStatement',\n spreadElement: 'SpreadElement',\n tSAsExpression: 'TSAsExpression',\n tSSatisfiesExpression: 'TSSatisfiesExpression',\n templateLiteral: 'TemplateLiteral',\n unaryExpression: 'UnaryExpression',\n variableDeclaration: 'VariableDeclaration',\n} as const\n\nexport const commentTypes = { line: 'Line' } as const\nexport const propertyKinds = { init: 'init' } as const\nexport const unaryOperators = { minus: '-', plus: '+' } as const\nconst diagnosticSeverities = { error: 'error' } as const\n\n/** A parsed file: its statements and every comment in it, or why it could not be parsed. */\ntype ParsedSource = { program: Program; comments: Array<Comment> } | { reason: string }\n\n/**\n * Parses `source` as a TypeScript module. Never throws: a syntax error, or a native parser that\n * cannot load on this platform, comes back as a `reason`.\n */\nexport function parseSource(source: string): ParsedSource {\n try {\n // Parentheses are dropped, so `export default (defineConfig({}))` reads as the call itself.\n const { program, comments, diagnostics } = parse(source, { lang: 'ts', sourceType: 'module', preserveParens: false })\n if (diagnostics.some((diagnostic) => diagnostic.severity === diagnosticSeverities.error)) return { reason: 'the config file could not be parsed' }\n return { program, comments }\n } catch (error) {\n return { reason: `the config parser could not load on this platform: ${getErrorMessage(error)}` }\n }\n}\n\n/** Parses `source` as one expression, such as a commented-out `pluginTs({ ... })` call. */\nexport function parseExpression(source: string): Expression | undefined {\n const parsed = parseSource(source)\n if ('reason' in parsed) return undefined\n const [statement] = parsed.program.body\n return parsed.program.body.length === 1 && statement?.type === nodeTypes.expressionStatement ? statement.expression : undefined\n}\n","import type { ValueOf } from '@internals/utils'\nimport type { ExtensionKind, ExtensionManifest } from '@kubb/core'\n\n/** Which `defineConfig(...)` entry an edit targets: its index or `name`, the first entry when omitted. */\nexport type ConfigRef = string | number\n\n/** A literal option value that survives a JSON round trip. */\nexport type OptionValue = string | number | boolean | null | Array<OptionValue> | { [key: string]: OptionValue }\n\nexport const extensionKinds = { plugin: 'plugin', adapter: 'adapter', parser: 'parser' } as const satisfies Record<string, ExtensionKind>\n\nexport const ConfigEditOperation = {\n SET_OPTION: 'set-option',\n REMOVE_OPTION: 'remove-option',\n ADD_PLUGIN: 'add-plugin',\n REMOVE_EXTENSION: 'remove-extension',\n DISABLE_PLUGIN: 'disable-plugin',\n ENABLE_PLUGIN: 'enable-plugin',\n SET_INPUT: 'set-input',\n SET_OUTPUT: 'set-output',\n REMOVE_OUTPUT: 'remove-output',\n} as const\nexport type ConfigEditOperation = ValueOf<typeof ConfigEditOperation>\n\n/**\n * One change to `kubb.config.ts`. `plugin` is the package name, and `kind` picks the `plugins` entry\n * (default), the `adapter`, or a `parsers` entry. `path` walks nested option objects.\n */\nexport type ConfigEdit =\n | { operation: typeof ConfigEditOperation.SET_OPTION; config?: ConfigRef; kind?: ExtensionKind; plugin: string; path: Array<string>; value: unknown }\n | { operation: typeof ConfigEditOperation.REMOVE_OPTION; config?: ConfigRef; kind?: ExtensionKind; plugin: string; path: Array<string> }\n /** With `kind: 'parser'`, adds to `parsers`. A config without `parsers` gets the defaults written next to it, so they keep running. */\n | {\n operation: typeof ConfigEditOperation.ADD_PLUGIN\n config?: ConfigRef\n kind?: typeof extensionKinds.plugin | typeof extensionKinds.parser\n plugin: string\n options?: Record<string, unknown>\n }\n /** Deletes every call of a plugin, or a parser with `kind: 'parser'`, a disabled block included, and the imports nothing else uses. */\n | {\n operation: typeof ConfigEditOperation.REMOVE_EXTENSION\n config?: ConfigRef\n kind?: typeof extensionKinds.plugin | typeof extensionKinds.parser\n plugin: string\n }\n | { operation: typeof ConfigEditOperation.DISABLE_PLUGIN; config?: ConfigRef; plugin: string }\n | { operation: typeof ConfigEditOperation.ENABLE_PLUGIN; config?: ConfigRef; plugin: string }\n | { operation: typeof ConfigEditOperation.SET_INPUT; config?: ConfigRef; input: string }\n | { operation: typeof ConfigEditOperation.SET_OUTPUT; config?: ConfigRef; path: Array<string>; value: unknown }\n | { operation: typeof ConfigEditOperation.REMOVE_OUTPUT; config?: ConfigRef; path: Array<string> }\n\n/** Option keys, each with whether Studio may write it. `locked` lists the code paths inside a partly literal object. */\nexport type OptionsView = Record<string, { literal: boolean; value?: OptionValue; locked?: Array<Array<string>> }>\n\n/** A factory call in `plugins`, `adapter`, or `parsers`. `importName` is the local name, alias included. */\nexport type PluginView = {\n importName: string\n packageName: string\n options: OptionsView\n /** The call is commented out by `disable-plugin`. */\n disabled?: true\n}\n\nexport type ConfigView = {\n name?: string\n plugins: Array<PluginView>\n adapter?: PluginView\n parsers?: Array<PluginView>\n /** The root `output` members Studio may set, absent when `output` is not an object literal. */\n output?: OptionsView\n}\n\n/** The config file as Studio may edit it, or why it cannot. */\nexport type ConfigFileView = { managed: true; configs: Array<ConfigView> } | { managed: false; reason: string }\n\nexport type ConfigEditOutcome = {\n edit: ConfigEdit\n applied: boolean\n reason?: string\n}\n\nexport type ExtensionEntry = {\n package: string\n version: string\n manifest: ExtensionManifest\n /** Ships with `kubb` at its version, so updating `kubb` updates it and `kubb update` cannot. */\n bundled?: true\n}\n\n/** Installed extensions by package name, the only ones Studio may import besides `@kubb/plugin-*`. */\nexport type InstalledExtensions = ReadonlyMap<string, ExtensionEntry>\n","import { type ExtensionKind, isPackageName } from '@kubb/core'\nimport { camelCase } from '@internals/utils'\nimport { extensionKinds, type InstalledExtensions, type OptionValue } from './types.ts'\n\n/** `@kubb/plugin-ts` becomes `plugin-ts`, the `name` Kubb plugin factories use. */\nexport function toPluginName(packageName: string): string {\n return packageName.split('/').pop() ?? packageName\n}\n\n/** `@kubb/plugin-react-query` becomes `pluginReactQuery`, the export a plugin package uses by convention. */\nexport function toExportName(packageName: string): string {\n return camelCase(toPluginName(packageName))\n}\n\nconst KUBB_PLUGIN_SPECIFIER = /^@kubb\\/plugin-[\\w.-]+$/\n\n/** Only a `@kubb/plugin-*` package or an installed extension of `kind` may be imported, never a path or URL. */\nexport function isAllowedPlugin({\n packageName,\n extensions,\n kind = extensionKinds.plugin,\n}: {\n packageName: string\n extensions: InstalledExtensions\n kind?: ExtensionKind\n}): boolean {\n if (!isPackageName(packageName)) return false\n return (kind === extensionKinds.plugin && KUBB_PLUGIN_SPECIFIER.test(packageName)) || extensions.get(packageName)?.manifest.kind === kind\n}\n\nconst UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\n/** Whether `key` can be an option key without reaching the object's prototype. */\nexport function isSafeKey(key: string): boolean {\n return !UNSAFE_KEYS.has(key)\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === null || prototype === Object.prototype\n}\n\n/** Whether `value` survives a JSON round trip, so an edit never writes a lossy copy into the file. */\nexport function isOptionValue(value: unknown): value is OptionValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true\n if (typeof value === 'number') return Number.isFinite(value)\n if (Array.isArray(value)) return value.every(isOptionValue)\n if (isPlainObject(value)) return Object.entries(value).every(([key, entry]) => isSafeKey(key) && isOptionValue(entry))\n\n return false\n}\n\n/** The root `output` members Studio may set, with the values each takes. */\nconst OUTPUT_VALUES: Record<string, (value: unknown) => boolean> = {\n barrel: (value) => value === false || (isPlainObject(value) && Object.keys(value).length === 1 && (value.type === 'named' || value.type === 'all')),\n format: (value) => value === false || ['auto', 'prettier', 'biome', 'oxfmt'].includes(value as string),\n lint: (value) => value === false || ['auto', 'eslint', 'biome', 'oxlint'].includes(value as string),\n clean: (value) => typeof value === 'boolean',\n defaultBanner: (value) => value === false || value === 'simple' || value === 'full',\n}\n\nexport function isOutputKey(key: string): boolean {\n return Object.hasOwn(OUTPUT_VALUES, key)\n}\n\nexport function isOutputValue({ key, value }: { key: string; value: unknown }): boolean {\n return isOutputKey(key) && OUTPUT_VALUES[key]!(value)\n}\n\nexport function pickOutput<T>(output: Record<string, T>): Record<string, T> {\n return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)))\n}\n","import type { ValueOf } from '@internals/utils'\nimport { type ArrayExpression, nodeTypes, type ObjectExpression } from './ast.ts'\nimport type { OptionValue } from './types.ts'\n\n/**\n * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,\n * never as source that breaks out of the import statement.\n */\nexport const IDENTIFIER_PATTERN = /^[A-Za-z_$][\\w$]*$/\n\nexport const quotes = { single: `'`, double: `\"` } as const\nexport type Quote = ValueOf<typeof quotes>\n\n/** `source` with the text between `start` and `end` replaced by `text`. */\nexport function replaceText(source: string, start: number, end: number, text = ''): string {\n return `${source.slice(0, start)}${text}${source.slice(end)}`\n}\n\n/** The 1-based line and 0-based column of `offset` in `source`. */\nexport function getPosition(source: string, offset: number): { line: number; column: number } {\n return { line: source.slice(0, offset).split('\\n').length, column: offset - source.lastIndexOf('\\n', offset - 1) - 1 }\n}\n\n/** Writes `value` as a single-line literal with the file's quote style. */\nexport function printValue(value: OptionValue, quote: Quote): string {\n if (typeof value === 'string') {\n // JSON's escaping covers every character that could end the literal or the line.\n const escaped = JSON.stringify(value).slice(1, -1)\n return quote === quotes.double ? `\"${escaped}\"` : `'${escaped.replaceAll(`\\\\\"`, `\"`).replaceAll(`'`, `\\\\'`)}'`\n }\n if (value === null || typeof value !== 'object') return String(value)\n if (Array.isArray(value)) return `[${value.map((item) => printValue(item, quote)).join(', ')}]`\n\n const entries = Object.entries(value)\n return entries.length ? `{ ${entries.map(([key, item]) => `${printKey(key, quote)}: ${printValue(item, quote)}`).join(', ')} }` : '{}'\n}\n\n/** An object key as source text: bare when it is an identifier, quoted otherwise. */\nexport function printKey(key: string, quote: Quote): string {\n return IDENTIFIER_PATTERN.test(key) ? key : printValue(key, quote)\n}\n\n/** `value` wrapped in one object per key of `path`: `wrapPath(['enum', 'type'], 'enum')` is `{ enum: { type: 'enum' } }`. */\nexport function wrapPath(path: Array<string>, value: OptionValue): OptionValue {\n return path.reduceRight<OptionValue>((inner, key) => ({ [key]: inner }), value)\n}\n\n/**\n * Adds `text` as the last item of an object or array literal, following its layout: on a line of\n * its own with the last item's indentation when the literal spans lines, inline otherwise.\n */\nexport function appendItem(source: string, container: ObjectExpression | ArrayExpression, text: string): string {\n const { start, end } = container\n const items: Array<{ start: number; end: number } | null> = container.type === nodeTypes.objectExpression ? container.properties : container.elements\n const last = items.filter((item) => item !== null).at(-1)\n\n if (!last) {\n const inner = source.slice(start + 1, end - 1)\n // A comment inside the empty literal stays, after the new item.\n if (inner.trim()) return replaceText(source, start + 1, start + 1, /^\\s/.test(inner) ? `${text},` : `${text}, `)\n return replaceText(source, start, end, container.type === nodeTypes.objectExpression ? `{ ${text} }` : `[${text}]`)\n }\n\n const between = source.slice(last.end, end - 1)\n // The closing bracket shares the last item's line: add the item inline.\n if (!between.includes('\\n')) return replaceText(source, last.end, last.end, `, ${text}`)\n\n const lineStart = source.lastIndexOf('\\n', last.start - 1) + 1\n const indent = source.slice(lineStart).match(/^[ \\t]*/)?.[0] ?? ''\n // After the last item's comma and any comment on its line, so neither moves. `between` holds a\n // newline, so one always follows.\n const lineEnd = source.indexOf('\\n', last.end)\n const comma = /^\\s*,/.test(between)\n\n return `${source.slice(0, last.end)}${comma ? '' : ','}${source.slice(last.end, lineEnd)}\\n${indent}${text}${comma ? ',' : ''}${source.slice(lineEnd)}`\n}\n\n/** Drops the item at `index` from an object or array literal, with its own lines when it sits on them alone. */\nexport function removeItem(source: string, node: ObjectExpression | ArrayExpression, index: number): string {\n const items: Array<{ start: number; end: number }> =\n node.type === nodeTypes.objectExpression ? node.properties : node.elements.filter((element) => element !== null)\n if (items.length === 1) return replaceText(source, node.start, node.end, node.type === nodeTypes.objectExpression ? '{}' : '[]')\n\n const { start, end } = items[index]!\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1\n const nextNewline = source.indexOf('\\n', end)\n const lineEnd = nextNewline === -1 ? source.length : nextNewline\n if (!source.slice(lineStart, start).trim() && /^\\s*,?\\s*(\\/\\/.*)?$/.test(source.slice(end, lineEnd))) {\n return replaceText(source, lineStart, Math.min(lineEnd + 1, source.length))\n }\n\n const next = items[index + 1]\n return next ? replaceText(source, start, next.start) : replaceText(source, items[index - 1]!.end, end)\n}\n","import type { ExtensionKind } from '@kubb/core'\nimport { getErrorMessage, memo, read, writeRaw } from '@internals/utils'\nimport type { ValueOf } from '@internals/utils'\nimport {\n type AssignmentExpression,\n type BindingProperty,\n type CallExpression,\n type Comment,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectPropertyKind,\n type Program,\n type RestElement,\n type SpreadElement,\n type VariableDeclaration,\n commentTypes,\n nodeTypes,\n parseExpression,\n parseSource,\n propertyKinds,\n unaryOperators,\n} from './ast.ts'\nimport { isAllowedPlugin, isOptionValue, isOutputKey, isOutputValue, isSafeKey, pickOutput, toExportName } from './rules.ts'\nimport { appendItem, getPosition, IDENTIFIER_PATTERN, printKey, printValue, quotes, type Quote, removeItem, replaceText, wrapPath } from './text.ts'\nimport {\n type ConfigEdit,\n ConfigEditOperation,\n type ConfigEditOutcome,\n type ConfigFileView,\n type ConfigRef,\n type ConfigView,\n extensionKinds,\n type InstalledExtensions,\n type OptionsView,\n type OptionValue,\n type PluginView,\n} from './types.ts'\n\n/** The marker `disable-plugin` writes, with the block's line count so `enable-plugin` restores exactly those lines. */\nconst DISABLED_MARKER_PATTERN = /^kubb:disabled (.+)\\s+(\\d+)$/\n\nconst OPERATIONS = new Set<string>(Object.values(ConfigEditOperation))\nconst OPTION_OPERATIONS = new Set<string>([ConfigEditOperation.SET_OPTION, ConfigEditOperation.REMOVE_OPTION])\nconst OUTPUT_OPERATIONS = new Set<string>([ConfigEditOperation.SET_OUTPUT, ConfigEditOperation.REMOVE_OUTPUT])\nconst KINDS = new Set<string>(Object.values(extensionKinds))\n\n/** Identifiers the editor matches by name. */\nconst identifiers = { defineConfig: 'defineConfig', require: 'require', module: 'module', exports: 'exports' } as const\n\nconst moduleKinds = { esm: 'esm', cjs: 'cjs' } as const\ntype ModuleKind = ValueOf<typeof moduleKinds>\n\ntype EditResult = { source: string } | { reason: string }\ntype ParsedConfig = { program: Program; comments: Array<Comment>; configs: Array<ObjectExpression>; kind: ModuleKind }\ntype ValueNode = Expression | SpreadElement | null | undefined\ntype Import = { from: string; exported: string }\ntype FactoryCall = { importName: string; exportName: string; packageName: string; call: CallExpression }\ntype DisabledBlock = { packageName: string; line: number; end: number; code: Array<string> }\ntype OutputEdit = Extract<ConfigEdit, { operation: typeof ConfigEditOperation.SET_OUTPUT | typeof ConfigEditOperation.REMOVE_OUTPUT }>\ntype OptionEdit = Extract<ConfigEdit, { operation: typeof ConfigEditOperation.SET_OPTION | typeof ConfigEditOperation.REMOVE_OPTION }>\ntype AddPluginEdit = Extract<ConfigEdit, { operation: typeof ConfigEditOperation.ADD_PLUGIN }>\ntype DisablePluginEdit = Extract<ConfigEdit, { operation: typeof ConfigEditOperation.DISABLE_PLUGIN }>\ntype RemoveExtensionEdit = Extract<ConfigEdit, { operation: typeof ConfigEditOperation.REMOVE_EXTENSION }>\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value !== ''\n}\n\n/** Edits cross the wire, so their shape is checked before anything reads them. */\nfunction validateEdit(edit: ConfigEdit): string | undefined {\n const { operation, plugin, config, path, kind, input } = (typeof edit === 'object' && edit !== null ? edit : {}) as Record<string, unknown>\n\n if (typeof operation !== 'string' || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`\n if (config !== undefined && typeof config !== 'string' && !Number.isSafeInteger(config)) return 'config must name an entry or give its index'\n\n if (operation === ConfigEditOperation.SET_INPUT) {\n return typeof input === 'string' && input.trim() !== '' ? undefined : 'the edit names no input'\n }\n\n const isOption = OPTION_OPERATIONS.has(operation)\n const isOutput = OUTPUT_OPERATIONS.has(operation)\n\n if (!isOutput && !isNonEmptyString(plugin)) return 'the edit names no plugin'\n\n if (kind !== undefined) {\n if (typeof kind !== 'string' || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`\n const takesKind = operation === ConfigEditOperation.ADD_PLUGIN || operation === ConfigEditOperation.REMOVE_EXTENSION\n if (takesKind && kind === extensionKinds.adapter) return `${operation} takes a plugin or a parser, since a config has one adapter`\n if (!isOption && !takesKind) return `${operation} edits the plugins array, so it takes no kind`\n }\n\n if (!isOption && !isOutput) return undefined\n\n if (!Array.isArray(path) || !path.every(isNonEmptyString)) return 'path must be a list of option names'\n if (path.length === 0) return 'no option path given'\n\n const unsafe = path.find((key) => !isSafeKey(key))\n if (unsafe !== undefined) return `${unsafe} cannot be used as an option name`\n\n if (isOutput && !isOutputKey(path[0]!)) return `output.${path[0]} can only be changed in the config file`\n\n return undefined\n}\n\n// Finding the config\n\n/** Steps through `as`/`satisfies` and `() => ...` wrappers to the config object. */\nfunction unwrapValue(node: ValueNode): ValueNode {\n if (!node) return undefined\n if (node.type === nodeTypes.tSAsExpression || node.type === nodeTypes.tSSatisfiesExpression) return unwrapValue(node.expression)\n if (node.type !== nodeTypes.arrowFunctionExpression && node.type !== nodeTypes.functionExpression) return node\n if (node.body?.type !== nodeTypes.blockStatement) return unwrapValue(node.body as Expression | null)\n\n const returned = node.body.body.find((statement) => statement.type === nodeTypes.returnStatement)\n return unwrapValue(returned?.type === nodeTypes.returnStatement ? returned.argument : undefined)\n}\n\nfunction isModuleExports(node: AssignmentExpression['left']): boolean {\n return (\n node.type === nodeTypes.memberExpression &&\n !node.computed &&\n node.object.type === nodeTypes.identifier &&\n node.object.name === identifiers.module &&\n node.property.type === nodeTypes.identifier &&\n node.property.name === identifiers.exports\n )\n}\n\n/** The exported config value and how the file exports it. */\nfunction findExport(program: Program): { exported: ValueNode; kind: ModuleKind } {\n for (const node of program.body) {\n if (node.type === nodeTypes.exportDefaultDeclaration) {\n // A `function` or `class` declaration is never a `defineConfig(...)` call, so `findConfigs` refuses it.\n return { exported: node.declaration as Expression, kind: moduleKinds.esm }\n }\n if (node.type === nodeTypes.expressionStatement && node.expression.type === nodeTypes.assignmentExpression && isModuleExports(node.expression.left)) {\n return { exported: node.expression.right, kind: moduleKinds.cjs }\n }\n }\n return { exported: undefined, kind: moduleKinds.esm }\n}\n\n/** Every config object in `export default` or `module.exports = defineConfig(...)`, or why the file is unmanaged. */\nfunction findConfigs(source: string): ParsedConfig | { reason: string } {\n const parsed = parseSource(source)\n if ('reason' in parsed) return parsed\n\n const { exported, kind } = findExport(parsed.program)\n const value = unwrapValue(exported)\n if (!value) return { reason: 'no `export default` or `module.exports` found' }\n if (value.type !== nodeTypes.callExpression || value.callee.type !== nodeTypes.identifier || value.callee.name !== identifiers.defineConfig) {\n return { reason: 'the exported config is not a defineConfig(...) call' }\n }\n\n const argument = unwrapValue(value.arguments[0])\n if (!argument) return { reason: 'defineConfig(...) was called without a config' }\n\n const entries = argument.type === nodeTypes.arrayExpression ? argument.elements.map((element) => unwrapValue(element)) : [argument]\n const configs = entries.filter((entry): entry is ObjectExpression => entry?.type === nodeTypes.objectExpression)\n if (configs.length !== entries.length) return { reason: 'config is not an object literal' }\n\n return { ...parsed, configs, kind }\n}\n\nfunction findConfigEntry(configs: Array<ObjectExpression>, ref: ConfigRef | undefined): ObjectExpression | undefined {\n return typeof ref === 'string' ? configs.find((entry) => getConfigName(entry) === ref) : configs[ref ?? 0]\n}\n\n// Reading object literals\n\nfunction getKey(entry: ObjectPropertyKind | BindingProperty | RestElement): string | undefined {\n if (entry.type !== nodeTypes.property || entry.computed) return undefined\n if (entry.key.type === nodeTypes.identifier) return entry.key.name\n return entry.key.type === nodeTypes.literal && typeof entry.key.value === 'string' ? entry.key.value : undefined\n}\n\n/** The last one wins when the key repeats, as at runtime. */\nfunction findProperty(node: ObjectExpression, key: string): { member: ObjectPropertyKind; index: number } | undefined {\n const index = node.properties.findLastIndex((entry) => getKey(entry) === key)\n return index === -1 ? undefined : { member: node.properties[index]!, index }\n}\n\nfunction getValue(node: ObjectExpression, key: string): ValueNode {\n const member = findProperty(node, key)?.member\n return member?.type === nodeTypes.property ? member.value : member\n}\n\nfunction getConfigName(config: ObjectExpression): string | undefined {\n const name = getValue(config, 'name')\n return name?.type === nodeTypes.literal && typeof name.value === 'string' ? name.value : undefined\n}\n\nfunction isOverridden(node: ObjectExpression, index: number): boolean {\n return node.properties.slice(index + 1).some((entry) => entry.type === nodeTypes.spreadElement)\n}\n\n/** `key: value`, not a method, getter, setter, or `{ key }` shorthand. */\nfunction isPlainProperty(member: Extract<ObjectPropertyKind, { type: typeof nodeTypes.property }>): boolean {\n return !member.method && !member.shorthand && member.kind === propertyKinds.init\n}\n\n/** A literal's value, `undefined` for code. */\nfunction readLiteral(node: ValueNode): OptionValue | undefined {\n switch (node?.type) {\n case nodeTypes.literal:\n // A bigint or a regex is code, not a value JSON can carry. A regex Node cannot compile also has a `null` value.\n return 'regex' in node || 'bigint' in node ? undefined : (node.value as OptionValue)\n case nodeTypes.templateLiteral:\n return node.expressions.length ? undefined : (node.quasis[0]?.value.cooked ?? '')\n case nodeTypes.unaryExpression: {\n const value = readLiteral(node.argument)\n if (typeof value !== 'number') return undefined\n if (node.operator === unaryOperators.minus) return -value\n if (node.operator === unaryOperators.plus) return value\n return undefined\n }\n case nodeTypes.arrayExpression: {\n const values = node.elements.map((element) => readLiteral(element))\n return values.every((value) => value !== undefined) ? values : undefined\n }\n case nodeTypes.objectExpression: {\n const entries: Record<string, OptionValue> = {}\n for (const entry of node.properties) {\n if (entry.type !== nodeTypes.property) return undefined\n const key = getKey(entry)\n const value = readLiteral(entry.value)\n // A `__proto__` key would replace the object's prototype instead of adding an entry.\n if (key === undefined || !isSafeKey(key) || value === undefined) return undefined\n entries[key] = value\n }\n return entries\n }\n }\n return undefined\n}\n\n// Imports and factory calls\n\nfunction getRequirePath(node: ValueNode): string | undefined {\n if (node?.type !== nodeTypes.callExpression || node.callee.type !== nodeTypes.identifier || node.callee.name !== identifiers.require) return undefined\n const [argument] = node.arguments\n return argument?.type === nodeTypes.literal && typeof argument.value === 'string' ? argument.value : undefined\n}\n\n/** `import { exported as local } from '...'`. A default or namespace import has no exported name, so its local name stands in. */\nfunction importBindings(statement: ImportDeclaration): Array<[string, Import]> {\n return statement.specifiers.map((specifier) => {\n const imported = specifier.type === nodeTypes.importSpecifier ? specifier.imported : specifier.local\n const exported = imported.type === nodeTypes.identifier ? imported.name : imported.value\n return [specifier.local.name, { from: statement.source.value, exported }]\n })\n}\n\n/** `const { exported: local } = require('...')`. */\nfunction requireBindings(statement: VariableDeclaration): Array<[string, Import]> {\n return statement.declarations.flatMap((declarator): Array<[string, Import]> => {\n const from = getRequirePath(declarator.init)\n if (from === undefined || declarator.id.type !== nodeTypes.objectPattern) return []\n\n return declarator.id.properties.flatMap((entry): Array<[string, Import]> => {\n if (entry.type !== nodeTypes.property || entry.value.type !== nodeTypes.identifier) return []\n return [[entry.value.name, { from, exported: getKey(entry) ?? entry.value.name }]]\n })\n })\n}\n\nfunction getImports(program: Program): Map<string, Import> {\n return new Map(\n program.body.flatMap((statement) => {\n if (statement.type === nodeTypes.importDeclaration) return importBindings(statement)\n if (statement.type === nodeTypes.variableDeclaration) return requireBindings(statement)\n return []\n }),\n )\n}\n\nfunction isImportStatement(node: Program['body'][number], kind: ModuleKind): boolean {\n if (kind === moduleKinds.esm) return node.type === nodeTypes.importDeclaration\n return node.type === nodeTypes.variableDeclaration && node.declarations.some((declarator) => getRequirePath(declarator.init) !== undefined)\n}\n\n/** The quote of the first string literal in the file, so new code matches it. */\nfunction detectQuote(node: unknown): Quote | undefined {\n if (!node || typeof node !== 'object') return undefined\n const { type, raw } = node as { type?: string; raw?: unknown }\n if (type === nodeTypes.literal && typeof raw === 'string' && (raw[0] === quotes.single || raw[0] === quotes.double)) return raw[0]\n for (const child of Object.values(node)) {\n const quote = detectQuote(child)\n if (quote) return quote\n }\n return undefined\n}\n\n/** The `adapter` value, or the elements of the `plugins` or `parsers` array. */\nfunction factoryNodes(config: ObjectExpression, kind: ExtensionKind): Array<ValueNode> {\n if (kind === extensionKinds.adapter) return [getValue(config, 'adapter')]\n const array = getValue(config, `${kind}s`)\n return array?.type === nodeTypes.arrayExpression ? array.elements : []\n}\n\n/** The factory calls of one kind whose callee the file imports. */\nfunction findCalls(program: Program, config: ObjectExpression, kind: ExtensionKind = extensionKinds.plugin): Array<FactoryCall> {\n const imports = getImports(program)\n return factoryNodes(config, kind).flatMap((node) => {\n if (node?.type !== nodeTypes.callExpression || node.callee.type !== nodeTypes.identifier) return []\n const imported = imports.get(node.callee.name)\n return imported ? [{ importName: node.callee.name, exportName: imported.exported, packageName: imported.from, call: node }] : []\n })\n}\n\n// Disabled plugins\n\n/** Whether nothing but whitespace precedes `offset` on its line. */\nfunction startsLine(source: string, offset: number): boolean {\n return source.slice(source.lastIndexOf('\\n', offset - 1) + 1, offset).trim() === ''\n}\n\n/** The `disable-plugin` blocks in this config, read from marker comments since the call is no longer a node. */\nfunction findDisabled(source: string, comments: Array<Comment>, config: ObjectExpression): Array<DisabledBlock> {\n const lines = source.split('\\n')\n\n return comments.flatMap((comment) => {\n const match = comment.type === commentTypes.line ? comment.value.trim().match(DISABLED_MARKER_PATTERN) : null\n // Only markers inside this entry, on a line of their own, so another entry or a trailing comment never matches.\n if (!match || comment.start < config.start || comment.end > config.end || !startsLine(source, comment.start)) return []\n\n const line = getPosition(source, comment.start).line\n const end = line + Number(match[2])\n const code = lines.slice(line, end).map((text) => text.replace(/^(\\s*)\\/\\/ ?/, '$1').replace(/^\\s+$/, ''))\n return [{ packageName: match[1]!, line, end, code }]\n })\n}\n\n// Reading options\n\n/** Literal members as `value` and code paths as `locked`, `undefined` for a computed key. */\nfunction readEditable(node: ObjectExpression, prefix: Array<string> = []): { value: Record<string, OptionValue>; locked: Array<Array<string>> } | undefined {\n const value: Record<string, OptionValue> = {}\n const locked: Array<Array<string>> = []\n\n for (const [index, entry] of node.properties.entries()) {\n if (entry.type === nodeTypes.spreadElement) continue\n const key = getKey(entry)\n if (key === undefined) return undefined\n if (findProperty(node, key)?.index !== index) continue\n\n const path = [...prefix, key]\n // A `__proto__` key replaces the prototype, so it reads as code.\n if (!isSafeKey(key)) {\n locked.push(path)\n continue\n }\n\n const member = isOverridden(node, index) ? undefined : entry.value\n const literal = readLiteral(member)\n if (literal !== undefined) {\n value[key] = literal\n continue\n }\n if (member?.type !== nodeTypes.objectExpression) {\n locked.push(path)\n continue\n }\n\n const nested = readEditable(member, path)\n if (!nested) return undefined\n value[key] = nested.value\n locked.push(...nested.locked)\n }\n return { value, locked }\n}\n\nfunction readObjectOptions(options: ObjectExpression): OptionsView {\n const entries: OptionsView = {}\n for (const [index, entry] of options.properties.entries()) {\n const key = getKey(entry)\n if (key === undefined || !isSafeKey(key)) continue\n\n const member = entry.type === nodeTypes.property && !isOverridden(options, index) ? entry.value : undefined\n const value = readLiteral(member)\n if (value !== undefined) {\n entries[key] = { literal: true, value }\n continue\n }\n entries[key] = { literal: false, ...(member?.type === nodeTypes.objectExpression ? readEditable(member) : undefined) }\n }\n return entries\n}\n\nfunction readCallOptions(call: CallExpression): OptionsView {\n const options = call.arguments[0]\n return options?.type === nodeTypes.objectExpression ? readObjectOptions(options) : {}\n}\n\nfunction readDisabledOptions(code: Array<string>): OptionsView {\n const call = parseExpression(code.join('\\n').trim().replace(/,$/, ''))\n return call?.type === nodeTypes.callExpression ? readCallOptions(call) : {}\n}\n\nfunction toPluginView({ importName, packageName, call }: FactoryCall): PluginView {\n return { importName, packageName, options: readCallOptions(call) }\n}\n\n/** Active and disabled plugins, in source order so a disabled plugin keeps its place. */\nfunction readPlugins({ source, parsed, config }: { source: string; parsed: ParsedConfig; config: ObjectExpression }): Array<PluginView> {\n const importNames = new Map([...getImports(parsed.program)].map(([local, { from }]) => [from, local]))\n\n const active = findCalls(parsed.program, config).map((call) => ({ line: getPosition(source, call.call.start).line, plugin: toPluginView(call) }))\n const disabled = findDisabled(source, parsed.comments, config).map(({ packageName, line, code }) => ({\n line,\n plugin: {\n importName: importNames.get(packageName) ?? toExportName(packageName),\n packageName,\n options: readDisabledOptions(code),\n disabled: true as const,\n },\n }))\n\n return [...active, ...disabled].sort((a, b) => a.line - b.line).map(({ plugin }) => plugin)\n}\n\nfunction readConfigView({ source, parsed, config }: { source: string; parsed: ParsedConfig; config: ObjectExpression }): ConfigView {\n const [adapter] = findCalls(parsed.program, config, extensionKinds.adapter).map(toPluginView)\n const parsers = findCalls(parsed.program, config, extensionKinds.parser).map(toPluginView)\n const output = getOutput(config)\n\n return {\n name: getConfigName(config),\n plugins: readPlugins({ source, parsed, config }),\n ...(adapter && { adapter }),\n ...(parsers.length ? { parsers } : {}),\n ...(!('reason' in output) && { output: pickOutput(readObjectOptions(output.object)) }),\n }\n}\n\n/** Which plugins the file declares and which options Studio may write. */\nexport function readConfig(source: string): ConfigFileView {\n const parsed = findConfigs(source)\n if ('reason' in parsed) return { managed: false, reason: parsed.reason }\n\n return { managed: true, configs: parsed.configs.map((config) => readConfigView({ source, parsed, config })) }\n}\n\n/** The modules the file imports, empty when it cannot be parsed. */\nexport function readImports(source: string): Array<string> {\n const parsed = parseSource(source)\n if ('reason' in parsed) return []\n return [...new Set([...getImports(parsed.program).values()].map(({ from }) => from))]\n}\n\n// Editing options\n\ntype FoundPath = { object: ObjectExpression; index: number; value: Expression } | { object: ObjectExpression; missing: number } | { reason: string }\n\n/** Follows `path` to its literal, or to the first missing key. Refuses a value set in code. */\nfunction findPath(options: ObjectExpression, path: Array<string>): FoundPath {\n let object = options\n\n for (const [depth, key] of path.entries()) {\n const found = findProperty(object, key)\n if (!found) return { object, missing: depth }\n if (isOverridden(object, found.index)) {\n return { reason: `${path.slice(0, depth + 1).join('.')} can be overridden by a spread after it, so it is customized in code` }\n }\n\n const { member, index } = found\n const isLast = depth === path.length - 1\n if (isLast) {\n return member.type === nodeTypes.property && readLiteral(member.value) !== undefined\n ? { object, index, value: member.value }\n : { reason: `${path.join('.')} is customized in code` }\n }\n if (member.type !== nodeTypes.property || member.value.type !== nodeTypes.objectExpression) {\n return { reason: `${key} is not an object, so ${path.join('.')} cannot be reached` }\n }\n object = member.value\n }\n return { reason: 'no option path given' }\n}\n\nfunction setAtPath({\n source,\n options,\n path,\n value,\n quote,\n}: {\n source: string\n options: ObjectExpression\n path: Array<string>\n value: OptionValue\n quote: Quote\n}): EditResult {\n const target = findPath(options, path)\n if ('reason' in target) return target\n if ('missing' in target) {\n const [key, ...rest] = path.slice(target.missing)\n return { source: appendItem(source, target.object, `${printKey(key!, quote)}: ${printValue(wrapPath(rest, value), quote)}`) }\n }\n return { source: replaceText(source, target.value.start, target.value.end, printValue(value, quote)) }\n}\n\nfunction removeAtPath({ source, options, path }: { source: string; options: ObjectExpression; path: Array<string> }): EditResult {\n const target = findPath(options, path)\n if ('reason' in target) return target\n if ('missing' in target) return { source }\n return { source: removeItem(source, target.object, target.index) }\n}\n\nfunction setOption(source: string, call: CallExpression, path: Array<string>, value: unknown, quote: Quote): EditResult {\n if (!isOptionValue(value)) return { reason: 'the value is not a literal that can be written to a config file' }\n\n const options = call.arguments[0]\n if (!options) {\n const closing = call.end - 1\n if (source[closing] !== ')') return { reason: 'the factory call could not be located in the file' }\n return { source: replaceText(source, closing, closing, printValue(wrapPath(path, value), quote)) }\n }\n if (options.type !== nodeTypes.objectExpression) return { reason: 'the factory was not called with an object literal' }\n return setAtPath({ source, options, path, value, quote })\n}\n\nfunction removeOption(source: string, call: CallExpression, path: Array<string>): EditResult {\n const options = call.arguments[0]\n if (!options) return { source }\n if (options.type !== nodeTypes.objectExpression) return { reason: 'the factory was not called with an object literal' }\n return removeAtPath({ source, options, path })\n}\n\nfunction editOption({\n source,\n parsed,\n config,\n edit,\n quote,\n extensions,\n}: {\n source: string\n parsed: ParsedConfig\n config: ObjectExpression\n edit: OptionEdit\n quote: Quote\n extensions: InstalledExtensions\n}): EditResult {\n const kind = edit.kind ?? extensionKinds.plugin\n // A package can ship several factories (`parserTs`, `parserTsx`), so prefer the export its manifest names.\n const calls = findCalls(parsed.program, config, kind).filter((entry) => entry.packageName === edit.plugin)\n const exportName = extensions.get(edit.plugin)?.manifest.export ?? toExportName(edit.plugin)\n const call = (calls.find((entry) => entry.exportName === exportName) ?? calls[0])?.call\n\n if (!call) {\n if (kind === extensionKinds.adapter) return { reason: `${edit.plugin} is not the config's adapter` }\n const disabled = kind === extensionKinds.plugin && findDisabled(source, parsed.comments, config).some((block) => block.packageName === edit.plugin)\n return { reason: disabled ? `${edit.plugin} is disabled, enable it first` : `${edit.plugin} is not in the ${kind}s array` }\n }\n\n if (edit.operation === ConfigEditOperation.SET_OPTION) return setOption(source, call, edit.path, edit.value, quote)\n return removeOption(source, call, edit.path)\n}\n\n// Editing the config's own fields\n\nfunction setInput(source: string, config: ObjectExpression, input: string, quote: Quote): EditResult {\n const value = printValue(input, quote)\n const found = findProperty(config, 'input')\n if (!found) return { source: appendItem(source, config, `input: ${value}`) }\n if (found.member.type !== nodeTypes.property || !isPlainProperty(found.member)) return { reason: 'input is not a plain property' }\n if (isOverridden(config, found.index)) return { reason: 'a spread after input could override it' }\n return { source: replaceText(source, found.member.value.start, found.member.value.end, value) }\n}\n\nfunction getOutput(config: ObjectExpression): { object: ObjectExpression } | { reason: string } {\n const found = findProperty(config, 'output')\n if (found?.member.type !== nodeTypes.property || found.member.value.type !== nodeTypes.objectExpression) return { reason: 'output is not an object literal' }\n if (isOverridden(config, found.index)) return { reason: 'a spread after output could override it' }\n return { object: found.member.value }\n}\n\nfunction editOutput({ source, config, edit, quote }: { source: string; config: ObjectExpression; edit: OutputEdit; quote: Quote }): EditResult {\n const output = getOutput(config)\n if ('reason' in output) return output\n if (edit.operation === ConfigEditOperation.REMOVE_OUTPUT) return removeAtPath({ source, options: output.object, path: edit.path })\n\n const [key, ...rest] = edit.path\n if (!isOptionValue(edit.value) || !isOutputValue({ key: key!, value: wrapPath(rest, edit.value) }))\n return { reason: `the value is not one output.${key} takes` }\n return setAtPath({ source, options: output.object, path: edit.path, value: edit.value, quote })\n}\n\n// Adding, disabling, and enabling plugins\n\n/** Adds the import after the last one, matching its semicolon style. */\nfunction addImport({\n source,\n parsed,\n importNames,\n moduleSpecifier,\n quote,\n}: {\n source: string\n parsed: ParsedConfig\n importNames: Array<string>\n moduleSpecifier: string\n quote: Quote\n}): string {\n const lastImport = parsed.program.body.findLast((node) => isImportStatement(node, parsed.kind))\n const afterLine = lastImport ? getPosition(source, lastImport.end).line : 0\n const lines = source.split('\\n')\n\n const semicolon = afterLine > 0 && lines[afterLine - 1]?.trimEnd().endsWith(';') ? ';' : ''\n const specifier = `${quote}${moduleSpecifier}${quote}`\n const statement =\n parsed.kind === moduleKinds.esm ? `import { ${importNames.join(', ')} } from ${specifier}` : `const { ${importNames.join(', ')} } = require(${specifier})`\n\n lines.splice(afterLine, 0, `${statement}${semicolon}`)\n if (afterLine === 0) lines.splice(1, 0, '')\n\n return lines.join('\\n')\n}\n\n/**\n * The parsers `defineConfig` applies when a config sets no `parsers`, by import name. Adding a parser\n * to such a config writes these too, or the new array would replace them.\n */\nconst DEFAULT_PARSERS = [\n { importName: 'parserTs', packageName: '@kubb/parser-ts' },\n { importName: 'parserTsx', packageName: '@kubb/parser-ts' },\n { importName: 'parserMd', packageName: '@kubb/parser-md' },\n] as const\n\n/**\n * Adds a plugin to `plugins`, or with `kind: 'parser'` a parser to `parsers`. Replaying the same add\n * is a no-op, while an import name taken by another package is an error.\n */\nfunction addPlugin({\n source,\n parsed,\n config,\n edit,\n quote,\n extensions,\n}: {\n source: string\n parsed: ParsedConfig\n config: ObjectExpression\n edit: AddPluginEdit\n quote: Quote\n extensions: InstalledExtensions\n}): EditResult {\n const kind = edit.kind ?? extensionKinds.plugin\n const isParser = kind === extensionKinds.parser\n if (!isAllowedPlugin({ packageName: edit.plugin, extensions, kind })) {\n return {\n reason: isParser ? `\"${edit.plugin}\" is not an installed Kubb parser` : `\"${edit.plugin}\" is not a @kubb/plugin-* package or an installed Kubb plugin`,\n }\n }\n\n const importName = extensions.get(edit.plugin)?.manifest.export ?? toExportName(edit.plugin)\n if (!IDENTIFIER_PATTERN.test(importName)) return { reason: `\"${importName}\" is not a valid import name` }\n // A package can ship several parsers (`parserTs` and `parserTsx`), so a parser is matched by its export too.\n if (findCalls(parsed.program, config, kind).some((entry) => entry.packageName === edit.plugin && (!isParser || entry.exportName === importName))) {\n return { source }\n }\n\n const options = edit.options ?? {}\n if (!isOptionValue(options)) return { reason: 'the options are not literals that can be written to a config file' }\n\n const key = `${kind}s`\n const array = getValue(config, key)\n if (array ? array.type !== nodeTypes.arrayExpression : !isParser) return { reason: `${key} is not an array literal` }\n // A config without `parsers` runs the defaults, so the new array lists them before the added parser.\n const defaults = isParser && !array ? DEFAULT_PARSERS.filter((parser) => parser.importName !== importName) : []\n\n // The missing imports by package, so `parserTs` and `parserTsx` share one line.\n const imports = getImports(parsed.program)\n const missing = memo.create<string, Array<string>>()\n for (const item of [...defaults, { importName, packageName: edit.plugin }]) {\n const from = imports.get(item.importName)?.from\n if (from && from !== item.packageName) return { reason: `${item.importName} is already imported from ${from}` }\n if (!from) memo(missing, item.packageName, () => []).push(item.importName)\n }\n\n // The array sits below the imports, so adding to it first leaves the import lines where they are.\n const call = `${importName}(${Object.keys(options).length ? printValue(options, quote) : ''})`\n const next =\n array?.type === nodeTypes.arrayExpression\n ? appendItem(source, array, call)\n : appendItem(source, config, `parsers: [${[...defaults.map((parser) => `${parser.importName}()`), call].join(', ')}]`)\n\n return {\n source: [...missing].reduceRight(\n (current, [moduleSpecifier, importNames]) => addImport({ source: current, parsed, importNames, moduleSpecifier, quote }),\n next,\n ),\n }\n}\n\n/** One item per line, so a call can be commented out alone. Skipped when comments sit between items. */\nfunction splitPlugins(source: string, config: ObjectExpression): string | undefined {\n const array = getValue(config, 'plugins')\n if (array?.type !== nodeTypes.arrayExpression) return undefined\n\n const items = array.elements.flatMap((element) => (element ? [element] : []))\n const { start, end } = array\n const gaps = [source.slice(start + 1, items[0]?.start ?? end - 1), ...items.map((item, index) => source.slice(item.end, items[index + 1]?.start ?? end - 1))]\n if (!items.length || gaps.some((gap) => !/^[\\s,]*$/.test(gap))) return undefined\n\n const lineStart = source.lastIndexOf('\\n', start - 1) + 1\n const indent = source.slice(lineStart).match(/^[ \\t]*/)?.[0] ?? ''\n const lines = items.map((item) => `${indent} ${source.slice(item.start, item.end)},`)\n\n return replaceText(source, start, end, `[\\n${lines.join('\\n')}\\n${indent}]`)\n}\n\nfunction disablePlugin(source: string, program: Program, config: ObjectExpression, plugin: string): EditResult {\n const call = findCalls(program, config).find((entry) => entry.packageName === plugin)?.call\n if (!call) return { reason: `${plugin} is not in the plugins array` }\n\n const start = getPosition(source, call.start)\n const end = getPosition(source, call.end)\n const lines = source.split('\\n')\n const from = start.line - 1\n const to = end.line - 1\n const firstLine = lines[from] ?? ''\n\n // Only safe when the call sits alone on its lines: anything else on its first line, or on its last\n // line besides a trailing comma, would be swallowed into the comment and corrupt the file.\n if (firstLine.slice(0, start.column).trim() || !/^,?\\s*$/.test((lines[to] ?? '').slice(end.column))) {\n return { reason: `${plugin} shares a line with other code, so it cannot be commented out safely` }\n }\n\n const indent = firstLine.match(/^\\s*/)?.[0] ?? ''\n const commented = lines.slice(from, to + 1).map((line) => (line.trim() ? `${indent}// ${line.slice(indent.length)}` : `${indent}//`))\n lines.splice(from, commented.length, `${indent}// kubb:disabled ${plugin} ${commented.length}`, ...commented)\n\n return { source: lines.join('\\n') }\n}\n\n/** Disables the plugin, first putting a one-line `plugins: [a(), b()]` (what `add-plugin` writes) on separate lines. */\nfunction disablePluginInConfig({\n source,\n parsed,\n config,\n edit,\n}: {\n source: string\n parsed: ParsedConfig\n config: ObjectExpression\n edit: DisablePluginEdit\n}): EditResult {\n const result = disablePlugin(source, parsed.program, config, edit.plugin)\n if (!('reason' in result) || !result.reason.includes('shares a line')) return result\n\n const split = splitPlugins(source, config)\n if (split === undefined) return result\n\n const reparsed = findConfigs(split)\n const reparsedConfig = 'reason' in reparsed ? undefined : findConfigEntry(reparsed.configs, edit.config)\n if ('reason' in reparsed || !reparsedConfig) return result\n\n return disablePlugin(split, reparsed.program, reparsedConfig, edit.plugin)\n}\n\nfunction enablePlugin(source: string, comments: Array<Comment>, config: ObjectExpression, plugin: string): EditResult {\n const block = findDisabled(source, comments, config).find((entry) => entry.packageName === plugin)\n if (!block) return { reason: `${plugin} is not disabled` }\n\n const lines = source.split('\\n')\n lines.splice(block.line - 1, block.end - block.line + 1, ...block.code)\n return { source: lines.join('\\n') }\n}\n\n// Removing extensions\n\n/** Drops the import statements of `packageName` once nothing else in the file uses their names. */\nfunction removeUnusedImports(source: string, packageName: string): string {\n const parsed = parseSource(source)\n if ('reason' in parsed) return source\n\n // From the last statement up, so the offsets of the earlier ones stay valid.\n return parsed.program.body.reduceRight((current, statement) => {\n const bindings =\n statement.type === nodeTypes.importDeclaration\n ? importBindings(statement)\n : statement.type === nodeTypes.variableDeclaration\n ? requireBindings(statement)\n : []\n if (!bindings.length || bindings.some(([, { from }]) => from !== packageName)) return current\n\n const rest = replaceText(current, statement.start, statement.end)\n if (bindings.some(([local]) => new RegExp(`(?<![\\\\w$])${local.replaceAll('$', '\\\\$')}(?![\\\\w$])`).test(rest))) return current\n\n const lineStart = current.lastIndexOf('\\n', statement.start - 1) + 1\n const lineEnd = current.indexOf('\\n', statement.end)\n const after = lineEnd === -1 ? current.length : lineEnd + 1\n // At the top of the file, the blank line after the import goes too, so the file does not start with one.\n return replaceText(current, lineStart, lineStart === 0 && current[after] === '\\n' ? after + 1 : after)\n }, source)\n}\n\n/**\n * Removes every call of a plugin or parser package, and the block `disable-plugin` commented out,\n * then its unused imports. Removing what the config does not hold is a no-op. Refuses to empty\n * `parsers`, since a config with no parser cannot print files.\n */\nfunction removeExtension(source: string, edit: RemoveExtensionEdit): EditResult {\n const kind = edit.kind ?? extensionKinds.plugin\n let current = source\n\n // One call at a time, re-parsing in between, since each removal moves the ones after it.\n for (;;) {\n const parsed = findConfigs(current)\n if ('reason' in parsed) return parsed\n const config = findConfigEntry(parsed.configs, edit.config)\n if (!config) return { reason: `no config entry found for ${JSON.stringify(edit.config)}` }\n\n const array = getValue(config, `${kind}s`)\n const calls = findCalls(parsed.program, config, kind).filter((entry) => entry.packageName === edit.plugin)\n const block = findDisabled(current, parsed.comments, config).find((entry) => entry.packageName === edit.plugin)\n\n if (calls[0] && array?.type === nodeTypes.arrayExpression) {\n const elements = array.elements.filter((element) => element !== null)\n if (kind === extensionKinds.parser && elements.length === calls.length) return { reason: `${edit.plugin} is the last parser in the parsers array` }\n current = removeItem(current, array, elements.indexOf(calls[0].call))\n continue\n }\n if (block && kind === extensionKinds.plugin) {\n const lines = current.split('\\n')\n lines.splice(block.line - 1, block.end - block.line + 1)\n current = lines.join('\\n')\n continue\n }\n return { source: current === source ? source : removeUnusedImports(current, edit.plugin) }\n }\n}\n\n// Applying edits\n\n/** Every edit re-parses the file, since the previous one rewrote it. */\nfunction applyEdit({ source, edit, extensions }: { source: string; edit: ConfigEdit; extensions: InstalledExtensions }): EditResult {\n const parsed = findConfigs(source)\n if ('reason' in parsed) return parsed\n\n const config = findConfigEntry(parsed.configs, edit.config)\n if (!config) return { reason: `no config entry found for ${JSON.stringify(edit.config)}` }\n const quote = detectQuote(parsed.program) ?? quotes.single\n\n switch (edit.operation) {\n case ConfigEditOperation.SET_INPUT:\n return setInput(source, config, edit.input, quote)\n case ConfigEditOperation.SET_OUTPUT:\n case ConfigEditOperation.REMOVE_OUTPUT:\n return editOutput({ source, config, edit, quote })\n case ConfigEditOperation.DISABLE_PLUGIN:\n return disablePluginInConfig({ source, parsed, config, edit })\n case ConfigEditOperation.ENABLE_PLUGIN:\n return enablePlugin(source, parsed.comments, config, edit.plugin)\n case ConfigEditOperation.ADD_PLUGIN:\n return addPlugin({ source, parsed, config, edit, quote, extensions })\n case ConfigEditOperation.REMOVE_EXTENSION:\n return removeExtension(source, edit)\n case ConfigEditOperation.SET_OPTION:\n case ConfigEditOperation.REMOVE_OPTION:\n return editOption({ source, parsed, config, edit, quote, extensions })\n }\n}\n\n/** Applies edits in place, touching only the text each targets. A refused edit is reported and the rest still run. */\nexport function editConfig({ source, edits, extensions = new Map() }: { source: string; edits: Array<ConfigEdit>; extensions?: InstalledExtensions }): {\n source: string\n outcomes: Array<ConfigEditOutcome>\n changed: boolean\n} {\n let current = source\n\n const outcomes = edits.map((edit): ConfigEditOutcome => {\n const invalid = validateEdit(edit)\n if (invalid) return { edit, applied: false, reason: invalid }\n\n try {\n const result = applyEdit({ source: current, edit, extensions })\n if ('reason' in result) return { edit, applied: false, reason: result.reason }\n current = result.source\n return { edit, applied: true }\n } catch (error) {\n return { edit, applied: false, reason: getErrorMessage(error) }\n }\n })\n\n return { source: current, outcomes, changed: current !== source }\n}\n\n/** Applies `edits` to `filePath`, writing only when something changed. */\nexport async function editConfigFile({ filePath, edits, extensions }: { filePath: string; edits: Array<ConfigEdit>; extensions?: InstalledExtensions }) {\n const current = await read(filePath)\n const result = editConfig({ source: current, edits, extensions })\n if (result.changed) await writeRaw(filePath, result.source)\n return result\n}\n"],"mappings":";;;;;;;;AAoBA,MAAa,YAAY;CACvB,iBAAiB;CACjB,yBAAyB;CACzB,sBAAsB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,0BAA0B;CAC1B,qBAAqB;CACrB,oBAAoB;CACpB,YAAY;CACZ,mBAAmB;CACnB,iBAAiB;CACjB,SAAS;CACT,kBAAkB;CAClB,kBAAkB;CAClB,eAAe;CACf,UAAU;CACV,iBAAiB;CACjB,eAAe;CACf,gBAAgB;CAChB,uBAAuB;CACvB,iBAAiB;CACjB,iBAAiB;CACjB,qBAAqB;AACvB;AAEA,MAAa,eAAe,EAAE,MAAM,OAAO;AAC3C,MAAa,gBAAgB,EAAE,MAAM,OAAO;AAC5C,MAAa,iBAAiB;CAAE,OAAO;CAAK,MAAM;AAAI;AACtD,MAAM,uBAAuB,EAAE,OAAO,QAAQ;;;;;AAS9C,SAAgB,YAAY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;EAAE,QAAQ;EAAS;EAAU,SAAS,YAAY;CAAO;AAClE;;AAGA,eAAsB,eAAe,EAAE,UAAU,OAAO,cAAgG;CAEtJ,MAAM,SAAS,WAAW;EAAE,QAAQ,MADdC,gBAAAA,KAAK,QAAQ;EACU;EAAO;CAAW,CAAC;CAChE,IAAI,OAAO,SAAS,MAAMC,gBAAAA,SAAS,UAAU,OAAO,MAAM;CAC1D,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
2
|
import { t as getErrorMessage } from "./errors-CEzFbRvL.js";
|
|
3
|
-
import { i as read, s as writeRaw } from "./fs-
|
|
4
|
-
import { f as camelCase } from "./utils-
|
|
3
|
+
import { i as read, l as memo, s as writeRaw } from "./fs-CWRKTIst.js";
|
|
4
|
+
import { f as camelCase } from "./utils-DnmjcKb0.js";
|
|
5
5
|
import { isPackageName } from "@kubb/core";
|
|
6
6
|
import { parse } from "yuku-parser";
|
|
7
7
|
// ../../internals/shared/src/configFile/ast.ts
|
|
@@ -749,14 +749,14 @@ function addPlugin({ source, parsed, config, edit, quote, extensions }) {
|
|
|
749
749
|
if (array ? array.type !== nodeTypes.arrayExpression : !isParser) return { reason: `${key} is not an array literal` };
|
|
750
750
|
const defaults = isParser && !array ? DEFAULT_PARSERS.filter((parser) => parser.importName !== importName) : [];
|
|
751
751
|
const imports = getImports(parsed.program);
|
|
752
|
-
const missing =
|
|
752
|
+
const missing = memo.create();
|
|
753
753
|
for (const item of [...defaults, {
|
|
754
754
|
importName,
|
|
755
755
|
packageName: edit.plugin
|
|
756
756
|
}]) {
|
|
757
757
|
const from = imports.get(item.importName)?.from;
|
|
758
758
|
if (from && from !== item.packageName) return { reason: `${item.importName} is already imported from ${from}` };
|
|
759
|
-
if (!from) missing
|
|
759
|
+
if (!from) memo(missing, item.packageName, () => []).push(item.importName);
|
|
760
760
|
}
|
|
761
761
|
const call = `${importName}(${Object.keys(options).length ? printValue(options, quote) : ""})`;
|
|
762
762
|
const next = array?.type === nodeTypes.arrayExpression ? appendItem(source, array, call) : appendItem(source, config, `parsers: [${[...defaults.map((parser) => `${parser.importName}()`), call].join(", ")}]`);
|
|
@@ -954,4 +954,4 @@ async function editConfigFile({ filePath, edits, extensions }) {
|
|
|
954
954
|
}
|
|
955
955
|
export { ConfigEditOperation as a, readImports as i, editConfigFile as n, extensionKinds as o, readConfig as r, editConfig as t };
|
|
956
956
|
|
|
957
|
-
//# sourceMappingURL=configFile-
|
|
957
|
+
//# sourceMappingURL=configFile-Bh_5k4pf.js.map
|