@kubb/cli 5.0.0-beta.36 → 5.0.0-beta.38
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/README.md +14 -11
- package/dist/{agent-DajReUxm.cjs → agent-Bl8JwjMa.cjs} +4 -4
- package/dist/{agent-DajReUxm.cjs.map → agent-Bl8JwjMa.cjs.map} +1 -1
- package/dist/{agent-cAalLgeU.js → agent-CfZ_Uqde.js} +4 -4
- package/dist/{agent-cAalLgeU.js.map → agent-CfZ_Uqde.js.map} +1 -1
- package/dist/{constants-FhPsMOdo.cjs → constants-CAKUpLcQ.cjs} +3 -12
- package/dist/{constants-FhPsMOdo.cjs.map → constants-CAKUpLcQ.cjs.map} +1 -1
- package/dist/{constants-Co6NWt3U.js → constants-CYxk4aNm.js} +4 -7
- package/dist/{constants-Co6NWt3U.js.map → constants-CYxk4aNm.js.map} +1 -1
- package/dist/{generate-C6oskVzT.cjs → generate-Bgds6Zx3.cjs} +19 -14
- package/dist/generate-Bgds6Zx3.cjs.map +1 -0
- package/dist/{generate-DmYQJcBv.js → generate-CfxFqNeb.js} +19 -14
- package/dist/generate-CfxFqNeb.js.map +1 -0
- package/dist/index.cjs +8 -8
- package/dist/index.js +8 -8
- package/dist/{init-Dbb4U-Xs.cjs → init-C5wnuzeK.cjs} +2 -2
- package/dist/{init-Dbb4U-Xs.cjs.map → init-C5wnuzeK.cjs.map} +1 -1
- package/dist/{init-iOg_X-uh.js → init-TIec3Dym.js} +2 -2
- package/dist/{init-iOg_X-uh.js.map → init-TIec3Dym.js.map} +1 -1
- package/dist/{mcp-DxrSTT8i.cjs → mcp-Cr753GW1.cjs} +3 -3
- package/dist/{mcp-DxrSTT8i.cjs.map → mcp-Cr753GW1.cjs.map} +1 -1
- package/dist/{mcp-Ci2OkdBj.js → mcp-Damue5Mq.js} +3 -3
- package/dist/{mcp-Ci2OkdBj.js.map → mcp-Damue5Mq.js.map} +1 -1
- package/dist/package-Cnt1K03J.js +6 -0
- package/dist/package-Cnt1K03J.js.map +1 -0
- package/dist/{package-DbsOo2rT.cjs → package-guApEHiW.cjs} +2 -2
- package/dist/package-guApEHiW.cjs.map +1 -0
- package/dist/{run-v-75bcU1.js → run-BFEK9md9.js} +2 -2
- package/dist/{run-v-75bcU1.js.map → run-BFEK9md9.js.map} +1 -1
- package/dist/{run-GvXhj9XF.cjs → run-BFZtWpcW.cjs} +491 -314
- package/dist/run-BFZtWpcW.cjs.map +1 -0
- package/dist/{run-CCgNPz0F.cjs → run-BFv6avA_.cjs} +3 -3
- package/dist/{run-CCgNPz0F.cjs.map → run-BFv6avA_.cjs.map} +1 -1
- package/dist/{run-DpDKN_rb.cjs → run-BQZyg7If.cjs} +2 -2
- package/dist/{run-DpDKN_rb.cjs.map → run-BQZyg7If.cjs.map} +1 -1
- package/dist/{run-CPimpDgO.js → run-BvXxelGR.js} +2 -2
- package/dist/{run-CPimpDgO.js.map → run-BvXxelGR.js.map} +1 -1
- package/dist/{run-Lnupy7qb.cjs → run-Bz9IFMWg.cjs} +2 -2
- package/dist/{run-Lnupy7qb.cjs.map → run-Bz9IFMWg.cjs.map} +1 -1
- package/dist/{run-B9ZkldVt.js → run-C752fag9.js} +557 -380
- package/dist/run-C752fag9.js.map +1 -0
- package/dist/run-C_NMctua.cjs.map +1 -1
- package/dist/run-D8dCWepS.js.map +1 -1
- package/dist/{run-BRrNHp24.js → run-DJxYClJV.js} +3 -3
- package/dist/{run-BRrNHp24.js.map → run-DJxYClJV.js.map} +1 -1
- package/dist/{telemetry-DRhd3joO.cjs → telemetry-B80oJfxR.cjs} +2 -2
- package/dist/telemetry-B80oJfxR.cjs.map +1 -0
- package/dist/{telemetry-ne1IOrz1.js → telemetry-ueaMzs_c.js} +2 -2
- package/dist/telemetry-ueaMzs_c.js.map +1 -0
- package/dist/{validate-Bh7MgISX.js → validate-CYTKdezO.js} +3 -3
- package/dist/{validate-Bh7MgISX.js.map → validate-CYTKdezO.js.map} +1 -1
- package/dist/{validate-DVkJx4q8.cjs → validate-DMzjP-hd.cjs} +3 -3
- package/dist/{validate-DVkJx4q8.cjs.map → validate-DMzjP-hd.cjs.map} +1 -1
- package/package.json +6 -6
- package/src/commands/generate.ts +16 -10
- package/src/constants.ts +1 -1
- package/src/loggers/clackLogger.ts +68 -71
- package/src/loggers/diagnostics.ts +77 -0
- package/src/loggers/githubActionsLogger.ts +38 -31
- package/src/loggers/plainLogger.ts +10 -26
- package/src/loggers/types.ts +1 -1
- package/src/loggers/utils.ts +47 -94
- package/src/reporters/cliReporter.ts +89 -0
- package/src/reporters/fileReporter.ts +103 -0
- package/src/reporters/jsonReporter.ts +20 -0
- package/src/reporters/report.ts +84 -0
- package/src/runners/agent/run.ts +2 -2
- package/src/runners/generate/run.ts +130 -44
- package/src/runners/generate/utils.ts +8 -11
- package/src/runners/init/run.ts +1 -1
- package/src/telemetry.ts +2 -2
- package/dist/generate-C6oskVzT.cjs.map +0 -1
- package/dist/generate-DmYQJcBv.js.map +0 -1
- package/dist/package-DbsOo2rT.cjs.map +0 -1
- package/dist/package-_R15a7lY.js +0 -6
- package/dist/package-_R15a7lY.js.map +0 -1
- package/dist/run-B9ZkldVt.js.map +0 -1
- package/dist/run-GvXhj9XF.cjs.map +0 -1
- package/dist/telemetry-DRhd3joO.cjs.map +0 -1
- package/dist/telemetry-ne1IOrz1.js.map +0 -1
- package/src/loggers/fileSystemLogger.ts +0 -151
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-BRrNHp24.js","names":[],"sources":["../src/runners/agent/utils.ts","../src/runners/agent/run.ts"],"sourcesContent":["import net from 'node:net'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { agentDefaults } from '../../constants.ts'\n\ntype AgentStartEnvironmentInput = {\n /**\n * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).\n */\n port: string | undefined\n /**\n * Hostname the HTTP server binds to.\n */\n host: string\n /**\n * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.\n */\n configPath: string | undefined\n /**\n * Grants the agent permission to write generated files to the filesystem.\n */\n allowWrite: boolean\n /**\n * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.\n */\n allowAll: boolean\n}\n\ntype ResolvedAgentStartEnvironment = {\n /**\n * Final port string after merging CLI flag, `PORT` env var, and the default.\n */\n port: string\n /**\n * Final hostname after merging CLI flag, `HOST` env var, and the default.\n */\n host: string\n /**\n * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.\n */\n allowWrite: boolean\n /**\n * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.\n */\n allowAll: boolean\n /**\n * Absolute path to the Kubb config file passed to the agent subprocess.\n */\n agentConfigPath: string\n /**\n * Merged `process.env` object with all resolved agent environment variables applied.\n */\n env: NodeJS.ProcessEnv\n}\n\n/**\n * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.\n */\nexport function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {\n const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port\n const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)\n const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'\n const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'\n const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()\n const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)\n\n return {\n port: resolvedPort,\n host: resolvedHost,\n allowWrite: resolvedAllowWrite,\n allowAll: resolvedAllowAll,\n agentConfigPath,\n env: {\n ...process.env,\n PORT: resolvedPort,\n HOST: resolvedHost,\n KUBB_AGENT_ROOT: agentRoot,\n KUBB_AGENT_CONFIG: agentConfigPath,\n KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),\n KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),\n KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,\n KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,\n KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,\n },\n }\n}\n\nexport function isPortAvailable(port: number, host: string): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer()\n server.once('error', () => resolve(false))\n server.once('listening', () => {\n server.close()\n resolve(true)\n })\n server.listen(port, host)\n })\n}\n","import { createRequire } from 'node:module'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { spawnAsync, getErrorMessage } from '@internals/utils'\nimport { agentDefaults } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'\nimport { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'\n\ntype AgentStartOptions = {\n /**\n * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).\n */\n port: string | undefined\n /**\n * Hostname the HTTP server binds to.\n *\n * @default 'localhost'\n */\n host: string\n /**\n * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.\n */\n configPath: string | undefined\n /**\n * Grants the agent permission to write generated files to the filesystem.\n */\n allowWrite: boolean\n /**\n * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.\n */\n allowAll: boolean\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Spawns the Kubb Agent HTTP server as a Node.js subprocess.\n * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.\n */\nexport async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'agent', kubbVersion: version, hrStart, status }))\n\n try {\n // Load .env file into process.env using Node.js built-in (v20.12.0+)\n try {\n process.loadEnvFile()\n } catch {\n // .env file may not exist; ignore\n }\n\n // Resolve the @kubb/agent package path — createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)\n const require = createRequire(import.meta.url)\n let agentPkgPath: string\n try {\n agentPkgPath = require.resolve('@kubb/agent/package.json')\n } catch (_e) {\n console.error(styleText('red', 'The @kubb/agent package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/agent'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/agent'))\n console.error('')\n process.exit(1)\n }\n const agentDir = path.dirname(agentPkgPath)\n const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)\n\n const resolvedEnv = resolveAgentStartEnvironment({\n port,\n host,\n configPath,\n allowWrite,\n allowAll,\n })\n const numericPort = Number(resolvedEnv.port)\n\n if (!Number.isInteger(numericPort) || numericPort <= 0) {\n throw new Error(`Invalid port \"${resolvedEnv.port}\". Provide a positive integer with --port or PORT.`)\n }\n\n clack.log.step(styleText('cyan', 'Starting agent server...'))\n clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))\n clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))\n clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))\n if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {\n clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))\n }\n\n if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {\n clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))\n process.exit(1)\n }\n\n // Spawns the server as a detached background process so the CLI can exit independently.\n await spawnAsync('node', [serverPath], {\n env: resolvedEnv.env,\n cwd: process.cwd(),\n })\n\n await report('success')\n } catch (error) {\n await report('failed')\n clack.log.error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IAAI,GAAI;GAC3D,MAAM,IAAI,MAAM,UAAU,OAAO,QAAQ,YAAY,KAAK,sFAAsF,CAAC;GACjJ,QAAQ,KAAK,CAAC;EAChB;EAGA,MAAM,WAAW,QAAQ,CAAC,UAAU,GAAG;GACrC,KAAK,YAAY;GACjB,KAAK,QAAQ,IAAI;EACnB,CAAC;EAED,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,MAAM,IAAI,MAAM,UAAU,OAAO,8BAA8B,CAAC;EAChE,MAAM,IAAI,MAAM,gBAAgB,KAAK,CAAC;EACtC,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"run-DJxYClJV.js","names":[],"sources":["../src/runners/agent/utils.ts","../src/runners/agent/run.ts"],"sourcesContent":["import net from 'node:net'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { agentDefaults } from '../../constants.ts'\n\ntype AgentStartEnvironmentInput = {\n /**\n * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).\n */\n port: string | undefined\n /**\n * Hostname the HTTP server binds to.\n */\n host: string\n /**\n * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.\n */\n configPath: string | undefined\n /**\n * Grants the agent permission to write generated files to the filesystem.\n */\n allowWrite: boolean\n /**\n * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.\n */\n allowAll: boolean\n}\n\ntype ResolvedAgentStartEnvironment = {\n /**\n * Final port string after merging CLI flag, `PORT` env var, and the default.\n */\n port: string\n /**\n * Final hostname after merging CLI flag, `HOST` env var, and the default.\n */\n host: string\n /**\n * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.\n */\n allowWrite: boolean\n /**\n * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.\n */\n allowAll: boolean\n /**\n * Absolute path to the Kubb config file passed to the agent subprocess.\n */\n agentConfigPath: string\n /**\n * Merged `process.env` object with all resolved agent environment variables applied.\n */\n env: NodeJS.ProcessEnv\n}\n\n/**\n * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.\n */\nexport function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {\n const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port\n const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)\n const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'\n const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'\n const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()\n const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)\n\n return {\n port: resolvedPort,\n host: resolvedHost,\n allowWrite: resolvedAllowWrite,\n allowAll: resolvedAllowAll,\n agentConfigPath,\n env: {\n ...process.env,\n PORT: resolvedPort,\n HOST: resolvedHost,\n KUBB_AGENT_ROOT: agentRoot,\n KUBB_AGENT_CONFIG: agentConfigPath,\n KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),\n KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),\n KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,\n KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,\n KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,\n },\n }\n}\n\nexport function isPortAvailable(port: number, host: string): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer()\n server.once('error', () => resolve(false))\n server.once('listening', () => {\n server.close()\n resolve(true)\n })\n server.listen(port, host)\n })\n}\n","import { createRequire } from 'node:module'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { spawnAsync, getErrorMessage } from '@internals/utils'\nimport { agentDefaults } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'\nimport { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'\n\ntype AgentStartOptions = {\n /**\n * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).\n */\n port: string | undefined\n /**\n * Hostname the HTTP server binds to.\n *\n * @default 'localhost'\n */\n host: string\n /**\n * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.\n */\n configPath: string | undefined\n /**\n * Grants the agent permission to write generated files to the filesystem.\n */\n allowWrite: boolean\n /**\n * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.\n */\n allowAll: boolean\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Spawns the Kubb Agent HTTP server as a Node.js subprocess.\n * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.\n */\nexport async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'agent', kubbVersion: version, hrStart, status }))\n\n try {\n // Load .env file into process.env using Node.js built-in (v20.12.0+)\n try {\n process.loadEnvFile()\n } catch {\n // .env file may not exist. Ignore\n }\n\n // Resolve the @kubb/agent package path, createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)\n const require = createRequire(import.meta.url)\n let agentPkgPath: string\n try {\n agentPkgPath = require.resolve('@kubb/agent/package.json')\n } catch (_e) {\n console.error(styleText('red', 'The @kubb/agent package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/agent'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/agent'))\n console.error('')\n process.exit(1)\n }\n const agentDir = path.dirname(agentPkgPath)\n const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)\n\n const resolvedEnv = resolveAgentStartEnvironment({\n port,\n host,\n configPath,\n allowWrite,\n allowAll,\n })\n const numericPort = Number(resolvedEnv.port)\n\n if (!Number.isInteger(numericPort) || numericPort <= 0) {\n throw new Error(`Invalid port \"${resolvedEnv.port}\". Provide a positive integer with --port or PORT.`)\n }\n\n clack.log.step(styleText('cyan', 'Starting agent server...'))\n clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))\n clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))\n clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))\n if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {\n clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))\n }\n\n if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {\n clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))\n process.exit(1)\n }\n\n // Spawns the server as a detached background process so the CLI can exit independently.\n await spawnAsync('node', [serverPath], {\n env: resolvedEnv.env,\n cwd: process.cwd(),\n })\n\n await report('success')\n } catch (error) {\n await report('failed')\n clack.log.error(styleText('red', 'Failed to start agent server'))\n clack.log.error(getErrorMessage(error))\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0DA,SAAgB,6BAA6B,EAAE,MAAM,MAAM,YAAY,YAAY,YAAuE;CACxJ,MAAM,eAAe,QAAQ,QAAQ,IAAI,QAAQ,cAAc;CAC/D,MAAM,eAAe,SAAS,cAAc,OAAO,OAAQ,QAAQ,IAAI,QAAQ,cAAc;CAC7F,MAAM,mBAAmB,YAAY,QAAQ,IAAI,yBAAyB;CAC1E,MAAM,qBAAqB,oBAAoB,cAAc,QAAQ,IAAI,2BAA2B;CACpG,MAAM,YAAY,QAAQ,IAAI,mBAAmB,QAAQ,IAAI;CAC7D,MAAM,kBAAkB,KAAK,QAAQ,QAAQ,IAAI,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
|
|
2
|
-
const require_constants = require("./constants-
|
|
2
|
+
const require_constants = require("./constants-CAKUpLcQ.cjs");
|
|
3
3
|
let node_crypto = require("node:crypto");
|
|
4
4
|
let node_dns = require("node:dns");
|
|
5
5
|
let node_os = require("node:os");
|
|
@@ -277,4 +277,4 @@ Object.defineProperty(exports, "sendTelemetry", {
|
|
|
277
277
|
}
|
|
278
278
|
});
|
|
279
279
|
|
|
280
|
-
//# sourceMappingURL=telemetry-
|
|
280
|
+
//# sourceMappingURL=telemetry-B80oJfxR.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-B80oJfxR.cjs","names":["dnsPromises","process","OTLP_ENDPOINT","os"],"sources":["../../../internals/utils/src/env.ts","../../../internals/utils/src/network.ts","../src/telemetry.ts"],"sourcesContent":["/**\n * Returns `true` when running inside a GitHub Actions workflow.\n *\n * @example\n * ```ts\n * if (isGitHubActions()) {\n * core.setOutput('result', 'ok')\n * }\n * ```\n */\nexport function isGitHubActions(): boolean {\n return !!process.env.GITHUB_ACTIONS\n}\n\n/**\n * Returns `true` when the process is running in a CI environment.\n * Covers GitHub Actions, GitLab CI, CircleCI, Travis CI, Jenkins, Bitbucket,\n * TeamCity, Buildkite, and Azure Pipelines.\n *\n * @example\n * ```ts\n * if (isCIEnvironment()) {\n * logger.level = 'error'\n * }\n * ```\n */\nexport function isCIEnvironment(): boolean {\n return !!(\n process.env.CI ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n\n/**\n * Returns `true` when the process has an interactive TTY with a valid terminal\n * width and is not running in CI.\n *\n * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,\n * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`\n * with a negative count and throw a `RangeError`). We therefore require a\n * positive column count before declaring the TTY usable.\n *\n * @example\n * ```ts\n * if (canUseTTY()) {\n * renderProgressBar()\n * }\n * ```\n */\nexport function canUseTTY(): boolean {\n return !!process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment()\n}\n","import { promises as dnsPromises } from 'node:dns'\n\n/**\n * Well-known stable domains used as DNS probes to check internet connectivity.\n */\nconst TEST_DOMAINS = ['dns.google.com', 'cloudflare.com', 'one.one.one.one'] as const\n\n/**\n * Returns `true` when the system has internet connectivity.\n * Probes DNS resolution against well-known stable domains.\n *\n * @example\n * ```ts\n * if (await isOnline()) {\n * await fetchLatestVersion()\n * }\n * ```\n */\nexport async function isOnline(): Promise<boolean> {\n for (const domain of TEST_DOMAINS) {\n try {\n await dnsPromises.resolve(domain)\n return true\n } catch {\n // Try next domain\n }\n }\n\n return false\n}\n\n/**\n * Executes `fn` only when the system is online. Returns `null` when offline or on error.\n *\n * @example\n * ```ts\n * const version = await executeIfOnline(() => fetchLatestVersion('kubb'))\n * // null when offline\n * ```\n */\nexport async function executeIfOnline<T>(fn: () => Promise<T>): Promise<T | null> {\n if (!(await isOnline())) return null\n\n try {\n return await fn()\n } catch {\n return null\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { executeIfOnline, isCIEnvironment } from '@internals/utils'\nimport { OTLP_ENDPOINT } from './constants.ts'\n\n// OpenTelemetry OTLP JSON types\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/common/v1/common.proto\n\ntype OtlpStringValue = { stringValue: string }\ntype OtlpBoolValue = { boolValue: boolean }\ntype OtlpIntValue = { intValue: number }\ntype OtlpDoubleValue = { doubleValue: number }\ntype OtlpBytesValue = { bytesValue: string }\ntype OtlpArrayValue = { arrayValue: { values: Array<OtlpAnyValue> } }\ntype OtlpKvListValue = { kvlistValue: { values: Array<OtlpKeyValue> } }\n\ntype OtlpAnyValue = OtlpStringValue | OtlpBoolValue | OtlpIntValue | OtlpDoubleValue | OtlpBytesValue | OtlpArrayValue | OtlpKvListValue\n\ntype OtlpKeyValue = {\n key: string\n value: OtlpAnyValue\n}\n\ntype OtlpResource = {\n attributes: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpInstrumentationScope = {\n name: string\n version?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\n/** https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto#L103 */\ntype OtlpSpanKind = 0 | 1 | 2 | 3 | 4 | 5\n\n/** 0 = STATUS_CODE_UNSET, 1 = STATUS_CODE_OK, 2 = STATUS_CODE_ERROR */\ntype OtlpStatusCode = 0 | 1 | 2\n\ntype OtlpStatus = {\n code: OtlpStatusCode\n message?: string\n}\n\ntype OtlpSpan = {\n traceId: string\n spanId: string\n traceState?: string\n parentSpanId?: string\n name: string\n kind: OtlpSpanKind\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n events?: Array<OtlpSpanEvent>\n droppedEventsCount?: number\n links?: Array<OtlpSpanLink>\n droppedLinksCount?: number\n status?: OtlpStatus\n}\n\ntype OtlpSpanEvent = {\n timeUnixNano: string\n name: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpSpanLink = {\n traceId: string\n spanId: string\n traceState?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpScopeSpans = {\n scope: OtlpInstrumentationScope\n spans: Array<OtlpSpan>\n schemaUrl?: string\n}\n\ntype OtlpResourceSpans = {\n resource: OtlpResource\n scopeSpans: Array<OtlpScopeSpans>\n schemaUrl?: string\n}\n\n/** Root payload sent to POST /v1/traces */\ntype OtlpExportTraceServiceRequest = {\n resourceSpans: Array<OtlpResourceSpans>\n}\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 plugin options snapshot, values are included but cannot be traced back to the user.\n */\n options: Record<string, unknown>\n}\n\ntype TelemetryEvent = {\n command: string\n kubbVersion: string\n nodeVersion: string\n platform: string\n ci: boolean\n plugins: Array<TelemetryPlugin>\n duration: number\n filesCreated: number\n status: 'success' | 'failed'\n}\n\n/**\n * Returns `true` when the current process runs inside a CI environment.\n */\nexport function isCi(): boolean {\n return isCIEnvironment()\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n process.env['DO_NOT_TRACK'] === '1' ||\n process.env['DO_NOT_TRACK'] === 'true' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === '1' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === 'true'\n )\n}\n\n/**\n * Convert a TelemetryEvent into an OTLP-compatible JSON trace payload.\n * See https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload(event: TelemetryEvent): OtlpExportTraceServiceRequest {\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(event.duration) * 1_000_000n\n\n const attributes: Array<OtlpKeyValue> = [\n { key: 'kubb.command', value: { stringValue: event.command } },\n { key: 'kubb.version', value: { stringValue: event.kubbVersion } },\n { key: 'kubb.node_version', value: { stringValue: event.nodeVersion } },\n { key: 'kubb.platform', value: { stringValue: event.platform } },\n { key: 'kubb.ci', value: { boolValue: event.ci } },\n { key: 'kubb.files_created', value: { intValue: event.filesCreated } },\n { key: 'kubb.status', value: { stringValue: event.status } },\n {\n key: 'kubb.plugins',\n value: {\n arrayValue: {\n values: event.plugins.map(\n (p): OtlpKvListValue => ({\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\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb-cli' } },\n {\n key: 'service.version',\n value: { stringValue: event.kubbVersion },\n },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-cli', version: event.kubbVersion },\n spans: [\n {\n traceId,\n spanId,\n name: event.command,\n kind: 1 satisfies OtlpSpanKind,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: (event.status === 'success' ? 1 : 2) satisfies OtlpStatusCode,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an anonymous telemetry event to the Kubb OTLP endpoint.\n * Respects DO_NOT_TRACK and KUBB_DISABLE_TELEMETRY environment variables.\n * Fails silently to never interrupt the generation process.\n */\nexport async function sendTelemetry(event: TelemetryEvent): Promise<void> {\n if (isTelemetryDisabled()) {\n return\n }\n\n await executeIfOnline(async () => {\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(buildOtlpPayload(event)),\n signal: AbortSignal.timeout(5_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the CLI\n }\n })\n}\n\n/**\n * Build an anonymous telemetry payload from a completed generation run.\n * No file paths, OpenAPI specs, or secrets are included.\n */\nexport function buildTelemetryEvent(options: {\n command: 'generate' | 'mcp' | 'validate' | 'agent'\n kubbVersion: string\n plugins?: Array<TelemetryPlugin>\n hrStart: [number, number]\n filesCreated?: number\n status: 'success' | 'failed'\n}): TelemetryEvent {\n const [seconds, nanoseconds] = process.hrtime(options.hrStart)\n const duration = Math.round(seconds * 1000 + nanoseconds / 1e6)\n\n return {\n command: options.command,\n kubbVersion: options.kubbVersion,\n nodeVersion: process.versions.node.split('.')[0] as string,\n platform: os.platform(),\n ci: isCi(),\n plugins: options.plugins ?? [],\n duration,\n filesCreated: options.filesCreated ?? 0,\n status: options.status,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAUA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,CAAC,QAAQ,IAAI;AACvB;;;;;;;;;;;;;AAcA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,EACN,QAAQ,IAAI,MACZ,QAAQ,IAAI,kBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI,0BACZ,QAAQ,IAAI,eACZ,QAAQ,IAAI,YACZ,QAAQ,IAAI,UACZ,QAAQ,IAAI,oBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI;AAEhB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YAAqB;CACnC,OAAO,CAAC,CAAC,QAAQ,OAAO,UAAU,QAAQ,OAAO,WAAW,KAAK,KAAK,CAAC,gBAAgB;AACzF;;;;;;ACtDA,MAAM,eAAe;CAAC;CAAkB;CAAkB;AAAiB;;;;;;;;;;;;AAa3E,eAAsB,WAA6B;CACjD,KAAK,MAAM,UAAU,cACnB,IAAI;EACF,MAAMA,SAAAA,SAAY,QAAQ,MAAM;EAChC,OAAO;CACT,QAAQ,CAER;CAGF,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,gBAAmB,IAAyC;CAChF,IAAI,CAAE,MAAM,SAAS,GAAI,OAAO;CAEhC,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AC+EA,SAAgB,OAAgB;CAC9B,OAAO,gBAAgB;AACzB;;;;AAKA,SAAgB,sBAA+B;CAC7C,OAC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k-CRm0XQPb.js";
|
|
2
|
-
import { n as OTLP_ENDPOINT } from "./constants-
|
|
2
|
+
import { n as OTLP_ENDPOINT } from "./constants-CYxk4aNm.js";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
4
|
import { promises } from "node:dns";
|
|
5
5
|
import os from "node:os";
|
|
@@ -240,4 +240,4 @@ function buildTelemetryEvent(options) {
|
|
|
240
240
|
//#endregion
|
|
241
241
|
export { canUseTTY as a, executeIfOnline as i, isTelemetryDisabled as n, isGitHubActions as o, sendTelemetry as r, buildTelemetryEvent as t };
|
|
242
242
|
|
|
243
|
-
//# sourceMappingURL=telemetry-
|
|
243
|
+
//# sourceMappingURL=telemetry-ueaMzs_c.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-ueaMzs_c.js","names":["dnsPromises","process"],"sources":["../../../internals/utils/src/env.ts","../../../internals/utils/src/network.ts","../src/telemetry.ts"],"sourcesContent":["/**\n * Returns `true` when running inside a GitHub Actions workflow.\n *\n * @example\n * ```ts\n * if (isGitHubActions()) {\n * core.setOutput('result', 'ok')\n * }\n * ```\n */\nexport function isGitHubActions(): boolean {\n return !!process.env.GITHUB_ACTIONS\n}\n\n/**\n * Returns `true` when the process is running in a CI environment.\n * Covers GitHub Actions, GitLab CI, CircleCI, Travis CI, Jenkins, Bitbucket,\n * TeamCity, Buildkite, and Azure Pipelines.\n *\n * @example\n * ```ts\n * if (isCIEnvironment()) {\n * logger.level = 'error'\n * }\n * ```\n */\nexport function isCIEnvironment(): boolean {\n return !!(\n process.env.CI ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n\n/**\n * Returns `true` when the process has an interactive TTY with a valid terminal\n * width and is not running in CI.\n *\n * Some IDE-embedded terminals report `isTTY = true` but set `columns` to `0`,\n * which breaks clack's box-drawing helpers (they call `String.prototype.repeat`\n * with a negative count and throw a `RangeError`). We therefore require a\n * positive column count before declaring the TTY usable.\n *\n * @example\n * ```ts\n * if (canUseTTY()) {\n * renderProgressBar()\n * }\n * ```\n */\nexport function canUseTTY(): boolean {\n return !!process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 && !isCIEnvironment()\n}\n","import { promises as dnsPromises } from 'node:dns'\n\n/**\n * Well-known stable domains used as DNS probes to check internet connectivity.\n */\nconst TEST_DOMAINS = ['dns.google.com', 'cloudflare.com', 'one.one.one.one'] as const\n\n/**\n * Returns `true` when the system has internet connectivity.\n * Probes DNS resolution against well-known stable domains.\n *\n * @example\n * ```ts\n * if (await isOnline()) {\n * await fetchLatestVersion()\n * }\n * ```\n */\nexport async function isOnline(): Promise<boolean> {\n for (const domain of TEST_DOMAINS) {\n try {\n await dnsPromises.resolve(domain)\n return true\n } catch {\n // Try next domain\n }\n }\n\n return false\n}\n\n/**\n * Executes `fn` only when the system is online. Returns `null` when offline or on error.\n *\n * @example\n * ```ts\n * const version = await executeIfOnline(() => fetchLatestVersion('kubb'))\n * // null when offline\n * ```\n */\nexport async function executeIfOnline<T>(fn: () => Promise<T>): Promise<T | null> {\n if (!(await isOnline())) return null\n\n try {\n return await fn()\n } catch {\n return null\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport os from 'node:os'\nimport process from 'node:process'\nimport { executeIfOnline, isCIEnvironment } from '@internals/utils'\nimport { OTLP_ENDPOINT } from './constants.ts'\n\n// OpenTelemetry OTLP JSON types\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/common/v1/common.proto\n\ntype OtlpStringValue = { stringValue: string }\ntype OtlpBoolValue = { boolValue: boolean }\ntype OtlpIntValue = { intValue: number }\ntype OtlpDoubleValue = { doubleValue: number }\ntype OtlpBytesValue = { bytesValue: string }\ntype OtlpArrayValue = { arrayValue: { values: Array<OtlpAnyValue> } }\ntype OtlpKvListValue = { kvlistValue: { values: Array<OtlpKeyValue> } }\n\ntype OtlpAnyValue = OtlpStringValue | OtlpBoolValue | OtlpIntValue | OtlpDoubleValue | OtlpBytesValue | OtlpArrayValue | OtlpKvListValue\n\ntype OtlpKeyValue = {\n key: string\n value: OtlpAnyValue\n}\n\ntype OtlpResource = {\n attributes: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpInstrumentationScope = {\n name: string\n version?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\n/** https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto#L103 */\ntype OtlpSpanKind = 0 | 1 | 2 | 3 | 4 | 5\n\n/** 0 = STATUS_CODE_UNSET, 1 = STATUS_CODE_OK, 2 = STATUS_CODE_ERROR */\ntype OtlpStatusCode = 0 | 1 | 2\n\ntype OtlpStatus = {\n code: OtlpStatusCode\n message?: string\n}\n\ntype OtlpSpan = {\n traceId: string\n spanId: string\n traceState?: string\n parentSpanId?: string\n name: string\n kind: OtlpSpanKind\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n events?: Array<OtlpSpanEvent>\n droppedEventsCount?: number\n links?: Array<OtlpSpanLink>\n droppedLinksCount?: number\n status?: OtlpStatus\n}\n\ntype OtlpSpanEvent = {\n timeUnixNano: string\n name: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpSpanLink = {\n traceId: string\n spanId: string\n traceState?: string\n attributes?: Array<OtlpKeyValue>\n droppedAttributesCount?: number\n}\n\ntype OtlpScopeSpans = {\n scope: OtlpInstrumentationScope\n spans: Array<OtlpSpan>\n schemaUrl?: string\n}\n\ntype OtlpResourceSpans = {\n resource: OtlpResource\n scopeSpans: Array<OtlpScopeSpans>\n schemaUrl?: string\n}\n\n/** Root payload sent to POST /v1/traces */\ntype OtlpExportTraceServiceRequest = {\n resourceSpans: Array<OtlpResourceSpans>\n}\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 plugin options snapshot, values are included but cannot be traced back to the user.\n */\n options: Record<string, unknown>\n}\n\ntype TelemetryEvent = {\n command: string\n kubbVersion: string\n nodeVersion: string\n platform: string\n ci: boolean\n plugins: Array<TelemetryPlugin>\n duration: number\n filesCreated: number\n status: 'success' | 'failed'\n}\n\n/**\n * Returns `true` when the current process runs inside a CI environment.\n */\nexport function isCi(): boolean {\n return isCIEnvironment()\n}\n\n/**\n * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n process.env['DO_NOT_TRACK'] === '1' ||\n process.env['DO_NOT_TRACK'] === 'true' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === '1' ||\n process.env['KUBB_DISABLE_TELEMETRY'] === 'true'\n )\n}\n\n/**\n * Convert a TelemetryEvent into an OTLP-compatible JSON trace payload.\n * See https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/\n */\nexport function buildOtlpPayload(event: TelemetryEvent): OtlpExportTraceServiceRequest {\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(event.duration) * 1_000_000n\n\n const attributes: Array<OtlpKeyValue> = [\n { key: 'kubb.command', value: { stringValue: event.command } },\n { key: 'kubb.version', value: { stringValue: event.kubbVersion } },\n { key: 'kubb.node_version', value: { stringValue: event.nodeVersion } },\n { key: 'kubb.platform', value: { stringValue: event.platform } },\n { key: 'kubb.ci', value: { boolValue: event.ci } },\n { key: 'kubb.files_created', value: { intValue: event.filesCreated } },\n { key: 'kubb.status', value: { stringValue: event.status } },\n {\n key: 'kubb.plugins',\n value: {\n arrayValue: {\n values: event.plugins.map(\n (p): OtlpKvListValue => ({\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\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: 'service.name', value: { stringValue: 'kubb-cli' } },\n {\n key: 'service.version',\n value: { stringValue: event.kubbVersion },\n },\n { key: 'telemetry.sdk.language', value: { stringValue: 'nodejs' } },\n ],\n },\n scopeSpans: [\n {\n scope: { name: 'kubb-cli', version: event.kubbVersion },\n spans: [\n {\n traceId,\n spanId,\n name: event.command,\n kind: 1 satisfies OtlpSpanKind,\n startTimeUnixNano: String(startTimeNs),\n endTimeUnixNano: String(endTimeNs),\n attributes,\n status: {\n code: (event.status === 'success' ? 1 : 2) satisfies OtlpStatusCode,\n },\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Send an anonymous telemetry event to the Kubb OTLP endpoint.\n * Respects DO_NOT_TRACK and KUBB_DISABLE_TELEMETRY environment variables.\n * Fails silently to never interrupt the generation process.\n */\nexport async function sendTelemetry(event: TelemetryEvent): Promise<void> {\n if (isTelemetryDisabled()) {\n return\n }\n\n await executeIfOnline(async () => {\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(buildOtlpPayload(event)),\n signal: AbortSignal.timeout(5_000),\n })\n } catch (_e) {\n // Fail silently, telemetry must never break the CLI\n }\n })\n}\n\n/**\n * Build an anonymous telemetry payload from a completed generation run.\n * No file paths, OpenAPI specs, or secrets are included.\n */\nexport function buildTelemetryEvent(options: {\n command: 'generate' | 'mcp' | 'validate' | 'agent'\n kubbVersion: string\n plugins?: Array<TelemetryPlugin>\n hrStart: [number, number]\n filesCreated?: number\n status: 'success' | 'failed'\n}): TelemetryEvent {\n const [seconds, nanoseconds] = process.hrtime(options.hrStart)\n const duration = Math.round(seconds * 1000 + nanoseconds / 1e6)\n\n return {\n command: options.command,\n kubbVersion: options.kubbVersion,\n nodeVersion: process.versions.node.split('.')[0] as string,\n platform: os.platform(),\n ci: isCi(),\n plugins: options.plugins ?? [],\n duration,\n filesCreated: options.filesCreated ?? 0,\n status: options.status,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAUA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,CAAC,QAAQ,IAAI;AACvB;;;;;;;;;;;;;AAcA,SAAgB,kBAA2B;CACzC,OAAO,CAAC,EACN,QAAQ,IAAI,MACZ,QAAQ,IAAI,kBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI,0BACZ,QAAQ,IAAI,eACZ,QAAQ,IAAI,YACZ,QAAQ,IAAI,UACZ,QAAQ,IAAI,oBACZ,QAAQ,IAAI,aACZ,QAAQ,IAAI;AAEhB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YAAqB;CACnC,OAAO,CAAC,CAAC,QAAQ,OAAO,UAAU,QAAQ,OAAO,WAAW,KAAK,KAAK,CAAC,gBAAgB;AACzF;;;;;;ACtDA,MAAM,eAAe;CAAC;CAAkB;CAAkB;AAAiB;;;;;;;;;;;;AAa3E,eAAsB,WAA6B;CACjD,KAAK,MAAM,UAAU,cACnB,IAAI;EACF,MAAMA,SAAY,QAAQ,MAAM;EAChC,OAAO;CACT,QAAQ,CAER;CAGF,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,gBAAmB,IAAyC;CAChF,IAAI,CAAE,MAAM,SAAS,GAAI,OAAO;CAEhC,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AC+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XQPb.js";
|
|
2
2
|
import { n as defineCommand } from "./define-DNG1U8ha.js";
|
|
3
|
-
import { t as version } from "./package-
|
|
3
|
+
import { t as version } from "./package-Cnt1K03J.js";
|
|
4
4
|
//#region src/commands/validate.ts
|
|
5
5
|
const command = defineCommand({
|
|
6
6
|
name: "validate",
|
|
@@ -13,7 +13,7 @@ const command = defineCommand({
|
|
|
13
13
|
required: true
|
|
14
14
|
} },
|
|
15
15
|
async run({ values }) {
|
|
16
|
-
const { run } = await import("./run-
|
|
16
|
+
const { run } = await import("./run-BFEK9md9.js");
|
|
17
17
|
await run({
|
|
18
18
|
input: values.input,
|
|
19
19
|
version
|
|
@@ -23,4 +23,4 @@ const command = defineCommand({
|
|
|
23
23
|
//#endregion
|
|
24
24
|
export { command };
|
|
25
25
|
|
|
26
|
-
//# sourceMappingURL=validate-
|
|
26
|
+
//# sourceMappingURL=validate-CYTKdezO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-
|
|
1
|
+
{"version":3,"file":"validate-CYTKdezO.js","names":[],"sources":["../src/commands/validate.ts"],"sourcesContent":["import { defineCommand } from '@internals/utils'\nimport { version } from '../../package.json'\n\nexport const command = defineCommand({\n name: 'validate',\n description:\n 'Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.',\n examples: ['kubb validate --input ./openapi.yaml', 'kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json'],\n options: {\n input: {\n type: 'string',\n description: 'Path or URL to the OpenAPI/Swagger file to validate',\n short: 'i',\n required: true,\n },\n },\n async run({ values }) {\n const { run } = await import('../runners/validate/run.ts')\n\n await run({ input: values.input, version })\n },\n})\n"],"mappings":";;;;AAGA,MAAa,UAAU,cAAc;CACnC,MAAM;CACN,aACE;CACF,UAAU,CAAC,wCAAwC,wEAAwE;CAC3H,SAAS,EACP,OAAO;EACL,MAAM;EACN,aAAa;EACb,OAAO;EACP,UAAU;CACZ,EACF;CACA,MAAM,IAAI,EAAE,UAAU;EACpB,MAAM,EAAE,QAAQ,MAAM,OAAO;EAE7B,MAAM,IAAI;GAAE,OAAO,OAAO;GAAO;EAAQ,CAAC;CAC5C;AACF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
require("./chunk-Bx3C2hgW.cjs");
|
|
2
2
|
const require_define = require("./define-C4AB3POr.cjs");
|
|
3
|
-
const require_package = require("./package-
|
|
3
|
+
const require_package = require("./package-guApEHiW.cjs");
|
|
4
4
|
//#region src/commands/validate.ts
|
|
5
5
|
const command = require_define.defineCommand({
|
|
6
6
|
name: "validate",
|
|
@@ -13,7 +13,7 @@ const command = require_define.defineCommand({
|
|
|
13
13
|
required: true
|
|
14
14
|
} },
|
|
15
15
|
async run({ values }) {
|
|
16
|
-
const { run } = await Promise.resolve().then(() => require("./run-
|
|
16
|
+
const { run } = await Promise.resolve().then(() => require("./run-Bz9IFMWg.cjs"));
|
|
17
17
|
await run({
|
|
18
18
|
input: values.input,
|
|
19
19
|
version: require_package.version
|
|
@@ -23,4 +23,4 @@ const command = require_define.defineCommand({
|
|
|
23
23
|
//#endregion
|
|
24
24
|
exports.command = command;
|
|
25
25
|
|
|
26
|
-
//# sourceMappingURL=validate-
|
|
26
|
+
//# sourceMappingURL=validate-DMzjP-hd.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-
|
|
1
|
+
{"version":3,"file":"validate-DMzjP-hd.cjs","names":["defineCommand"],"sources":["../src/commands/validate.ts"],"sourcesContent":["import { defineCommand } from '@internals/utils'\nimport { version } from '../../package.json'\n\nexport const command = defineCommand({\n name: 'validate',\n description:\n 'Parse and validate an OpenAPI/Swagger file for structural correctness. Reports schema errors, missing required fields, and malformed references. Use this before running generate to catch spec issues early.',\n examples: ['kubb validate --input ./openapi.yaml', 'kubb validate --input https://petstore3.swagger.io/api/v3/openapi.json'],\n options: {\n input: {\n type: 'string',\n description: 'Path or URL to the OpenAPI/Swagger file to validate',\n short: 'i',\n required: true,\n },\n },\n async run({ values }) {\n const { run } = await import('../runners/validate/run.ts')\n\n await run({ input: values.input, version })\n },\n})\n"],"mappings":";;;;AAGA,MAAa,UAAUA,eAAAA,cAAc;CACnC,MAAM;CACN,aACE;CACF,UAAU,CAAC,wCAAwC,wEAAwE;CAC3H,SAAS,EACP,OAAO;EACL,MAAM;EACN,aAAa;EACb,OAAO;EACP,UAAU;CACZ,EACF;CACA,MAAM,IAAI,EAAE,UAAU;EACpB,MAAM,EAAE,QAAQ,MAAA,QAAA,QAAA,EAAA,WAAA,QAAM,oBAAA,CAAA;EAEtB,MAAM,IAAI;GAAE,OAAO,OAAO;GAAO,SAAA,gBAAA;EAAQ,CAAC;CAC5C;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/cli",
|
|
3
|
-
"version": "5.0.0-beta.
|
|
3
|
+
"version": "5.0.0-beta.38",
|
|
4
4
|
"description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb mcp, and kubb agent to manage the full code generation lifecycle from OpenAPI/Swagger specs.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -52,17 +52,17 @@
|
|
|
52
52
|
"cosmiconfig": "^9.0.1",
|
|
53
53
|
"jiti": "^2.7.0",
|
|
54
54
|
"tinyexec": "~1.1.2",
|
|
55
|
-
"@kubb/core": "5.0.0-beta.
|
|
55
|
+
"@kubb/core": "5.0.0-beta.38"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@internals/shared": "0.0.0",
|
|
59
59
|
"@internals/utils": "0.0.0",
|
|
60
|
-
"@kubb/adapter-oas": "5.0.0-beta.
|
|
60
|
+
"@kubb/adapter-oas": "5.0.0-beta.38"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
|
-
"@kubb/adapter-oas": "5.0.0-beta.
|
|
64
|
-
"@kubb/agent": "5.0.0-beta.
|
|
65
|
-
"@kubb/mcp": "5.0.0-beta.
|
|
63
|
+
"@kubb/adapter-oas": "5.0.0-beta.38",
|
|
64
|
+
"@kubb/agent": "5.0.0-beta.38",
|
|
65
|
+
"@kubb/mcp": "5.0.0-beta.38"
|
|
66
66
|
},
|
|
67
67
|
"peerDependenciesMeta": {
|
|
68
68
|
"@kubb/adapter-oas": {
|
package/src/commands/generate.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineCommand } from '@internals/utils'
|
|
2
|
+
import type { ReporterName } from '@kubb/core'
|
|
2
3
|
|
|
3
4
|
export const command = defineCommand({
|
|
4
5
|
name: 'generate',
|
|
@@ -14,11 +15,11 @@ export const command = defineCommand({
|
|
|
14
15
|
},
|
|
15
16
|
logLevel: {
|
|
16
17
|
type: 'string',
|
|
17
|
-
description: 'Info, silent
|
|
18
|
+
description: 'Info, silent or verbose',
|
|
18
19
|
short: 'l',
|
|
19
20
|
default: 'info',
|
|
20
|
-
hint: 'silent|info|verbose
|
|
21
|
-
enum: ['silent', 'info', 'verbose'
|
|
21
|
+
hint: 'silent|info|verbose',
|
|
22
|
+
enum: ['silent', 'info', 'verbose'],
|
|
22
23
|
},
|
|
23
24
|
watch: {
|
|
24
25
|
type: 'boolean',
|
|
@@ -26,12 +27,6 @@ export const command = defineCommand({
|
|
|
26
27
|
short: 'w',
|
|
27
28
|
default: false,
|
|
28
29
|
},
|
|
29
|
-
debug: {
|
|
30
|
-
type: 'boolean',
|
|
31
|
-
description: 'Override logLevel to debug',
|
|
32
|
-
short: 'd',
|
|
33
|
-
default: false,
|
|
34
|
-
},
|
|
35
30
|
verbose: {
|
|
36
31
|
type: 'boolean',
|
|
37
32
|
description: 'Override logLevel to verbose',
|
|
@@ -44,9 +39,19 @@ export const command = defineCommand({
|
|
|
44
39
|
short: 's',
|
|
45
40
|
default: false,
|
|
46
41
|
},
|
|
42
|
+
reporter: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
description: 'Reporters that render the run, comma-separated. Overrides config.reporters',
|
|
45
|
+
hint: 'cli|json|file',
|
|
46
|
+
enum: ['cli', 'json', 'file'],
|
|
47
|
+
},
|
|
47
48
|
},
|
|
48
49
|
async run({ values, positionals }) {
|
|
49
|
-
const logLevel = values.
|
|
50
|
+
const logLevel = values.verbose ? 'verbose' : values.silent ? 'silent' : values.logLevel
|
|
51
|
+
const reporters = values.reporter
|
|
52
|
+
?.split(',')
|
|
53
|
+
.map((name) => name.trim())
|
|
54
|
+
.filter(Boolean) as Array<ReporterName> | undefined
|
|
50
55
|
const { run } = await import('../runners/generate/run.ts')
|
|
51
56
|
|
|
52
57
|
await run({
|
|
@@ -54,6 +59,7 @@ export const command = defineCommand({
|
|
|
54
59
|
configPath: values.config,
|
|
55
60
|
logLevel,
|
|
56
61
|
watch: values.watch,
|
|
62
|
+
reporters,
|
|
57
63
|
})
|
|
58
64
|
},
|
|
59
65
|
})
|
package/src/constants.ts
CHANGED
|
@@ -31,7 +31,7 @@ export const SUMMARY_TIME_SCALE_DIVISOR = 100 as const
|
|
|
31
31
|
export const WATCHER_IGNORED_PATHS = '**/{.git,node_modules}/**' as const
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
|
-
* Flags that short-circuit execution (help/version)
|
|
34
|
+
* Flags that short-circuit execution (help/version), no telemetry notice is shown.
|
|
35
35
|
*/
|
|
36
36
|
export const QUIET_FLAGS = new Set(['--help', '-h', '--version', '-v'] as const)
|
|
37
37
|
|
|
@@ -2,9 +2,9 @@ import { relative } from 'node:path'
|
|
|
2
2
|
import process from 'node:process'
|
|
3
3
|
import { styleText } from 'node:util'
|
|
4
4
|
import * as clack from '@clack/prompts'
|
|
5
|
-
import {
|
|
6
|
-
import { defineLogger, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'
|
|
7
|
-
import {
|
|
5
|
+
import { formatMsWithColor, getElapsedMs, getIntro, toCause } from '@internals/utils'
|
|
6
|
+
import { defineLogger, isUpdateDiagnostic, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'
|
|
7
|
+
import { diagnosticDetails, diagnosticHeadline, diagnosticSymbol } from './diagnostics.ts'
|
|
8
8
|
import { buildProgressLine, createProgressCounters, formatCommandWithArgs, formatMessage, recordPluginResult, resetProgressCounters } from './utils.ts'
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -18,25 +18,38 @@ export const clackLogger = defineLogger({
|
|
|
18
18
|
...createProgressCounters(),
|
|
19
19
|
spinner: clack.spinner(),
|
|
20
20
|
isSpinning: false,
|
|
21
|
+
runningPlugins: new Set<string>(),
|
|
21
22
|
activeProgress: new Map<string, { interval?: NodeJS.Timeout; progressBar: clack.ProgressResult }>(),
|
|
22
23
|
activeHookLogs: new Map<string, { taskLog: ReturnType<typeof clack.taskLog>; hrStart: [number, number] }>(),
|
|
23
24
|
}
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
// Clear every active progress bar's interval, stop it, and drop the map.
|
|
27
|
+
function stopActiveProgress() {
|
|
28
|
+
for (const [, active] of state.activeProgress) {
|
|
27
29
|
if (active.interval) {
|
|
28
30
|
clearInterval(active.interval)
|
|
29
31
|
}
|
|
30
32
|
active.progressBar?.stop()
|
|
31
33
|
}
|
|
34
|
+
state.activeProgress.clear()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function reset() {
|
|
38
|
+
stopActiveProgress()
|
|
32
39
|
|
|
33
40
|
resetProgressCounters(state)
|
|
34
41
|
state.spinner = clack.spinner()
|
|
35
42
|
state.isSpinning = false
|
|
36
|
-
state.
|
|
43
|
+
state.runningPlugins.clear()
|
|
37
44
|
state.activeHookLogs.clear()
|
|
38
45
|
}
|
|
39
46
|
|
|
47
|
+
// Label for the shared plugin bar, listing the plugins currently generating.
|
|
48
|
+
function pluginProgressText(): string {
|
|
49
|
+
const running = [...state.runningPlugins].map((name) => styleText('bold', name))
|
|
50
|
+
return getMessage(running.length > 0 ? `Generating ${running.join(', ')}` : 'Generating plugins')
|
|
51
|
+
}
|
|
52
|
+
|
|
40
53
|
function showProgressStep() {
|
|
41
54
|
if (logLevel <= logLevelMap.silent) {
|
|
42
55
|
return
|
|
@@ -80,7 +93,7 @@ export const clackLogger = defineLogger({
|
|
|
80
93
|
return
|
|
81
94
|
}
|
|
82
95
|
|
|
83
|
-
const text = getMessage([styleText('blue', 'ℹ'), message, styleText('dim', info)].join(' '))
|
|
96
|
+
const text = getMessage([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))
|
|
84
97
|
|
|
85
98
|
if (state.isSpinning) {
|
|
86
99
|
state.spinner.message(text)
|
|
@@ -126,8 +139,8 @@ export const clackLogger = defineLogger({
|
|
|
126
139
|
}
|
|
127
140
|
clack.log.error(getMessage(text))
|
|
128
141
|
|
|
129
|
-
// Show stack trace in
|
|
130
|
-
if (logLevel >= logLevelMap.
|
|
142
|
+
// Show stack trace in verbose mode (first 3 frames)
|
|
143
|
+
if (logLevel >= logLevelMap.verbose && error.stack) {
|
|
131
144
|
const frames = error.stack.split('\n').slice(1, 4)
|
|
132
145
|
for (const frame of frames) {
|
|
133
146
|
clack.log.message(getMessage(styleText('dim', frame.trim())))
|
|
@@ -144,14 +157,21 @@ export const clackLogger = defineLogger({
|
|
|
144
157
|
}
|
|
145
158
|
})
|
|
146
159
|
|
|
147
|
-
context.on('kubb:
|
|
148
|
-
|
|
160
|
+
context.on('kubb:diagnostic', ({ diagnostic }) => {
|
|
161
|
+
// Silent still surfaces errors so failures stay visible. It drops warnings and info.
|
|
162
|
+
if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {
|
|
149
163
|
return
|
|
150
164
|
}
|
|
151
165
|
|
|
152
|
-
|
|
166
|
+
stopSpinner()
|
|
167
|
+
|
|
168
|
+
// Stop any lingering progress UI so the multi-line block renders cleanly.
|
|
169
|
+
stopActiveProgress()
|
|
170
|
+
|
|
171
|
+
// The version-update notice keeps its own framed box instead of the diagnostic gutter.
|
|
172
|
+
if (isUpdateDiagnostic(diagnostic)) {
|
|
153
173
|
clack.box(
|
|
154
|
-
`\`v${currentVersion}\` → \`v${latestVersion}\`
|
|
174
|
+
`\`v${diagnostic.currentVersion}\` → \`v${diagnostic.latestVersion}\`
|
|
155
175
|
Run \`npm install -g @kubb/cli\` to update`,
|
|
156
176
|
'Update available for `Kubb`',
|
|
157
177
|
{
|
|
@@ -163,14 +183,20 @@ Run \`npm install -g @kubb/cli\` to update`,
|
|
|
163
183
|
titleAlign: 'center',
|
|
164
184
|
},
|
|
165
185
|
)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
console.log('Run `npm install -g @kubb/cli` to update')
|
|
186
|
+
|
|
187
|
+
return
|
|
169
188
|
}
|
|
189
|
+
|
|
190
|
+
// Hand the severity glyph to clack as the gutter `symbol`, then let it draw the
|
|
191
|
+
// bar on each detail line via the default `secondarySymbol`. The headline and
|
|
192
|
+
// details carry their own colors, so clack only owns the gutter.
|
|
193
|
+
clack.log.message([diagnosticHeadline(diagnostic), ...diagnosticDetails(diagnostic)], {
|
|
194
|
+
symbol: diagnosticSymbol(diagnostic.severity),
|
|
195
|
+
})
|
|
170
196
|
})
|
|
171
197
|
|
|
172
198
|
context.on('kubb:lifecycle:start', async ({ version }) => {
|
|
173
|
-
console.log(`\n${getIntro({ title: 'The
|
|
199
|
+
console.log(`\n${getIntro({ title: 'The meta framework for code generation', description: 'Ready to start', version, areEyesOpen: true })}\n`)
|
|
174
200
|
|
|
175
201
|
reset()
|
|
176
202
|
})
|
|
@@ -211,6 +237,8 @@ Run \`npm install -g @kubb/cli\` to update`,
|
|
|
211
237
|
clack.intro(text)
|
|
212
238
|
})
|
|
213
239
|
|
|
240
|
+
// Plugins run concurrently, so they share a single progress bar. A bar per plugin
|
|
241
|
+
// would make clack render them side by side and pile up keypress listeners.
|
|
214
242
|
context.on('kubb:plugin:start', ({ plugin }) => {
|
|
215
243
|
if (logLevel <= logLevelMap.silent) {
|
|
216
244
|
return
|
|
@@ -218,46 +246,44 @@ Run \`npm install -g @kubb/cli\` to update`,
|
|
|
218
246
|
|
|
219
247
|
stopSpinner()
|
|
220
248
|
|
|
249
|
+
state.runningPlugins.add(plugin.name)
|
|
250
|
+
|
|
251
|
+
const active = state.activeProgress.get('plugins')
|
|
252
|
+
if (active) {
|
|
253
|
+
active.progressBar.advance(0, pluginProgressText())
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
|
|
221
257
|
const progressBar = clack.progress({
|
|
222
258
|
style: 'block',
|
|
223
|
-
max:
|
|
259
|
+
max: Math.max(state.totalPlugins, 1),
|
|
224
260
|
size: 30,
|
|
225
261
|
})
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
progressBar.advance()
|
|
231
|
-
}, 100)
|
|
232
|
-
|
|
233
|
-
state.activeProgress.set(plugin.name, { progressBar, interval })
|
|
262
|
+
progressBar.start(pluginProgressText())
|
|
263
|
+
// Catch up to plugins already finished before this bar opened.
|
|
264
|
+
progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText())
|
|
265
|
+
state.activeProgress.set('plugins', { progressBar })
|
|
234
266
|
})
|
|
235
267
|
|
|
236
|
-
context.on('kubb:plugin:end', ({ plugin,
|
|
268
|
+
context.on('kubb:plugin:end', ({ plugin, success }) => {
|
|
237
269
|
stopSpinner()
|
|
238
270
|
|
|
239
|
-
const active = state.activeProgress.get(
|
|
271
|
+
const active = state.activeProgress.get('plugins')
|
|
240
272
|
|
|
241
273
|
if (!active || logLevel === logLevelMap.silent) {
|
|
242
274
|
return
|
|
243
275
|
}
|
|
244
276
|
|
|
245
|
-
|
|
246
|
-
|
|
277
|
+
state.runningPlugins.delete(plugin.name)
|
|
247
278
|
recordPluginResult(state, success)
|
|
279
|
+
active.progressBar.advance(1, pluginProgressText())
|
|
248
280
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
active.progressBar.stop(text)
|
|
257
|
-
state.activeProgress.delete(plugin.name)
|
|
258
|
-
|
|
259
|
-
// Show progress step after each plugin
|
|
260
|
-
showProgressStep()
|
|
281
|
+
// Close the bar once nothing is generating, then print the progress step.
|
|
282
|
+
if (state.runningPlugins.size === 0) {
|
|
283
|
+
active.progressBar.stop(getMessage('Plugins generated'))
|
|
284
|
+
state.activeProgress.delete('plugins')
|
|
285
|
+
showProgressStep()
|
|
286
|
+
}
|
|
261
287
|
})
|
|
262
288
|
|
|
263
289
|
context.on('kubb:files:processing:start', ({ files }) => {
|
|
@@ -366,35 +392,6 @@ Run \`npm install -g @kubb/cli\` to update`,
|
|
|
366
392
|
}
|
|
367
393
|
})
|
|
368
394
|
|
|
369
|
-
context.on('kubb:generation:summary', ({ config, pluginTimings, failedPlugins, filesCreated, status, hrStart }) => {
|
|
370
|
-
const summary = getSummary({
|
|
371
|
-
failedPlugins,
|
|
372
|
-
filesCreated,
|
|
373
|
-
config,
|
|
374
|
-
status,
|
|
375
|
-
hrStart,
|
|
376
|
-
pluginTimings: logLevel >= logLevelMap.verbose ? pluginTimings : undefined,
|
|
377
|
-
})
|
|
378
|
-
const title = config.name || ''
|
|
379
|
-
|
|
380
|
-
summary.unshift('\n')
|
|
381
|
-
summary.push('\n')
|
|
382
|
-
|
|
383
|
-
const borderColor = status === 'success' ? 'green' : 'red'
|
|
384
|
-
try {
|
|
385
|
-
clack.box(summary.join('\n'), getMessage(title), {
|
|
386
|
-
width: 'auto',
|
|
387
|
-
formatBorder: (s: string) => styleText(borderColor, s),
|
|
388
|
-
rounded: true,
|
|
389
|
-
withGuide: false,
|
|
390
|
-
contentAlign: 'left',
|
|
391
|
-
titleAlign: 'center',
|
|
392
|
-
})
|
|
393
|
-
} catch {
|
|
394
|
-
console.log(summary.join('\n'))
|
|
395
|
-
}
|
|
396
|
-
})
|
|
397
|
-
|
|
398
395
|
context.on('kubb:lifecycle:end', () => {
|
|
399
396
|
reset()
|
|
400
397
|
})
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { styleText } from 'node:util'
|
|
2
|
+
import { type Diagnostic, diagnosticCode, Diagnostics, type DiagnosticSeverity, isProblemDiagnostic } from '@kubb/core'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Glyph and accent color per severity, matching the miette/oxlint convention
|
|
6
|
+
* (`×` error, `⚠` warning, `ℹ` advice).
|
|
7
|
+
*/
|
|
8
|
+
const severityStyle: Record<DiagnosticSeverity, { glyph: string; color: 'red' | 'yellow' | 'blue' }> = {
|
|
9
|
+
error: { glyph: '×', color: 'red' },
|
|
10
|
+
warning: { glyph: '⚠', color: 'yellow' },
|
|
11
|
+
info: { glyph: 'ℹ', color: 'blue' },
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The colored, bold severity glyph (`×`, `⚠`, `ℹ`) on its own. Pass it as clack's
|
|
16
|
+
* `symbol` so clack owns the gutter and adds the bar to the continuation lines,
|
|
17
|
+
* instead of baking the glyph into the message text.
|
|
18
|
+
*/
|
|
19
|
+
export function diagnosticSymbol(severity: DiagnosticSeverity): string {
|
|
20
|
+
const { glyph, color } = severityStyle[severity]
|
|
21
|
+
return styleText(color, styleText('bold', glyph))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The `plugin(CODE): message` headline, without the leading severity glyph.
|
|
26
|
+
*/
|
|
27
|
+
export function diagnosticHeadline(diagnostic: Diagnostic): string {
|
|
28
|
+
const { code, severity, message } = diagnostic
|
|
29
|
+
const plugin = isProblemDiagnostic(diagnostic) ? diagnostic.plugin : undefined
|
|
30
|
+
const { color } = severityStyle[severity]
|
|
31
|
+
|
|
32
|
+
const rule = styleText(color, styleText('bold', plugin ? `${plugin}(${code})` : code))
|
|
33
|
+
return `${rule}: ${message}`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The detail lines below the headline: optional `at <pointer>`, `help:`, and
|
|
38
|
+
* `docs:`. OpenAPI has no line/column, so the location is the JSON pointer the
|
|
39
|
+
* adapter built. Each line keeps a two-space indent so it sits under the headline.
|
|
40
|
+
*/
|
|
41
|
+
export function diagnosticDetails(diagnostic: Diagnostic): Array<string> {
|
|
42
|
+
const { code } = diagnostic
|
|
43
|
+
const problem = isProblemDiagnostic(diagnostic) ? diagnostic : undefined
|
|
44
|
+
const location = problem?.location
|
|
45
|
+
const help = problem?.help
|
|
46
|
+
const lines: Array<string> = []
|
|
47
|
+
|
|
48
|
+
if (location && 'pointer' in location) {
|
|
49
|
+
lines.push(` ${styleText('dim', 'at')} ${styleText('cyan', location.pointer)}`)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (help) {
|
|
53
|
+
lines.push(` ${styleText('cyan', 'help:')} ${help}`)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (code !== diagnosticCode.unknown) {
|
|
57
|
+
lines.push(` ${styleText('dim', 'docs:')} ${styleText('cyan', Diagnostics.docsUrl(code))}`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return lines
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Renders a {@link Diagnostic} in the oxlint style as a self-contained block: a
|
|
65
|
+
* `× plugin(CODE): message` header followed by the {@link diagnosticDetails}.
|
|
66
|
+
* Use this where clack's gutter is not available (plain, file output); clack
|
|
67
|
+
* loggers pass {@link diagnosticSymbol}, {@link diagnosticHeadline}, and
|
|
68
|
+
* {@link diagnosticDetails} to `clack.log.message` instead.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* formatDiagnostic({ code: 'KUBB_REF_NOT_FOUND', severity: 'error', message: 'Could not find Pet', help: 'Add Pet under components.schemas.', plugin: '@kubb/plugin-zod', location: { kind: 'schema', pointer: '#/components/schemas/Pet' } })
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export function formatDiagnostic(diagnostic: Diagnostic): Array<string> {
|
|
76
|
+
return [`${diagnosticSymbol(diagnostic.severity)} ${diagnosticHeadline(diagnostic)}`, ...diagnosticDetails(diagnostic)]
|
|
77
|
+
}
|