@kubb/cli 5.2.8 → 5.3.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-DIDDCARm.js → Telemetry-CJcQkQOT.js} +2 -2
- package/dist/Telemetry-CJcQkQOT.js.map +1 -0
- package/dist/{Telemetry-C-y1OMHs.cjs → Telemetry-CvHQevSK.cjs} +4 -4
- package/dist/Telemetry-CvHQevSK.cjs.map +1 -0
- package/dist/agent-3JmkMghp.js +24 -0
- package/dist/agent-3JmkMghp.js.map +1 -0
- package/dist/agent-BPqs9VRj.cjs +36 -0
- package/dist/agent-BPqs9VRj.cjs.map +1 -0
- package/dist/{generate-Bg8-2XSd.cjs → generate-CCjNi8-B.cjs} +6 -5
- package/dist/generate-CCjNi8-B.cjs.map +1 -0
- package/dist/{generate-CKsAI5H2.js → generate-DnOsvKdA.js} +6 -5
- package/dist/generate-DnOsvKdA.js.map +1 -0
- package/dist/index.cjs +7 -7
- package/dist/index.js +7 -7
- package/dist/{init-BPArhQCK.cjs → init-BEZE-TU-.cjs} +3 -3
- package/dist/{init-BPArhQCK.cjs.map → init-BEZE-TU-.cjs.map} +1 -1
- package/dist/{init-DroN6dri.js → init-DFBbp97w.js} +3 -3
- package/dist/{init-DroN6dri.js.map → init-DFBbp97w.js.map} +1 -1
- package/dist/{output-LZvrgF3z.js → output-DH2Uoy4x.js} +32 -3
- package/dist/output-DH2Uoy4x.js.map +1 -0
- package/dist/{output-B2V2MN_C.cjs → output-kmklyYIv.cjs} +42 -7
- package/dist/output-kmklyYIv.cjs.map +1 -0
- package/dist/package-DYdGw7-C.js +6 -0
- package/dist/package-DYdGw7-C.js.map +1 -0
- package/dist/{package-BMZZ3mUo.cjs → package-DgNWnCoo.cjs} +2 -2
- package/dist/package-DgNWnCoo.cjs.map +1 -0
- package/dist/{run-CphhWHm6.js → run-B1-xSKKe.js} +3 -3
- package/dist/{run-CphhWHm6.js.map → run-B1-xSKKe.js.map} +1 -1
- package/dist/{run-Cni7891O.cjs → run-BWahaRPU.cjs} +3 -3
- package/dist/{run-Cni7891O.cjs.map → run-BWahaRPU.cjs.map} +1 -1
- package/dist/{run-DL1wCsGn.cjs → run-Bh9GxeT8.cjs} +6 -7
- package/dist/{run-DL1wCsGn.cjs.map → run-Bh9GxeT8.cjs.map} +1 -1
- package/dist/{run-DoU73Qo5.cjs → run-BwMRCeWt.cjs} +3 -3
- package/dist/{run-DoU73Qo5.cjs.map → run-BwMRCeWt.cjs.map} +1 -1
- package/dist/{run-BHMES-2P.cjs → run-CDLUop5s.cjs} +51 -36
- package/dist/run-CDLUop5s.cjs.map +1 -0
- package/dist/{run-BcEQGlz_.js → run-CIkCVMy_.js} +3 -3
- package/dist/{run-BcEQGlz_.js.map → run-CIkCVMy_.js.map} +1 -1
- package/dist/{run-B6bZaLqK.js → run-CZaUf7i2.js} +48 -33
- package/dist/run-CZaUf7i2.js.map +1 -0
- package/dist/{run-SxqXLbrs.js → run-DiL672xB.js} +6 -7
- package/dist/{run-SxqXLbrs.js.map → run-DiL672xB.js.map} +1 -1
- package/dist/{run-DRBqVXX0.cjs → run-VK50TiB7.cjs} +2 -2
- package/dist/{run-DRBqVXX0.cjs.map → run-VK50TiB7.cjs.map} +1 -1
- package/dist/{run-BzvsJ0Ek.js → run-kdxqOL8u.js} +2 -2
- package/dist/{run-BzvsJ0Ek.js.map → run-kdxqOL8u.js.map} +1 -1
- package/dist/{utils-BgEQilnN.cjs → utils-CMU1rLfY.cjs} +22 -6
- package/dist/utils-CMU1rLfY.cjs.map +1 -0
- package/dist/{utils-VadUNZOm.js → utils-s6yetN6W.js} +21 -5
- package/dist/utils-s6yetN6W.js.map +1 -0
- package/package.json +7 -7
- package/dist/Telemetry-C-y1OMHs.cjs.map +0 -1
- package/dist/Telemetry-DIDDCARm.js.map +0 -1
- package/dist/env-DHaFBZTX.cjs +0 -82
- package/dist/env-DHaFBZTX.cjs.map +0 -1
- package/dist/env-DqPKEL59.js +0 -59
- package/dist/env-DqPKEL59.js.map +0 -1
- package/dist/generate-Bg8-2XSd.cjs.map +0 -1
- package/dist/generate-CKsAI5H2.js.map +0 -1
- package/dist/output-B2V2MN_C.cjs.map +0 -1
- package/dist/output-LZvrgF3z.js.map +0 -1
- package/dist/package-BMZZ3mUo.cjs.map +0 -1
- package/dist/package-BXaDNEkt.js +0 -6
- package/dist/package-BXaDNEkt.js.map +0 -1
- package/dist/run-B6bZaLqK.js.map +0 -1
- package/dist/run-BHMES-2P.cjs.map +0 -1
- package/dist/utils-BgEQilnN.cjs.map +0 -1
- package/dist/utils-VadUNZOm.js.map +0 -1
package/dist/run-B6bZaLqK.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-B6bZaLqK.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { hash } from 'node:crypto'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nexport function getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\n/**\n * Root for the credential and machine identity of the current project.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n const projectId = hash('sha256', project)\n return path.join(getKubbHome(), 'projects', projectId)\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowWrite?: boolean; allowConfigEdit?: boolean; allowInput?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n}\n\nfunction readGithubPullRequestNumber(eventPath: string | undefined): string | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: { number?: number } }\n return event.pull_request?.number ? String(event.pull_request.number) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequestNumber = readGithubPullRequestNumber(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const scope = pullRequestNumber ?? env.GITHUB_RUN_ID ?? ''\n\n return { id: `gh:${repositoryId}:${scope}`, name: `${env.GITHUB_REPOSITORY ?? 'github'}#${scope}` }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n\n return { id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`, name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}` }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}` }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}` }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { exists, read } from '@internals/utils'\nimport { createAgent, createClient, createJob, machineTokenFrom, waitForJob, type StudioSnapshot } from '@kubb/studio'\nimport { createSpinner, logBlock } from '../../loggers/output.ts'\nimport { detectCi } from './ci.ts'\nimport { loadConfigs, type StudioOptions } from './run.ts'\n\n/**\n * How long to wait for Studio's `studio:ready` acknowledgement, above the client's own 10s\n * handshake-ack timeout.\n */\nconst READY_TIMEOUT_MS = 15_000\n\n/**\n * Longest `--timeout` accepted. Job records expire from Studio's storage after an hour.\n */\nconst MAX_TIMEOUT_SECONDS = 3600\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1'])\n\nasync function findPackageJson(startDirectory: string): Promise<{ name: string; version: string }> {\n let directory = startDirectory\n\n for (;;) {\n const file = join(directory, 'package.json')\n\n if (await exists(file)) {\n const packageJson = JSON.parse(await read(file)) as Partial<{ name: string; version: string }>\n\n if (packageJson.name && packageJson.version) {\n return { name: packageJson.name, version: packageJson.version }\n }\n }\n\n const parent = dirname(directory)\n\n if (parent === directory) {\n break\n }\n\n directory = parent\n }\n\n throw new Error(`No package.json with a name and a version found above ${startDirectory}`)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: StudioOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) {\n return { name: options.name, version: options.packageVersion }\n }\n\n const packageMetadata = await findPackageJson(process.cwd())\n\n return { name: options.name ?? packageMetadata.name, version: options.packageVersion ?? packageMetadata.version }\n}\n\nfunction resolveToken(options: StudioOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: StudioOptions): { id: string; name: string } {\n if (options.id) {\n return { id: options.id, name: options.id }\n }\n\n const detected = detectCi()\n\n if (!detected) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n return detected\n}\n\n/** Rejects a bad `--timeout` up front instead of letting it reach `waitForJob` as NaN or <= 0. */\nfunction resolveTimeoutMs(options: StudioOptions): number {\n const seconds = options.timeout ?? 600\n\n if (!Number.isFinite(seconds) || seconds <= 0) {\n throw new Error('--timeout must be a positive number of seconds')\n }\n\n return Math.min(seconds, MAX_TIMEOUT_SECONDS) * 1000\n}\n\n/** The CI key is a credential, so refuse to send it anywhere but HTTPS or a loopback dev host. */\nfunction assertSecureStudioUrl(studioUrl: string): void {\n const url = new URL(studioUrl)\n\n if (url.protocol !== 'https:' && !LOOPBACK_HOSTS.has(url.hostname)) {\n throw new Error(`Refusing to send the CI API key to ${studioUrl}. Use an https:// Studio URL, or a loopback host for local development.`)\n }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n}\n\nfunction toResult(studioUrl: string, snapshot: StudioSnapshot, agentSlug: string): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${agentSlug}`),\n }\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates a Kubb Studio snapshot from a script: registers or reuses a CI agent, connects it,\n * queues a snapshot job, and polls until the tarball is ready. A snapshot job runs generation and\n * packs the tarball in one step, so this needs no separate generation run.\n */\nexport async function snapshot(options: StudioOptions): Promise<void> {\n const timeoutMs = resolveTimeoutMs(options)\n const token = resolveToken(options)\n assertSecureStudioUrl(options.studioUrl)\n const { configPath } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n\n // Set before the first `getMachineToken()` call (inside `client.connect()`), so the WebSocket\n // session registers under the same machine token `createAgent` just registered with Studio.\n process.env.KUBB_AGENT_SECRET = ci.id\n\n const spinner = options.json ? null : createSpinner()\n\n spinner?.start('Connecting to Kubb Studio')\n\n const agent = await createAgent({ studioUrl: options.studioUrl, token, name: ci.name, machineToken: machineTokenFrom(ci.id) })\n\n const { promise: ready, reject: markFailed, resolve: markReady } = Promise.withResolvers<void>()\n\n const client = createClient({\n studioUrl: options.studioUrl,\n token: agent.token,\n configPath,\n root: process.cwd(),\n version: options.version,\n client: { kind: 'ci' },\n loadConfig: async () => (await loadConfigs(options)).config,\n installLogger: (hooks) => {\n hooks.hook('studio:ready', () => markReady())\n hooks.hook('studio:error', ({ error }) => markFailed(error))\n },\n })\n\n await client.connect()\n\n try {\n let readyTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n try {\n await Promise.race([\n ready,\n new Promise<void>((_, reject) => {\n readyTimeoutHandle = setTimeout(() => reject(new Error('Timed out waiting for Kubb Studio to confirm the agent was ready')), READY_TIMEOUT_MS)\n }),\n ])\n } finally {\n clearTimeout(readyTimeoutHandle)\n }\n\n spinner?.message('Generating and publishing the snapshot')\n\n const job = await createJob({ studioUrl: options.studioUrl, token, type: 'snapshot', agentId: agent.id, name, version: packageVersion })\n const finished = await waitForJob({ studioUrl: options.studioUrl, token, id: job.id, timeoutMs })\n\n if (finished.status === 'failed') {\n throw new Error(finished.error ?? 'Snapshot job failed')\n }\n\n if (!finished.snapshot) {\n throw new Error('Snapshot job succeeded without a snapshot')\n }\n\n const result = toResult(options.studioUrl, finished.snapshot, agent.slug)\n\n spinner?.stop('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n } else {\n printSummary(result)\n }\n } catch (error) {\n spinner?.stop('Snapshot failed')\n throw error\n } finally {\n client.disconnect()\n }\n}\n","import { hostname } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n PairingCanceledError,\n pollForPairingToken,\n runConnection,\n setStorage,\n startPairing,\n} from '@kubb/studio'\nimport { x } from 'tinyexec'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/studio.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro } from '../../loggers/output.ts'\nimport { canUseTTY, isCIEnvironment } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getProjectKubbHome, readCredentials, writeCredentials } from './credentials.ts'\nimport { snapshot } from './snapshot.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status', 'snapshot'] as const\n\nexport type StudioAction = (typeof ACTIONS)[number]\n\ntype Permission = 'allowWrite' | 'allowConfigEdit' | 'allowInput' | 'allowExec'\n\nexport type StudioOptions = {\n action: StudioAction\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<Permission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n /**\n * `snapshot` only: organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * `snapshot` only: stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /**\n * `snapshot` only: package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * `snapshot` only: package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * `snapshot` only: seconds to wait for the job to finish.\n */\n timeout?: number\n /**\n * `snapshot` only: print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/**\n * Opens a URL in the user's browser. Best effort: a failure just means the user follows the\n * printed link instead.\n *\n * `start` is a `cmd.exe` builtin, not an executable on PATH, so Windows runs it through `cmd`.\n * The empty string is the window-title argument `start` expects before the URL.\n */\nasync function openInBrowser(url: string): Promise<void> {\n try {\n if (process.platform === 'win32') {\n await x('cmd', ['/c', 'start', '', url])\n } else {\n await x(process.platform === 'darwin' ? 'open' : 'xdg-open', [url])\n }\n } catch {}\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nasync function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const session = await startPairing({ studioUrl, name: path.basename(process.cwd()), hostname: hostname(), signal })\n\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n await openInBrowser(session.verification_uri_complete)\n }\n\n const spinner = createSpinner()\n spinner.start('Waiting for approval')\n\n try {\n const { token, agent } = await pollForPairingToken({ studioUrl, session, signal })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowInput',\n label: 'use a Studio spec',\n question: () => 'Let Kubb Studio generate from an OpenAPI spec it sends, instead of the one on disk?',\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowWrite: false, allowConfigEdit: false, allowInput: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nexport async function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\n/**\n * One `kubb studio` connect run: pairing if needed, connecting, and pairing again whenever Studio\n * rejects the token. Reached through `connect()`, which is what the command runs.\n */\nclass StudioConnection {\n readonly #options: StudioOptions\n readonly #configPath: string\n readonly #shutdown = new AbortController()\n readonly #requestShutdown = (): void => this.#shutdown.abort()\n // `bun-types` narrows `process.on`/`process.off` to its own event union, which omits Node's\n // process signal events, so the listener is installed and removed through the plain emitter API.\n readonly #processEvents = process as unknown as NodeJS.EventEmitter\n\n // Known once `run()` resolves the initial credentials, before anything else reads this field.\n #credentials!: Credentials\n // Whether the \"Press Ctrl+C\" hint already printed, so a reconnect never repeats it.\n #hinted = false\n // One automatic re-pair per run, whether the rejection lands at startup or once the session is\n // live. A token rejected right after a fresh login is a hard failure, not a reason to keep\n // pairing.\n #hasReauthenticated = false\n // Resolved by `run()` from the flags and the project's saved answers, before anything reads it.\n #granted!: Record<Permission, boolean>\n\n constructor(options: StudioOptions, configPath: string) {\n this.#options = options\n this.#configPath = configPath\n }\n\n #reportDisconnected(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n logOutro('Disconnected')\n }\n\n /**\n * Connects and streams generation events until the process is stopped or Studio rejects the\n * token.\n *\n * One `AbortController` covers the whole run: it cancels an in-flight pairing poll on Ctrl+C and\n * ends the wait in `#connectAndWait`. Its signal listeners are armed once here, so a retried\n * pairing cannot leave a duplicate behind.\n */\n async run(): Promise<void> {\n this.#processEvents.once('SIGINT', this.#requestShutdown)\n this.#processEvents.once('SIGTERM', this.#requestShutdown)\n\n try {\n this.#credentials = await this.#resolveInitialCredentials()\n\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n this.#printBanner()\n\n const outcome = await runConnection({\n credentials: this.#credentials,\n signal: this.#shutdown.signal,\n clientOptions: () => this.#clientOptions(),\n onTokenRejected: ({ error, live }) => this.#handleRejection(error, live),\n })\n\n if (outcome === 'shutdown') {\n this.#reportDisconnected()\n }\n } catch (error) {\n // Canceling the very first pairing (before anything was ever connected) is Ctrl+C working as\n // intended, not a failure to report.\n if (error instanceof PairingCanceledError) {\n return\n }\n\n throw error\n } finally {\n this.#processEvents.off('SIGINT', this.#requestShutdown)\n this.#processEvents.off('SIGTERM', this.#requestShutdown)\n }\n }\n\n async #resolveInitialCredentials(): Promise<Credentials> {\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n\n // A credential is only reused for the Studio it was issued by, so switching `--url` re-pairs\n // instead of sending one instance's token to another.\n const resolved = envToken\n ? { studioUrl: this.#options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n : stored?.studioUrl === this.#options.studioUrl\n ? stored\n : null\n\n if (resolved) {\n return resolved\n }\n\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${this.#options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n\n return login(this.#options, { signal: this.#shutdown.signal })\n }\n\n #printBanner(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n const detail = (label: string, value: string) => `${styleText('dim', label.padEnd(7))} ${value}`\n\n logBlock([\n detail('Studio', styleText('cyan', this.#options.studioUrl)),\n detail('Project', path.basename(process.cwd())),\n detail('Config', path.relative(process.cwd(), this.#configPath) || this.#configPath),\n '',\n styleText('dim', 'Permissions'),\n ...formatPermissionRows(this.#granted),\n ])\n }\n\n /**\n * What every connection attempt opens with. Rebuilt per attempt, so a re-pair that changed the\n * granted permissions takes effect on the next one.\n */\n #clientOptions(): Omit<ClientOptions, 'token' | 'onAuthRequired'> {\n return {\n studioUrl: this.#options.studioUrl,\n configPath: this.#configPath,\n version: this.#options.version,\n // Reloaded on every generate, so an edit to kubb.config.ts is picked up without reconnecting.\n loadConfig: async () => (await loadConfigs(this.#options)).config,\n client: { kind: 'cli' },\n root: process.cwd(),\n permissions: this.#granted,\n // The loggers `kubb generate` installs, so one place renders the session events and the\n // generations it drives.\n installLogger: async (hooks) => {\n await setupReporters(hooks, { logLevel: logLevelMap[this.#options.logLevel ?? 'info'], reporters: [cliReporter] })\n\n // `client.connect()` resolves once the agent is registered, not once a session is open, so\n // this is the only point that knows the connection is live. Registered after the loggers so\n // it lands under their \"Connected to ...\" line, and once, since every reconnect fires again.\n hooks.hook('studio:connected', () => {\n if (this.#hinted || this.#options.logLevel === 'silent') {\n return\n }\n this.#hinted = true\n\n logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n })\n },\n }\n }\n\n /**\n * Throws when a rejected token cannot be replaced by pairing again: this run already paired once\n * and was rejected anyway, or there is no browser to approve a new pairing.\n */\n #assertCanReauthenticate(error: InvalidAgentTokenError): void {\n if (this.#hasReauthenticated) {\n throw explainRejectedToken(error, 'reauthExhausted')\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n throw explainRejectedToken(error, 'nonInteractive')\n }\n }\n\n /**\n * Studio rejected the token, either before a session ever opened or once one was already live.\n * Keeping a rejected token only produces 401s on every run, so it is forgotten and paired again.\n * Returns the credential to reconnect with, or null when the run is over.\n */\n async #handleRejection(error: InvalidAgentTokenError, live: boolean): Promise<Credentials | null> {\n // An operator-supplied token is never replaced automatically.\n if (process.env.KUBB_AGENT_TOKEN) {\n throw explainRejectedToken(error, 'envToken')\n }\n\n // A token dead at startup is forgotten either way. A live one is only forgotten once this run\n // knows it can pair again, so a CI run keeps the credential it could not replace.\n if (!live) {\n await clearCredentials()\n }\n\n this.#assertCanReauthenticate(error)\n\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n\n if (live) {\n await clearCredentials()\n }\n\n const credentials = await this.#reauthenticate()\n\n // Nothing was ever connected at startup, so there is no session to report the end of.\n if (!credentials && live) {\n this.#reportDisconnected()\n }\n\n return credentials\n }\n\n /**\n * Re-pairs and stores the resulting credentials. Returns null when the operator canceled it.\n */\n async #reauthenticate(): Promise<Credentials | null> {\n try {\n this.#credentials = await login(this.#options, { signal: this.#shutdown.signal, previousCredentials: this.#credentials })\n } catch (loginError) {\n if (loginError instanceof PairingCanceledError) {\n return null\n }\n throw loginError\n }\n\n this.#hasReauthenticated = true\n\n // The approved agent may be a different identity, whose saved permissions did not carry\n // forward. Resolving again asks for whatever this credential does not already hold, instead\n // of handing the new agent what the previous one was granted.\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n return this.#credentials\n }\n}\n\n/**\n * Connects this project to Studio and streams generation events until the process is stopped or\n * Studio rejects the token.\n */\nexport async function connect(options: StudioOptions): Promise<void> {\n // Resolved before any network call to Studio (pairing included), so a project with no config\n // fails fast instead of starting a device-authorization flow it can never use.\n const { configPath } = await loadConfigs(options)\n\n await new StudioConnection(options, configPath).run()\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nasync function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowInput: remembered.allowInput === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a `kubb studio` action and reports the outcome to telemetry.\n */\nasync function run(options: StudioOptions): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(getProjectKubbHome()))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\n\n try {\n // `snapshot --json` prints exactly one JSON object on stdout, so nothing else may write there.\n if (options.logLevel !== 'silent' && !(options.action === 'snapshot' && options.json)) {\n logIntro({\n title: `Kubb Studio ${styleText('dim', `v${options.version}`)}`,\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n // Only `connect` stays open long enough to close the block again with `logOutro`.\n block: options.action === 'connect',\n })\n }\n\n switch (options.action) {\n case 'login':\n await login(options)\n break\n case 'logout':\n await clearCredentials()\n console.log('Signed out of Kubb Studio.')\n break\n case 'status':\n await status(options)\n break\n case 'connect':\n await connect(options)\n break\n case 'snapshot':\n await snapshot(options)\n break\n default:\n throw new Error(`Unknown action \"${options.action}\", expected one of ${ACTIONS.join(', ')}`)\n }\n\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Maps the parsed `kubb studio` flags onto {@link run}. Loaded on demand by `index.ts`, so the\n * Studio client stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({\n action: (values.action ?? 'connect') as StudioAction,\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowInput: values.allowInput,\n allowExec: values.allowExec,\n },\n autoOpen: values.open,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n name: values.name,\n packageVersion: values.packageVersion,\n timeout: values.timeout,\n json: values.json,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,eAAsB,OAAO,MAAgC;CAC3D,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO;CAE/B,OAAO,OAAO,IAAI,CAAC,CAAC,WACZ,YACA,KACR;AACF;;;;;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AAgB,UAAU,OAAO,IAAI,QAAQ,SAAS;GAC7D,SAAS,UAAU,UAAU,2DAA2D;GAExF,OAAO,QAAQ,WAAW;EAC5B,CAAC;EAGH,QAAQ,QAAQ,QAAhB;GACE,KAAK;IACH,MAAM,MAAM,OAAO;IACnB;GACF,KAAK;IACH,MAAM,iBAAiB;IACvB,QAAQ,IAAI,4BAA4B;IACxC;GACF,KAAK;IACH,MAAM,OAAO,OAAO;IACpB;GACF,KAAK;IACH,MAAM,QAAQ,OAAO;IACrB;GACF,KAAK;IACH,MAAM,SAAS,OAAO;IACtB;GACF,SACE,MAAM,IAAI,MAAM,mBAAmB,QAAQ,OAAO,qBAAqB,QAAQ,KAAK,IAAI,GAAG;EAC/F;EAEA,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EACR,QAAS,OAAO,UAAU;EAC1B;EACA,YAAY,OAAO;EACnB,WAAW,OAAO,OAAO;EACzB,YAAY;GACV,YAAY,OAAO;GACnB,iBAAiB,OAAO;GACxB,YAAY,OAAO;GACnB,WAAW,OAAO;EACpB;EACA,UAAU,OAAO;EACjB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,SAAS,OAAO;EAChB,MAAM,OAAO;CACf,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-BHMES-2P.cjs","names":["runtime","access","readFile","rm","process","path","homedir","hash","mkdir","writeFile","readFileSync","process","join","dirname","process","styleText","createSpinner","createAgent","machineTokenFrom","createClient","createJob","waitForJob","process","x","startPairing","path","hostname","styleText","createSpinner","pollForPairingToken","PairingCanceledError","KUBB_CONFIG_FILENAME","isCIEnvironment","canUseTTY","prompts","getConfigs","runConnection","setupReporters","logLevelMap","cliReporter","createFileStorage","sendTelemetry","buildTelemetryEvent","toError","defaultStudioUrl"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { hash } from 'node:crypto'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nexport function getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\n/**\n * Root for the credential and machine identity of the current project.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n const projectId = hash('sha256', project)\n return path.join(getKubbHome(), 'projects', projectId)\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowWrite?: boolean; allowConfigEdit?: boolean; allowInput?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n}\n\nfunction readGithubPullRequestNumber(eventPath: string | undefined): string | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: { number?: number } }\n return event.pull_request?.number ? String(event.pull_request.number) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequestNumber = readGithubPullRequestNumber(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const scope = pullRequestNumber ?? env.GITHUB_RUN_ID ?? ''\n\n return { id: `gh:${repositoryId}:${scope}`, name: `${env.GITHUB_REPOSITORY ?? 'github'}#${scope}` }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n\n return { id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`, name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}` }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}` }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}` }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { exists, read } from '@internals/utils'\nimport { createAgent, createClient, createJob, machineTokenFrom, waitForJob, type StudioSnapshot } from '@kubb/studio'\nimport { createSpinner, logBlock } from '../../loggers/output.ts'\nimport { detectCi } from './ci.ts'\nimport { loadConfigs, type StudioOptions } from './run.ts'\n\n/**\n * How long to wait for Studio's `studio:ready` acknowledgement, above the client's own 10s\n * handshake-ack timeout.\n */\nconst READY_TIMEOUT_MS = 15_000\n\n/**\n * Longest `--timeout` accepted. Job records expire from Studio's storage after an hour.\n */\nconst MAX_TIMEOUT_SECONDS = 3600\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1'])\n\nasync function findPackageJson(startDirectory: string): Promise<{ name: string; version: string }> {\n let directory = startDirectory\n\n for (;;) {\n const file = join(directory, 'package.json')\n\n if (await exists(file)) {\n const packageJson = JSON.parse(await read(file)) as Partial<{ name: string; version: string }>\n\n if (packageJson.name && packageJson.version) {\n return { name: packageJson.name, version: packageJson.version }\n }\n }\n\n const parent = dirname(directory)\n\n if (parent === directory) {\n break\n }\n\n directory = parent\n }\n\n throw new Error(`No package.json with a name and a version found above ${startDirectory}`)\n}\n\n/** Reads package.json only for whichever of name/version --name and --version did not supply. */\nasync function resolvePackageMetadata(options: StudioOptions): Promise<{ name: string; version: string }> {\n if (options.name && options.packageVersion) {\n return { name: options.name, version: options.packageVersion }\n }\n\n const packageMetadata = await findPackageJson(process.cwd())\n\n return { name: options.name ?? packageMetadata.name, version: options.packageVersion ?? packageMetadata.version }\n}\n\nfunction resolveToken(options: StudioOptions): string {\n const token = options.token ?? process.env.KUBB_TOKEN\n\n if (!token) {\n throw new Error('An organization CI API key is required. Pass --token or set KUBB_TOKEN.')\n }\n\n return token\n}\n\nfunction resolveCiIdentity(options: StudioOptions): { id: string; name: string } {\n if (options.id) {\n return { id: options.id, name: options.id }\n }\n\n const detected = detectCi()\n\n if (!detected) {\n throw new Error('Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.')\n }\n\n return detected\n}\n\n/** Rejects a bad `--timeout` up front instead of letting it reach `waitForJob` as NaN or <= 0. */\nfunction resolveTimeoutMs(options: StudioOptions): number {\n const seconds = options.timeout ?? 600\n\n if (!Number.isFinite(seconds) || seconds <= 0) {\n throw new Error('--timeout must be a positive number of seconds')\n }\n\n return Math.min(seconds, MAX_TIMEOUT_SECONDS) * 1000\n}\n\n/** The CI key is a credential, so refuse to send it anywhere but HTTPS or a loopback dev host. */\nfunction assertSecureStudioUrl(studioUrl: string): void {\n const url = new URL(studioUrl)\n\n if (url.protocol !== 'https:' && !LOOPBACK_HOSTS.has(url.hostname)) {\n throw new Error(`Refusing to send the CI API key to ${studioUrl}. Use an https:// Studio URL, or a loopback host for local development.`)\n }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n expiresAt: string\n agentUrl: string\n}\n\nfunction toResult(studioUrl: string, snapshot: StudioSnapshot, agentSlug: string): SnapshotResult {\n return {\n id: snapshot.id,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${agentSlug}`),\n }\n}\n\nfunction printSummary(result: SnapshotResult): void {\n logBlock([\n `${styleText('dim', 'Package'.padEnd(10))} ${result.name ?? '(unnamed)'}@${result.version ?? '0.0.0'}`,\n `${styleText('dim', 'Tarball'.padEnd(10))} ${styleText('cyan', result.url)}`,\n `${styleText('dim', 'Agent'.padEnd(10))} ${result.agentUrl}`,\n `${styleText('dim', 'Expires'.padEnd(10))} ${result.expiresAt}`,\n ])\n}\n\n/**\n * Generates a Kubb Studio snapshot from a script: registers or reuses a CI agent, connects it,\n * queues a snapshot job, and polls until the tarball is ready. A snapshot job runs generation and\n * packs the tarball in one step, so this needs no separate generation run.\n */\nexport async function snapshot(options: StudioOptions): Promise<void> {\n const timeoutMs = resolveTimeoutMs(options)\n const token = resolveToken(options)\n assertSecureStudioUrl(options.studioUrl)\n const { configPath } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n const { name, version: packageVersion } = await resolvePackageMetadata(options)\n\n // Set before the first `getMachineToken()` call (inside `client.connect()`), so the WebSocket\n // session registers under the same machine token `createAgent` just registered with Studio.\n process.env.KUBB_AGENT_SECRET = ci.id\n\n const spinner = options.json ? null : createSpinner()\n\n spinner?.start('Connecting to Kubb Studio')\n\n const agent = await createAgent({ studioUrl: options.studioUrl, token, name: ci.name, machineToken: machineTokenFrom(ci.id) })\n\n const { promise: ready, reject: markFailed, resolve: markReady } = Promise.withResolvers<void>()\n\n const client = createClient({\n studioUrl: options.studioUrl,\n token: agent.token,\n configPath,\n root: process.cwd(),\n version: options.version,\n client: { kind: 'ci' },\n loadConfig: async () => (await loadConfigs(options)).config,\n installLogger: (hooks) => {\n hooks.hook('studio:ready', () => markReady())\n hooks.hook('studio:error', ({ error }) => markFailed(error))\n },\n })\n\n await client.connect()\n\n try {\n let readyTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n try {\n await Promise.race([\n ready,\n new Promise<void>((_, reject) => {\n readyTimeoutHandle = setTimeout(() => reject(new Error('Timed out waiting for Kubb Studio to confirm the agent was ready')), READY_TIMEOUT_MS)\n }),\n ])\n } finally {\n clearTimeout(readyTimeoutHandle)\n }\n\n spinner?.message('Generating and publishing the snapshot')\n\n const job = await createJob({ studioUrl: options.studioUrl, token, type: 'snapshot', agentId: agent.id, name, version: packageVersion })\n const finished = await waitForJob({ studioUrl: options.studioUrl, token, id: job.id, timeoutMs })\n\n if (finished.status === 'failed') {\n throw new Error(finished.error ?? 'Snapshot job failed')\n }\n\n if (!finished.snapshot) {\n throw new Error('Snapshot job succeeded without a snapshot')\n }\n\n const result = toResult(options.studioUrl, finished.snapshot, agent.slug)\n\n spinner?.stop('Snapshot published')\n\n if (options.json) {\n console.log(JSON.stringify(result))\n } else {\n printSummary(result)\n }\n } catch (error) {\n spinner?.stop('Snapshot failed')\n throw error\n } finally {\n client.disconnect()\n }\n}\n","import { hostname } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n PairingCanceledError,\n pollForPairingToken,\n runConnection,\n setStorage,\n startPairing,\n} from '@kubb/studio'\nimport { x } from 'tinyexec'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/studio.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro } from '../../loggers/output.ts'\nimport { canUseTTY, isCIEnvironment } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getProjectKubbHome, readCredentials, writeCredentials } from './credentials.ts'\nimport { snapshot } from './snapshot.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status', 'snapshot'] as const\n\nexport type StudioAction = (typeof ACTIONS)[number]\n\ntype Permission = 'allowWrite' | 'allowConfigEdit' | 'allowInput' | 'allowExec'\n\nexport type StudioOptions = {\n action: StudioAction\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<Permission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n /**\n * `snapshot` only: organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * `snapshot` only: stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /**\n * `snapshot` only: package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * `snapshot` only: package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * `snapshot` only: seconds to wait for the job to finish.\n */\n timeout?: number\n /**\n * `snapshot` only: print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/**\n * Opens a URL in the user's browser. Best effort: a failure just means the user follows the\n * printed link instead.\n *\n * `start` is a `cmd.exe` builtin, not an executable on PATH, so Windows runs it through `cmd`.\n * The empty string is the window-title argument `start` expects before the URL.\n */\nasync function openInBrowser(url: string): Promise<void> {\n try {\n if (process.platform === 'win32') {\n await x('cmd', ['/c', 'start', '', url])\n } else {\n await x(process.platform === 'darwin' ? 'open' : 'xdg-open', [url])\n }\n } catch {}\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nasync function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const session = await startPairing({ studioUrl, name: path.basename(process.cwd()), hostname: hostname(), signal })\n\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n await openInBrowser(session.verification_uri_complete)\n }\n\n const spinner = createSpinner()\n spinner.start('Waiting for approval')\n\n try {\n const { token, agent } = await pollForPairingToken({ studioUrl, session, signal })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowInput',\n label: 'use a Studio spec',\n question: () => 'Let Kubb Studio generate from an OpenAPI spec it sends, instead of the one on disk?',\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowWrite: false, allowConfigEdit: false, allowInput: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nexport async function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\n/**\n * One `kubb studio` connect run: pairing if needed, connecting, and pairing again whenever Studio\n * rejects the token. Reached through `connect()`, which is what the command runs.\n */\nclass StudioConnection {\n readonly #options: StudioOptions\n readonly #configPath: string\n readonly #shutdown = new AbortController()\n readonly #requestShutdown = (): void => this.#shutdown.abort()\n // `bun-types` narrows `process.on`/`process.off` to its own event union, which omits Node's\n // process signal events, so the listener is installed and removed through the plain emitter API.\n readonly #processEvents = process as unknown as NodeJS.EventEmitter\n\n // Known once `run()` resolves the initial credentials, before anything else reads this field.\n #credentials!: Credentials\n // Whether the \"Press Ctrl+C\" hint already printed, so a reconnect never repeats it.\n #hinted = false\n // One automatic re-pair per run, whether the rejection lands at startup or once the session is\n // live. A token rejected right after a fresh login is a hard failure, not a reason to keep\n // pairing.\n #hasReauthenticated = false\n // Resolved by `run()` from the flags and the project's saved answers, before anything reads it.\n #granted!: Record<Permission, boolean>\n\n constructor(options: StudioOptions, configPath: string) {\n this.#options = options\n this.#configPath = configPath\n }\n\n #reportDisconnected(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n logOutro('Disconnected')\n }\n\n /**\n * Connects and streams generation events until the process is stopped or Studio rejects the\n * token.\n *\n * One `AbortController` covers the whole run: it cancels an in-flight pairing poll on Ctrl+C and\n * ends the wait in `#connectAndWait`. Its signal listeners are armed once here, so a retried\n * pairing cannot leave a duplicate behind.\n */\n async run(): Promise<void> {\n this.#processEvents.once('SIGINT', this.#requestShutdown)\n this.#processEvents.once('SIGTERM', this.#requestShutdown)\n\n try {\n this.#credentials = await this.#resolveInitialCredentials()\n\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n this.#printBanner()\n\n const outcome = await runConnection({\n credentials: this.#credentials,\n signal: this.#shutdown.signal,\n clientOptions: () => this.#clientOptions(),\n onTokenRejected: ({ error, live }) => this.#handleRejection(error, live),\n })\n\n if (outcome === 'shutdown') {\n this.#reportDisconnected()\n }\n } catch (error) {\n // Canceling the very first pairing (before anything was ever connected) is Ctrl+C working as\n // intended, not a failure to report.\n if (error instanceof PairingCanceledError) {\n return\n }\n\n throw error\n } finally {\n this.#processEvents.off('SIGINT', this.#requestShutdown)\n this.#processEvents.off('SIGTERM', this.#requestShutdown)\n }\n }\n\n async #resolveInitialCredentials(): Promise<Credentials> {\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n\n // A credential is only reused for the Studio it was issued by, so switching `--url` re-pairs\n // instead of sending one instance's token to another.\n const resolved = envToken\n ? { studioUrl: this.#options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n : stored?.studioUrl === this.#options.studioUrl\n ? stored\n : null\n\n if (resolved) {\n return resolved\n }\n\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${this.#options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n\n return login(this.#options, { signal: this.#shutdown.signal })\n }\n\n #printBanner(): void {\n if (this.#options.logLevel === 'silent') {\n return\n }\n\n const detail = (label: string, value: string) => `${styleText('dim', label.padEnd(7))} ${value}`\n\n logBlock([\n detail('Studio', styleText('cyan', this.#options.studioUrl)),\n detail('Project', path.basename(process.cwd())),\n detail('Config', path.relative(process.cwd(), this.#configPath) || this.#configPath),\n '',\n styleText('dim', 'Permissions'),\n ...formatPermissionRows(this.#granted),\n ])\n }\n\n /**\n * What every connection attempt opens with. Rebuilt per attempt, so a re-pair that changed the\n * granted permissions takes effect on the next one.\n */\n #clientOptions(): Omit<ClientOptions, 'token' | 'onAuthRequired'> {\n return {\n studioUrl: this.#options.studioUrl,\n configPath: this.#configPath,\n version: this.#options.version,\n // Reloaded on every generate, so an edit to kubb.config.ts is picked up without reconnecting.\n loadConfig: async () => (await loadConfigs(this.#options)).config,\n client: { kind: 'cli' },\n root: process.cwd(),\n permissions: this.#granted,\n // The loggers `kubb generate` installs, so one place renders the session events and the\n // generations it drives.\n installLogger: async (hooks) => {\n await setupReporters(hooks, { logLevel: logLevelMap[this.#options.logLevel ?? 'info'], reporters: [cliReporter] })\n\n // `client.connect()` resolves once the agent is registered, not once a session is open, so\n // this is the only point that knows the connection is live. Registered after the loggers so\n // it lands under their \"Connected to ...\" line, and once, since every reconnect fires again.\n hooks.hook('studio:connected', () => {\n if (this.#hinted || this.#options.logLevel === 'silent') {\n return\n }\n this.#hinted = true\n\n logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n })\n },\n }\n }\n\n /**\n * Throws when a rejected token cannot be replaced by pairing again: this run already paired once\n * and was rejected anyway, or there is no browser to approve a new pairing.\n */\n #assertCanReauthenticate(error: InvalidAgentTokenError): void {\n if (this.#hasReauthenticated) {\n throw explainRejectedToken(error, 'reauthExhausted')\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n throw explainRejectedToken(error, 'nonInteractive')\n }\n }\n\n /**\n * Studio rejected the token, either before a session ever opened or once one was already live.\n * Keeping a rejected token only produces 401s on every run, so it is forgotten and paired again.\n * Returns the credential to reconnect with, or null when the run is over.\n */\n async #handleRejection(error: InvalidAgentTokenError, live: boolean): Promise<Credentials | null> {\n // An operator-supplied token is never replaced automatically.\n if (process.env.KUBB_AGENT_TOKEN) {\n throw explainRejectedToken(error, 'envToken')\n }\n\n // A token dead at startup is forgotten either way. A live one is only forgotten once this run\n // knows it can pair again, so a CI run keeps the credential it could not replace.\n if (!live) {\n await clearCredentials()\n }\n\n this.#assertCanReauthenticate(error)\n\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n\n if (live) {\n await clearCredentials()\n }\n\n const credentials = await this.#reauthenticate()\n\n // Nothing was ever connected at startup, so there is no session to report the end of.\n if (!credentials && live) {\n this.#reportDisconnected()\n }\n\n return credentials\n }\n\n /**\n * Re-pairs and stores the resulting credentials. Returns null when the operator canceled it.\n */\n async #reauthenticate(): Promise<Credentials | null> {\n try {\n this.#credentials = await login(this.#options, { signal: this.#shutdown.signal, previousCredentials: this.#credentials })\n } catch (loginError) {\n if (loginError instanceof PairingCanceledError) {\n return null\n }\n throw loginError\n }\n\n this.#hasReauthenticated = true\n\n // The approved agent may be a different identity, whose saved permissions did not carry\n // forward. Resolving again asks for whatever this credential does not already hold, instead\n // of handing the new agent what the previous one was granted.\n this.#granted = await resolvePermissions(this.#options, this.#credentials, this.#configPath, !process.env.KUBB_AGENT_TOKEN)\n\n return this.#credentials\n }\n}\n\n/**\n * Connects this project to Studio and streams generation events until the process is stopped or\n * Studio rejects the token.\n */\nexport async function connect(options: StudioOptions): Promise<void> {\n // Resolved before any network call to Studio (pairing included), so a project with no config\n // fails fast instead of starting a device-authorization flow it can never use.\n const { configPath } = await loadConfigs(options)\n\n await new StudioConnection(options, configPath).run()\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nasync function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowInput: remembered.allowInput === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a `kubb studio` action and reports the outcome to telemetry.\n */\nasync function run(options: StudioOptions): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(getProjectKubbHome()))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\n\n try {\n // `snapshot --json` prints exactly one JSON object on stdout, so nothing else may write there.\n if (options.logLevel !== 'silent' && !(options.action === 'snapshot' && options.json)) {\n logIntro({\n title: `Kubb Studio ${styleText('dim', `v${options.version}`)}`,\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n // Only `connect` stays open long enough to close the block again with `logOutro`.\n block: options.action === 'connect',\n })\n }\n\n switch (options.action) {\n case 'login':\n await login(options)\n break\n case 'logout':\n await clearCredentials()\n console.log('Signed out of Kubb Studio.')\n break\n case 'status':\n await status(options)\n break\n case 'connect':\n await connect(options)\n break\n case 'snapshot':\n await snapshot(options)\n break\n default:\n throw new Error(`Unknown action \"${options.action}\", expected one of ${ACTIONS.join(', ')}`)\n }\n\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Maps the parsed `kubb studio` flags onto {@link run}. Loaded on demand by `index.ts`, so the\n * Studio client stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({\n action: (values.action ?? 'connect') as StudioAction,\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowInput: values.allowInput,\n allowExec: values.allowExec,\n },\n autoOpen: values.open,\n logLevel: values.logLevel,\n token: values.token,\n id: values.id,\n name: values.name,\n packageVersion: values.packageVersion,\n timeout: values.timeout,\n json: values.json,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,eAAsB,OAAO,MAAgC;CAC3D,IAAIA,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO;CAE/B,QAAA,GAAOC,iBAAAA,OAAAA,CAAO,IAAI,CAAC,CAAC,WACZ,YACA,KACR;AACF;;;;;;;;;;AAWA,eAAsB,KAAK,MAA+B;CACxD,IAAID,kBAAAA,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,QAAA,GAAOE,iBAAAA,SAAAA,CAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,QAAA,GAAOC,iBAAAA,GAAAA,CAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACpIA,SAAgB,cAAsB;CACpC,OAAOC,a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ACH,MAAM,OAAO,OAAO;IACpB;GACF,KAAK;IACH,MAAM,QAAQ,OAAO;IACrB;GACF,KAAK;IACH,MAAM,SAAS,OAAO;IACtB;GACF,SACE,MAAM,IAAI,MAAM,mBAAmB,QAAQ,OAAO,qBAAqB,QAAQ,KAAK,IAAI,GAAG;EAC/F;EAEA,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAMgB,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,aAAA,QAAA,WAAmB;CACrB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EACR,QAAS,OAAO,UAAU;EAC1B,SAAA,gBAAA;EACA,YAAY,OAAO;EACnB,WAAW,OAAO,OAAOC,aAAAA;EACzB,YAAY;GACV,YAAY,OAAO;GACnB,iBAAiB,OAAO;GACxB,YAAY,OAAO;GACnB,WAAW,OAAO;EACpB;EACA,UAAU,OAAO;EACjB,UAAU,OAAO;EACjB,OAAO,OAAO;EACd,IAAI,OAAO;EACX,MAAM,OAAO;EACb,gBAAgB,OAAO;EACvB,SAAS,OAAO;EAChB,MAAM,OAAO;CACf,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-BgEQilnN.cjs","names":["spawn","styleText","logLevelMap","clack","styleText","Diagnostics","relative","process","logLevelMap","Diagnostics","relative","logLevelMap","styleText","process","canUseTTY","getAgentName","jiti","createJiti","resolve","basename","loadConfig","dirname","process","isValid","isGreater","truncate","randomUUID","x","styleText","NonZeroExitError","toError","WATCHER_IGNORED_PATHS","URL_WATCHER_TIMEOUT_MS","URL_WATCHER_INTERVAL_MS"],"sources":["../../../internals/utils/src/tools.ts","../../../internals/utils/src/time.ts","../src/loggers/banner.ts","../src/loggers/clackLogger.ts","../src/loggers/plainLogger.ts","../src/loggers/utils.ts","../../../internals/shared/src/loader.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH and answers `--version` with a zero exit.\n */\nexport function isToolAvailable(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(name, ['--version'], { stdio: 'ignore' })\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate)) {\n return candidate\n }\n }\n\n return null\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","import { styleText } from 'node:util'\nimport { formatMs } from '@internals/utils'\n\n/**\n * Parsed RGB channels from a CSS hex color string.\n */\ntype RGB = { r: number; g: number; b: number }\n\n/**\n * Parses a CSS hex color string (`#RGB`) into its RGB channels.\n * Falls back to `255` for any channel that cannot be parsed.\n */\nfunction parseHex(color: string): RGB {\n const int = Number.parseInt(color.replace('#', ''), 16)\n return Number.isNaN(int) ? { r: 255, g: 255, b: 255 } : { r: (int >> 16) & 0xff, g: (int >> 8) & 0xff, b: int & 0xff }\n}\n\n/**\n * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence\n * for the given hex color.\n */\nfunction hex(color: string): (text: string) => string {\n const { r, g, b } = parseHex(color)\n return (text: string) => `\\x1b[38;2;${r};${g};${b}m${text}\\x1b[0m`\n}\n\nfunction gradient(colorStops: Array<string>, text: string): string {\n const chars = text.split('')\n return chars\n .map((char, i) => {\n const t = chars.length <= 1 ? 0 : i / (chars.length - 1)\n const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2)\n const lt = t * (colorStops.length - 1) - seg\n const from = parseHex(colorStops[seg]!)\n const to = parseHex(colorStops[seg + 1]!)\n const r = Math.round(from.r + (to.r - from.r) * lt)\n const g = Math.round(from.g + (to.g - from.g) * lt)\n const b = Math.round(from.b + (to.b - from.b) * lt)\n return `\\x1b[38;2;${r};${g};${b}m${char}\\x1b[0m`\n })\n .join('')\n}\n\n/**\n * ANSI color functions for each part of the Kubb mascot illustration.\n */\nconst palette = {\n /**\n * Top cap of the skittle.\n */\n lid: hex('#F55A17'),\n /**\n * Upper wood body.\n */\n woodTop: hex('#F5A217'),\n /**\n * Middle wood body.\n */\n woodMid: hex('#F58517'),\n /**\n * Base wood body.\n */\n woodBase: hex('#B45309'),\n /**\n * Eye whites.\n */\n eye: hex('#FFFFFF'),\n /**\n * Highlight accent.\n */\n highlight: hex('#adadc6'),\n /**\n * Cheek blush.\n */\n blush: hex('#FDA4AF'),\n}\n\n/**\n * Generates the Kubb mascot welcome banner as an ANSI-colored string.\n *\n * @example\n * ```ts\n * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))\n * ```\n */\nexport function getIntro({\n title,\n description,\n version,\n areEyesOpen,\n}: {\n /**\n * Name of the active configuration or tool being started.\n */\n title: string\n /**\n * Short subtitle shown next to the arrow prompt.\n */\n description: string\n /**\n * Kubb version string rendered in the gradient header.\n */\n version: string\n /**\n * When `false` the eyes are shown as closed dashes instead of open blocks.\n */\n areEyesOpen: boolean\n}): string {\n const kubbVersion = gradient(['#F58517', '#F5A217', '#F55A17'], `KUBB v${version}`)\n\n const eyeTop = areEyesOpen ? palette.eye('█▀█') : palette.eye('───')\n const eyeBottom = areEyesOpen ? palette.eye('▀▀▀') : palette.eye('───')\n\n return `\n ${palette.lid('▄▄▄▄▄▄▄▄▄▄▄▄▄')}\n ${palette.woodTop('█ ')}${palette.highlight('▄▄')}${palette.woodTop(' ')}${palette.highlight('▄▄')}${palette.woodTop(' █')} ${kubbVersion}\n ${palette.woodMid('█ ')}${eyeTop}${palette.woodMid(' ')}${eyeTop}${palette.woodMid(' █')} ${styleText('gray', title)}\n ${palette.woodMid('█ ')}${eyeBottom}${palette.woodMid(' ')}${palette.blush('◡')}${palette.woodMid(' ')}${eyeBottom}${palette.woodMid(' █')} ${styleText('yellow', '➜')} ${styleText('white', description)}\n ${palette.woodBase('▀▀▀▀▀▀▀▀▀▀▀▀▀')}\n`\n}\n\n/**\n * Formats a millisecond duration with a threshold-based ANSI color.\n * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.\n *\n * @example\n * ```ts\n * formatMsWithColor(200) // '\\x1b[32m200ms\\x1b[39m'\n * formatMsWithColor(800) // '\\x1b[33m800ms\\x1b[39m'\n * formatMsWithColor(1500) // '\\x1b[31m1.50s\\x1b[39m'\n * ```\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n if (ms <= 500) return styleText('green', formatted)\n if (ms <= 1000) return styleText('yellow', formatted)\n\n return styleText('red', formatted)\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { getElapsedMs } from '@internals/utils'\nimport { Diagnostics, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { formatMsWithColor, getIntro } from './banner.ts'\nimport type { Logger } from './defineLogger.ts'\nimport {\n buildProgressLine,\n createProgressCounters,\n formatCommandWithArgs,\n formatErrorFrames,\n formatMessage,\n formatVersions,\n getInputPath,\n recordPluginResult,\n resetProgressCounters,\n} from './utils.ts'\n\n/**\n * TTY logger for local development, with spinners and progress bars.\n */\nexport const clackLogger = {\n name: 'clack',\n install(context, options) {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const state = {\n ...createProgressCounters(),\n spinner: clack.spinner(),\n isSpinning: false,\n runningPlugins: new Set<string>(),\n activeProgress: new Map<string, { interval?: NodeJS.Timeout; progressBar: clack.ProgressResult }>(),\n activeHookLogs: new Map<string, { taskLog: ReturnType<typeof clack.taskLog>; hrStart: [number, number] }>(),\n }\n\n // Clear every active progress bar's interval, stop it, and drop the map.\n function stopActiveProgress() {\n for (const [, active] of state.activeProgress) {\n if (active.interval) {\n clearInterval(active.interval)\n }\n active.progressBar?.stop()\n }\n state.activeProgress.clear()\n }\n\n function reset() {\n stopActiveProgress()\n\n resetProgressCounters(state)\n state.spinner = clack.spinner()\n state.isSpinning = false\n state.runningPlugins.clear()\n state.activeHookLogs.clear()\n }\n\n // Label for the shared plugin bar, listing the plugins currently generating.\n function pluginProgressText(): string {\n const running = [...state.runningPlugins].map((name) => styleText('bold', name))\n return getMessage(running.length > 0 ? `Generating ${running.join(', ')}` : 'Generating plugins')\n }\n\n function showProgressStep() {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const line = buildProgressLine(state)\n if (line) {\n clack.log.step(getMessage(line))\n }\n }\n\n function getMessage(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n // Registers a handler that prints a fixed step message, skipped at silent level.\n function onStep<E extends keyof KubbHooks>(hook: E, message: string): void {\n context.hook(hook, () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n clack.log.step(getMessage(message))\n })\n }\n\n function stopSpinner(text?: string) {\n if (!state.isSpinning) {\n return\n }\n state.spinner.stop(text)\n state.isSpinning = false\n }\n\n context.hook('kubb:info', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n if (state.isSpinning) {\n state.spinner.message(text)\n return\n }\n clack.log.info(text)\n })\n\n context.hook('kubb:success', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage([styleText('blue', '✓'), message, logLevel >= logLevelMap.info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n if (state.isSpinning) {\n stopSpinner(text)\n return\n }\n clack.log.success(text)\n })\n\n context.hook('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n const text = getMessage(\n [styleText('yellow', '⚠'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '),\n )\n\n clack.log.warn(text)\n })\n\n context.hook('kubb:error', ({ error }) => {\n const text = [styleText('red', '✗'), error.message].join(' ')\n\n if (state.isSpinning) {\n stopSpinner(getMessage(text))\n return\n }\n clack.log.error(getMessage(text))\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (frames) {\n for (const frame of frames.frames) {\n clack.log.message(getMessage(styleText('dim', frame)))\n }\n\n if (frames.cause) {\n clack.log.message(styleText('dim', frames.cause.header))\n\n for (const frame of frames.cause.frames) {\n clack.log.message(getMessage(` ${styleText('dim', frame)}`))\n }\n }\n }\n })\n\n context.hook('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {\n return\n }\n\n stopSpinner()\n\n // Stop any lingering progress UI so the multi-line block renders cleanly.\n stopActiveProgress()\n\n // The version-update notice keeps its own framed box instead of the diagnostic gutter.\n if (Diagnostics.isUpdate(diagnostic)) {\n clack.box(\n `\\`v${diagnostic.currentVersion}\\` → \\`v${diagnostic.latestVersion}\\`\nRun \\`npm install -g @kubb/cli\\` to update`,\n 'Update available for `Kubb`',\n {\n width: 'auto',\n formatBorder: (s: string) => styleText('yellow', s),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n },\n )\n\n return\n }\n\n // The diagnostic carries the code and its own indented detail rows, so clear clack's\n // gutter and bar (`symbol`/`secondarySymbol`) and let the block stand on its own.\n const { headline, details } = Diagnostics.format(diagnostic)\n clack.log.message([headline, ...details], { symbol: '', secondarySymbol: '' })\n })\n\n // A `kubb studio` session emits these on the same emitter as its generations, so one logger\n // renders the whole command. The socket opens without being awaited, hence the spinner.\n context.hook('studio:connecting', ({ url }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n state.spinner = clack.spinner()\n state.spinner.start(getMessage(`Connecting to ${styleText('cyan', url)}`))\n state.isSpinning = true\n })\n\n context.hook('studio:connected', ({ url, versions }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(`Connected to ${styleText('cyan', url)} ${styleText('dim', `(${formatVersions(versions)})`)}`)\n\n if (state.isSpinning) {\n stopSpinner(text)\n return\n }\n clack.log.success(text)\n })\n\n context.hook('studio:ready', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n clack.log.success(getMessage('Ready to receive jobs'))\n })\n\n context.hook('studio:disconnected', ({ reason }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n stopSpinner()\n clack.log.warn(getMessage(`Kubb Studio ended the session (${reason})`))\n })\n\n context.hook('studio:command:start', ({ command }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n clack.log.info(getMessage(`Kubb Studio asked to ${styleText('bold', command)}`))\n })\n\n context.hook('studio:command:end', ({ command, info }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n clack.log.success(getMessage(`Finished ${command}${info ? ` ${styleText('dim', `(${info})`)}` : ''}`))\n })\n\n context.hook('studio:warn', ({ message }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n clack.log.warn(getMessage(message))\n })\n\n // Unguarded, like `kubb:error`: a failure stays visible even at silent.\n context.hook('studio:error', ({ error }) => {\n const text = getMessage([styleText('red', '✗'), error.message].join(' '))\n\n if (state.isSpinning) {\n stopSpinner(text)\n return\n }\n clack.log.error(text)\n })\n\n context.hook('kubb:lifecycle:start', async ({ version }) => {\n console.log(`\\n${getIntro({ title: 'The meta framework for code generation', description: 'Ready to start', version, areEyesOpen: true })}\\n`)\n\n reset()\n })\n\n context.hook('kubb:generation:start', ({ config }) => {\n reset()\n\n // Initialize progress tracking for this generation\n state.totalPlugins = config.plugins?.length ?? 0\n\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(\n ['Generation started', config.name ? `for ${styleText('dim', config.name)}` : undefined, getInputPath(config)].filter(Boolean).join(' '),\n )\n\n clack.intro(text)\n })\n\n // Plugins run concurrently, so they share a single progress bar. A bar per plugin\n // would make clack render them side by side and pile up keypress listeners.\n context.hook('kubb:plugin:start', ({ plugin }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n state.runningPlugins.add(plugin.name)\n\n const active = state.activeProgress.get('plugins')\n if (active) {\n active.progressBar.advance(0, pluginProgressText())\n return\n }\n\n const progressBar = clack.progress({\n style: 'block',\n max: Math.max(state.totalPlugins, 1),\n size: 30,\n })\n progressBar.start(pluginProgressText())\n // Catch up to plugins already finished before this bar opened.\n progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText())\n state.activeProgress.set('plugins', { progressBar })\n })\n\n context.hook('kubb:plugin:end', ({ plugin, success }) => {\n stopSpinner()\n\n const active = state.activeProgress.get('plugins')\n\n if (!active || logLevel <= logLevelMap.silent) {\n return\n }\n\n state.runningPlugins.delete(plugin.name)\n recordPluginResult(state, success)\n active.progressBar.advance(1, pluginProgressText())\n\n // Close the bar once nothing is generating, then print the progress step.\n if (state.runningPlugins.size === 0) {\n active.progressBar.stop(getMessage('Plugins generated'))\n state.activeProgress.delete('plugins')\n showProgressStep()\n }\n })\n\n context.hook('kubb:files:processing:start', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n state.totalFiles = files.length\n state.processedFiles = 0\n\n const text = `Writing ${files.length} files`\n const progressBar = clack.progress({\n style: 'block',\n max: files.length,\n size: 30,\n })\n\n context.callHook('kubb:info', { message: text })\n progressBar.start(getMessage(text))\n state.activeProgress.set('files', { progressBar })\n })\n\n context.hook('kubb:files:processing:update', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n const active = state.activeProgress.get('files')\n for (const { file, config } of files) {\n state.processedFiles++\n if (active) {\n active.progressBar.advance(undefined, `Writing ${relative(config.root, file.path)}`)\n }\n }\n })\n context.hook('kubb:files:processing:end', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n stopSpinner()\n\n const text = getMessage('Files written successfully')\n const active = state.activeProgress.get('files')\n\n if (!active) {\n return\n }\n\n active.progressBar.stop(text)\n state.activeProgress.delete('files')\n\n // Show final progress step after files are written\n showProgressStep()\n })\n\n context.hook('kubb:generation:end', ({ config }) => {\n stopSpinner()\n\n const text = getMessage(config.name ? `Generation completed for ${styleText('dim', config.name)}` : 'Generation completed')\n\n clack.outro(text)\n })\n\n onStep('kubb:format:start', 'Formatting')\n onStep('kubb:lint:start', 'Linting')\n onStep('kubb:hooks:start', 'Running hooks')\n\n context.hook('kubb:hook:start', ({ id, command, name, args }) => {\n if (logLevel <= logLevelMap.silent || !id) {\n return\n }\n\n stopSpinner()\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n const title = getMessage(`Running ${styleText('dim', name ?? commandWithArgs)}`)\n const taskLog = clack.taskLog({ title })\n\n state.activeHookLogs.set(id, { taskLog, hrStart: process.hrtime() })\n })\n\n // Registered only when not silent, so its presence is what tells the runner to stream\n // (`kubb:hook:line` listenerCount). At silent level the listener is absent, so no streaming happens.\n if (logLevel > logLevelMap.silent) {\n context.hook('kubb:hook:line', ({ id, line }) => {\n const active = state.activeHookLogs.get(id)\n active?.taskLog.message(styleText('dim', line))\n })\n }\n\n context.hook('kubb:hook:end', ({ id, command, name, args, success, error, stdout, stderr }) => {\n if (!id) {\n return\n }\n\n if (logLevel <= logLevelMap.silent) {\n // Even when silent, surface a failed hook's captured output.\n if (!success) {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n }\n return\n }\n\n const active = state.activeHookLogs.get(id)\n if (!active) {\n return\n }\n state.activeHookLogs.delete(id)\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n const duration = formatMsWithColor(getElapsedMs(active.hrStart))\n\n if (success) {\n active.taskLog.success(getMessage(`${styleText('dim', name ?? commandWithArgs)} completed in ${duration}`))\n } else {\n // The hook's output already reached the taskLog live via `kubb:hook:line`, so `showLog`\n // replays it here. `kubb:hook:end` carries no captured output on the streaming path.\n const reason = error?.message ? ` (${error.message})` : ''\n active.taskLog.error(getMessage(`${styleText('dim', name ?? commandWithArgs)} failed${reason}`), { showLog: true })\n }\n })\n\n context.hook('kubb:lifecycle:end', () => {\n reset()\n })\n },\n} satisfies Logger\n","import { relative } from 'node:path'\nimport { formatMs } from '@internals/utils'\nimport { Diagnostics, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport type { Logger } from './defineLogger.ts'\nimport { createHookTimer, formatCommandWithArgs, formatErrorFrames, formatMessage, formatVersions, getInputPath } from './utils.ts'\n\n/**\n * Plain console adapter for non-TTY environments, built on `console.log`.\n */\nexport const plainLogger = {\n name: 'plain',\n install(context, options) {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const hookTimer = createHookTimer()\n\n function getMessage(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n // Registers a handler that logs a fixed message, skipped at silent level.\n function onStep<E extends keyof KubbHooks>(hook: E, message: string): void {\n context.hook(hook, () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(message))\n })\n }\n\n context.hook('kubb:info', ({ message, info }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(['ℹ', message, info].join(' '))\n\n console.log(text)\n })\n\n context.hook('kubb:success', ({ message, info = '' }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(['✓', message, logLevel >= logLevelMap.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.hook('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n const text = getMessage(['⚠', message, logLevel >= logLevelMap.info ? info : undefined].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.hook('kubb:error', ({ error }) => {\n const text = getMessage(['✗', error.message].join(' '))\n\n console.log(text)\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (frames) {\n for (const frame of frames.frames) {\n console.log(getMessage(frame))\n }\n\n if (frames.cause) {\n console.log(frames.cause.header)\n\n for (const frame of frames.cause.frames) {\n console.log(getMessage(` ${frame}`))\n }\n }\n }\n })\n\n context.hook('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {\n return\n }\n console.log(getMessage(Diagnostics.formatLines(diagnostic).join('\\n')))\n })\n\n // A `kubb studio` session emits these on the same emitter as its generations, so one logger\n // renders the whole command. Nothing to animate here, so no spinner.\n context.hook('studio:connecting', ({ url }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(`Connecting to ${url}`))\n })\n\n context.hook('studio:connected', ({ url, versions }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(`✓ Connected to ${url} (${formatVersions(versions)})`))\n })\n\n context.hook('studio:ready', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage('✓ Ready to receive jobs'))\n })\n\n context.hook('studio:disconnected', ({ reason }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n console.log(getMessage(`⚠ Kubb Studio ended the session (${reason})`))\n })\n\n context.hook('studio:command:start', ({ command }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(`Kubb Studio asked to ${command}`))\n })\n\n context.hook('studio:command:end', ({ command, info }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n console.log(getMessage(`✓ Finished ${command}${info ? ` (${info})` : ''}`))\n })\n\n context.hook('studio:warn', ({ message }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n console.log(getMessage(`⚠ ${message}`))\n })\n\n // Unguarded, like `kubb:error`: a failure stays visible even at silent.\n context.hook('studio:error', ({ error }) => {\n console.log(getMessage(`✗ ${error.message}`))\n })\n\n context.hook('kubb:lifecycle:start', ({ version }) => {\n console.log(`Kubb CLI v${version}`)\n })\n\n context.hook('kubb:generation:start', ({ config }) => {\n const text = getMessage(['Generation started', getInputPath(config)].filter(Boolean).join(' '))\n\n console.log(text)\n })\n\n context.hook('kubb:plugin:start', ({ plugin }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n const text = getMessage(`Generating ${plugin.name}`)\n\n console.log(text)\n })\n\n context.hook('kubb:plugin:end', ({ plugin, duration, success }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const durationStr = formatMs(duration)\n const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`)\n\n console.log(text)\n })\n\n context.hook('kubb:files:processing:start', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage(`Writing ${files.length} files`)\n\n console.log(text)\n })\n\n context.hook('kubb:files:processing:update', ({ files }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n for (const { file, config } of files) {\n console.log(getMessage(`Writing ${relative(config.root, file.path)}`))\n }\n })\n\n context.hook('kubb:files:processing:end', () => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const text = getMessage('Files written successfully')\n\n console.log(text)\n })\n\n context.hook('kubb:generation:end', ({ config }) => {\n const text = getMessage(config.name ? `Generation completed for ${config.name}` : 'Generation completed')\n\n console.log(text)\n })\n\n onStep('kubb:format:start', 'Format started')\n onStep('kubb:format:end', 'Format completed')\n onStep('kubb:lint:start', 'Lint started')\n onStep('kubb:lint:end', 'Lint completed')\n onStep('kubb:hooks:start', 'Hooks started')\n onStep('kubb:hooks:end', 'Hooks completed')\n\n context.hook('kubb:hook:start', ({ id, command, name, args }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n if (id) {\n hookTimer.start(id)\n }\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n console.log(getMessage(`Hook ${name ?? commandWithArgs} started`))\n })\n\n context.hook('kubb:hook:end', ({ id, command, name, args, success, error, stdout, stderr }) => {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const ms = id ? hookTimer.end(id) : undefined\n const durationStr = ms !== undefined ? ` in ${formatMs(ms)}` : ''\n\n const commandWithArgs = formatCommandWithArgs(command, args)\n\n if (success) {\n console.log(getMessage(`✓ Hook ${name ?? commandWithArgs} completed${durationStr}`))\n } else {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n const reason = error?.message ? ` (${error.message})` : ''\n console.log(getMessage(`✗ Hook ${name ?? commandWithArgs} failed${durationStr}${reason}`))\n }\n })\n },\n} satisfies Logger\n","import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport type { Config, Reporter, ReporterContext } from '@kubb/core'\nimport { logLevel as logLevelMap } from '@kubb/core'\nimport type { StudioConnectedContext } from '@kubb/studio'\nimport { getAgentName } from '../agent.ts'\nimport { canUseTTY } from '../utils/env.ts'\nimport type { LoggerContext, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/**\n * Display path for a config's input: the string form, or its `path` field when the input is an\n * object. Loggers show it alongside `Generation started`.\n */\nexport function getInputPath(config: Config): string | undefined {\n const { input } = config\n if (typeof input === 'string') return input\n return typeof input?.path === 'string' ? input.path : undefined\n}\n\n/**\n * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.\n * Shared across all logger adapters to avoid duplication.\n */\nexport function formatMessage(message: string, logLevel: number): string {\n if (logLevel >= logLevelMap.verbose) {\n const timestamp = new Date().toLocaleTimeString('en-US', {\n hour12: false,\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n return `${styleText('dim', `[${timestamp}]`)} ${message}`\n }\n return message\n}\n\n/**\n * Renders the versions from a `studio:connected` event as one parenthetical. The runtime is listed\n * only when it differs from the host, and Studio's only when it sent one.\n */\nexport function formatVersions({ studio, kubb, agent }: StudioConnectedContext['versions']): string {\n return [`v${agent}`, kubb !== agent ? `runtime v${kubb}` : undefined, studio ? `Studio v${studio}` : undefined].filter(Boolean).join(', ')\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n */\nfunction toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n\n/**\n * First stack frames for verbose error output, including an optional `cause` chain.\n */\nexport function formatErrorFrames(error: Error): { frames: Array<string>; cause?: { header: string; frames: Array<string> } } | null {\n if (!error.stack) {\n return null\n }\n\n const frames = error.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim())\n const caused = toCause(error)\n\n if (!caused?.stack) {\n return { frames }\n }\n\n return {\n frames,\n cause: {\n header: `└─ caused by ${caused.message}`,\n frames: caused.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim()),\n },\n }\n}\n\ntype ProgressState = {\n /**\n * Total number of plugins scheduled for this generation run.\n */\n totalPlugins: number\n /**\n * Number of plugins that have finished without error.\n */\n completedPlugins: number\n /**\n * Number of plugins that exited with an error.\n */\n failedPlugins: number\n /**\n * Total number of files expected to be written.\n */\n totalFiles: number\n /**\n * Number of files written so far.\n */\n processedFiles: number\n /**\n * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.\n */\n hrStart: [number, number]\n}\n\n/**\n * Build the progress summary line shown by the clack logger.\n * Returns null when there is nothing to display.\n */\nexport function buildProgressLine(state: ProgressState): string | null {\n const parts: Array<string> = []\n const duration = formatMs(getElapsedMs(state.hrStart))\n\n if (state.totalPlugins > 0) {\n const pluginStr =\n state.failedPlugins > 0\n ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`\n : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`\n parts.push(pluginStr)\n }\n\n if (state.totalFiles > 0) {\n parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)\n }\n\n if (parts.length === 0) {\n return null\n }\n\n parts.push(`${styleText('green', duration)} elapsed`)\n return parts.join(styleText('dim', ' | '))\n}\n\n/**\n * Creates the per-run progress counters used by the clack logger.\n */\nexport function createProgressCounters(): ProgressState {\n return {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n }\n}\n\n/**\n * Resets the progress counters in place at the start/end of a generation run.\n */\nexport function resetProgressCounters(state: ProgressState): void {\n state.totalPlugins = 0\n state.completedPlugins = 0\n state.failedPlugins = 0\n state.totalFiles = 0\n state.processedFiles = 0\n state.hrStart = process.hrtime()\n}\n\n/**\n * Records a finished plugin against the progress counters.\n */\nexport function recordPluginResult(state: ProgressState, success: boolean): void {\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n}\n\n/**\n * Tracks per-hook start times so a logger can report a hook's elapsed duration.\n * Used by the plain logger, which keys timing by hook `id`.\n */\ntype HookTimer = {\n start(id: string): void\n /**\n * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.\n */\n end(id: string): number | undefined\n}\n\n/**\n * Creates a {@link HookTimer} backed by a private `id → hrtime` map.\n */\nexport function createHookTimer(): HookTimer {\n const starts = new Map<string, [number, number]>()\n\n return {\n start(id: string): void {\n starts.set(id, process.hrtime())\n },\n end(id: string): number | undefined {\n const hrStart = starts.get(id)\n if (!hrStart) {\n return undefined\n }\n starts.delete(id)\n return getElapsedMs(hrStart)\n },\n }\n}\n\n/**\n * Join a command and its optional args into a single display string.\n *\n * @example With args\n * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`\n */\nexport function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {\n return args?.length ? `${command} ${args.join(' ')}` : command\n}\n\n/**\n * Bridges a {@link Reporter} onto the run's hook emitter: calls `report` with each config's\n * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.\n */\nexport function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart }, ctx)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/**\n * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are\n * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This\n * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the\n * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.\n *\n * Loggers and reporters are independent, except for `cli`: it both installs the live logger view\n * here and registers as a reporter that prints the per-config summary. The `json` reporter owns\n * stdout, so the whole `cli` reporter (live logger and summary) is skipped whenever `json` is\n * among the reporters, even if `cli` is also listed.\n */\nasync function setupReporters(context: LoggerContext, { logLevel, reporters }: LoggerOptions & { reporters: ReadonlyArray<Reporter> }): Promise<void> {\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name === 'cli') {\n if (hasJson) {\n continue\n }\n // Spinners and cursor-movement escapes are hard for an AI coding agent to parse, even over a pseudo-TTY.\n const logger = canUseTTY() && !getAgentName() ? clackLogger : plainLogger\n await logger.install(context, { logLevel })\n }\n\n installReporter(context, reporter, ctx)\n }\n}\n\nexport default setupReporters\n\n/**\n * Picks the reporters whose `name` matches one of `names`, in the order the names are given.\n * The config carries every available reporter, and the host selects which to activate by name\n * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are\n * skipped.\n */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n const seen = new Set<string>()\n const selected: Array<Reporter> = []\n\n for (const name of names) {\n if (seen.has(name)) {\n continue\n }\n seen.add(name)\n\n const reporter = reporters.find((candidate) => candidate.name === name)\n if (reporter) {\n selected.push(reporter)\n }\n }\n\n return selected\n}\n","import { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Per-call options for {@link ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { basename, dirname, resolve } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createModuleLoader } from '@internals/shared'\nimport { toError, tokenize } from '@internals/utils'\nimport type { CLIOptions, Config, KubbHooks, PossibleConfig, PostGenerateCommand, Hookable } from '@kubb/core'\nimport { NonZeroExitError, x } from 'tinyexec'\nimport { type LoadConfigResult, type LoadConfigSource, loadConfig } from 'unconfig'\nimport { isGreater, isValid, truncate } from 'verkit'\nimport { URL_WATCHER_INTERVAL_MS, URL_WATCHER_TIMEOUT_MS, WATCHER_DEBOUNCE_MS, WATCHER_IGNORED_PATHS } from '../../constants.ts'\n\nconst loader = createModuleLoader()\n\n// Kubb configs are JS/TS modules (they call `defineConfig`/`pluginX()`), so YAML and JSON are not\n// supported. The jiti loader handles every module format and the JSX runtime, returning the default export.\nconst tsLoader = (configFile: string) => loader.load(configFile, { default: true })\n\nconst MODULE_NAME = 'kubb'\n\nconst SEARCH_FILES = ['', '.config/', 'configs/'].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`])\nconst SEARCH_EXTENSIONS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']\n\ntype GetConfigsOptions = {\n /**\n * Explicit path to the Kubb config file. When omitted, the loader searches up from the current directory.\n */\n configPath?: string\n /**\n * Optional OpenAPI input path or URL that overrides `config.input` for this run.\n */\n input?: string\n /**\n * Watch flag forwarded to the user's `defineConfig` function.\n */\n watch?: boolean\n /**\n * Log level forwarded to the user's `defineConfig` function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /**\n * Absolute path to the resolved config file.\n */\n configPath: string\n /**\n * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.\n */\n configs: Array<Config>\n}\n\n/**\n * Discovers the Kubb config and resolves it into a normalized array of configs.\n * Every config in the result is guaranteed to have a `plugins` array.\n */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const abs = configPath ? resolve(configPath) : undefined\n const sources: Array<LoadConfigSource<unknown>> = abs\n ? [{ files: [basename(abs)], extensions: [], parser: tsLoader }]\n : [{ files: SEARCH_FILES, extensions: SEARCH_EXTENSIONS, parser: tsLoader }]\n\n let result: LoadConfigResult<unknown>\n try {\n result = await loadConfig<unknown>({ cwd: abs ? dirname(abs) : process.cwd(), sources, merge: false })\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n const [filepath] = result.sources\n if (!result.config || !filepath) {\n throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n const config = result.config as PossibleConfig<CLIOptions>\n const cli: CLIOptions = { config: configPath, input, watch, logLevel }\n const resolved = await (typeof config === 'function' ? config(cli) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return {\n configPath: filepath,\n configs: userConfigs.map((item) => {\n const config: Config = { ...item, plugins: item.plugins ?? [] }\n return config\n }),\n }\n}\n\ntype RunPostGenerateOptions = {\n commands: Array<PostGenerateCommand>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Outcome of a single hook subprocess, returned by `runHook` alongside the\n * `kubb:hook:end` hook it emits for the loggers.\n */\ntype HookResult = {\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * What went wrong, `null` when the command succeeded.\n */\n error: Error | null\n /**\n * Captured stdout, only present on a non-zero exit.\n */\n stdout?: string\n /**\n * Captured stderr, only present on a non-zero exit.\n */\n stderr?: string\n}\n\n/**\n * Returns `true` when `latest` is a newer semver version than `current`. Compares each numeric\n * part, so `5.10.0` beats `5.9.0` where a plain string comparison would not. Prerelease\n * suffixes are ignored, and a malformed version never reports an update.\n *\n * @example Double-digit minor\n * `isNewerVersion('5.9.0', '5.10.0') // true`\n *\n * @example String comparison would get this wrong the other way\n * `isNewerVersion('5.10.0', '5.9.0') // false`\n */\nexport function isNewerVersion(current: string, latest: string): boolean {\n if (!isValid(current) || !isValid(latest)) return false\n\n return isGreater(truncate(latest, 'patch') as string, truncate(current, 'patch') as string)\n}\n\n/**\n * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's\n * outcome, so the caller can turn failures into diagnostics.\n */\nexport async function runPostGenerate({ commands, hooks }: RunPostGenerateOptions): Promise<Array<HookResult>> {\n const results: Array<HookResult> = []\n\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [cmd, ...args] = tokenize(command)\n if (!cmd) continue\n\n const hookId = randomUUID()\n const commandWithArgs = [cmd, ...args].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: cmd, name, args })\n results.push(await runHook({ id: hookId, command: cmd, name, args, commandWithArgs, hooks }))\n }\n\n return results\n}\n\ntype RunHookOptions = {\n id: string\n command: string\n name?: string\n args?: ReadonlyArray<string>\n commandWithArgs: string\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Spawns a hook command and returns its outcome, mirroring it through `kubb:hook:end` for the\n * loggers. A non-zero exit returns `success: false` rather than throwing, so the caller can turn\n * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`\n * only while a listener is attached.\n */\nexport async function runHook({ id, command, name, args, commandWithArgs, hooks }: RunHookOptions): Promise<HookResult> {\n const emitEnd = async (result: HookResult): Promise<HookResult> => {\n await hooks.callHook('kubb:hook:end', { command, name, args, id, ...result })\n return result\n }\n\n // Only stream line-by-line when a logger is listening, so the non-streaming plain\n // logger doesn't pay to iterate the subprocess output.\n const stream = hooks.listenerCount('kubb:hook:line') > 0\n\n try {\n const proc = x(command, [...(args ?? [])], {\n nodeOptions: { detached: process.platform !== 'win32' },\n throwOnError: true,\n })\n\n if (stream) {\n for await (const line of proc) {\n await hooks.callHook('kubb:hook:line', { id, line })\n }\n }\n\n await proc\n await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? commandWithArgs)} successfully executed` })\n return emitEnd({ success: true, error: null })\n } catch (err) {\n if (!(err instanceof NonZeroExitError)) {\n return emitEnd({ success: false, error: toError(err) })\n }\n\n const stderr = err.output?.stderr ?? ''\n const stdout = err.output?.stdout ?? ''\n\n const error = new Error(`Hook execute failed: ${commandWithArgs}`)\n // Signal the failure via the result and `kubb:hook:end` only, carrying the captured output so\n // the logger can render it. The caller turns this into a coded diagnostic and emits that\n // through `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.\n return emitEnd({ success: false, error, stdout, stderr })\n }\n}\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one build, and builds never overlap: changes during a build queue exactly\n * one rebuild.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<void> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n}\n\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body within the timeout. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, timeoutMs: number = URL_WATCHER_TIMEOUT_MS): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n try {\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)])\n const response = await fetch(url, { signal })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`)\n }\n const body = await response.text()\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n } catch {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n }\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n void poll()\n\n return stop\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,aAAa;CACxB,UAAU;EACR,SAAS;EAC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