@kubb/cli 5.2.2 → 5.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{Telemetry-DKfJQxnC.cjs → Telemetry-C-y1OMHs.cjs} +23 -1
  2. package/dist/Telemetry-C-y1OMHs.cjs.map +1 -0
  3. package/dist/{Telemetry-BCTY-Nzq.js → Telemetry-DIDDCARm.js} +12 -2
  4. package/dist/Telemetry-DIDDCARm.js.map +1 -0
  5. package/dist/{generate-FnqkFRDH.js → generate-BOM6Jh0K.js} +3 -3
  6. package/dist/{generate-FnqkFRDH.js.map → generate-BOM6Jh0K.js.map} +1 -1
  7. package/dist/{generate-ZWvsWer2.cjs → generate-DUOuZSY7.cjs} +3 -3
  8. package/dist/{generate-ZWvsWer2.cjs.map → generate-DUOuZSY7.cjs.map} +1 -1
  9. package/dist/index.cjs +7 -7
  10. package/dist/index.js +7 -7
  11. package/dist/{init-onrLNkdI.cjs → init-B7ehKuMb.cjs} +2 -2
  12. package/dist/{init-onrLNkdI.cjs.map → init-B7ehKuMb.cjs.map} +1 -1
  13. package/dist/{init-BQ0JXhap.js → init-CjJsi1ea.js} +2 -2
  14. package/dist/{init-BQ0JXhap.js.map → init-CjJsi1ea.js.map} +1 -1
  15. package/dist/{package-B45PcHOn.cjs → package-BtgEczay.cjs} +2 -2
  16. package/dist/package-BtgEczay.cjs.map +1 -0
  17. package/dist/package-DtLAJtma.js +6 -0
  18. package/dist/package-DtLAJtma.js.map +1 -0
  19. package/dist/{run-g2mZr8BS.js → run-BivS_md8.js} +3 -3
  20. package/dist/{run-g2mZr8BS.js.map → run-BivS_md8.js.map} +1 -1
  21. package/dist/{run-DuRIXbnI.cjs → run-Bk_QSCjS.cjs} +3 -3
  22. package/dist/{run-DuRIXbnI.cjs.map → run-Bk_QSCjS.cjs.map} +1 -1
  23. package/dist/{run-DhIqGkoY.js → run-BlYDo-vD.js} +4 -4
  24. package/dist/{run-DhIqGkoY.js.map → run-BlYDo-vD.js.map} +1 -1
  25. package/dist/{run-DOKY1xdi.js → run-CE7d8LvB.js} +15 -6
  26. package/dist/run-CE7d8LvB.js.map +1 -0
  27. package/dist/{run-Bwj2qS0v.cjs → run-Ce3ZoyDU.cjs} +3 -3
  28. package/dist/{run-Bwj2qS0v.cjs.map → run-Ce3ZoyDU.cjs.map} +1 -1
  29. package/dist/{run-DWselriZ.cjs → run-CzyLOeT1.cjs} +15 -6
  30. package/dist/run-CzyLOeT1.cjs.map +1 -0
  31. package/dist/{run-CinpPEto.js → run-Df7AhaaH.js} +3 -3
  32. package/dist/{run-CinpPEto.js.map → run-Df7AhaaH.js.map} +1 -1
  33. package/dist/{run-gpEaRaDp.cjs → run-DmRYvDCi.cjs} +4 -4
  34. package/dist/{run-gpEaRaDp.cjs.map → run-DmRYvDCi.cjs.map} +1 -1
  35. package/dist/{utils-CzoNURwq.js → utils-DOpJIiJM.js} +77 -3
  36. package/dist/{utils-CzoNURwq.js.map → utils-DOpJIiJM.js.map} +1 -1
  37. package/dist/{utils-B0SrWoNh.cjs → utils-DT_n0UZH.cjs} +88 -2
  38. package/dist/utils-DT_n0UZH.cjs.map +1 -0
  39. package/package.json +8 -8
  40. package/dist/Telemetry-BCTY-Nzq.js.map +0 -1
  41. package/dist/Telemetry-DKfJQxnC.cjs.map +0 -1
  42. package/dist/package-B45PcHOn.cjs.map +0 -1
  43. package/dist/package-CDmvOHxC.js +0 -6
  44. package/dist/package-CDmvOHxC.js.map +0 -1
  45. package/dist/run-DOKY1xdi.js.map +0 -1
  46. package/dist/run-DWselriZ.cjs.map +0 -1
  47. package/dist/utils-B0SrWoNh.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"run-DhIqGkoY.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.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 { 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\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(getKubbHome(), 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 { 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, getKubbHome, readCredentials, writeCredentials } from './credentials.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status'] 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\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 */\nasync 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(path.join(getKubbHome(), 'cache')))\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 if (options.logLevel !== 'silent') {\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 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 })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,OAAO,GAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACrIA,SAAgB,cAAsB;CACpC,OAAO,QAAQ,IAAI,aAAa,KAAK,KAAK,QAAQ,GAAG,OAAO;AAC9D;AAEA,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAO,KAAK,KAAK,YAAY,GAAG,oBAAoB;AACtD;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,MAAM,MAAM,KAAK,mBAAmB,CAAC,CAAC,CAAC,YAAY,IAAI;CAC7D,IAAI,CAAC,KACH,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,OAAO,mBAAmB;CAEhC,MAAM,MAAM,KAAK,QAAQ,IAAI,GAAG;EAAE,WAAW;EA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,gBAAgB,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,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;CACnB,CAAC;AACH"}
1
+ {"version":3,"file":"run-BlYDo-vD.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.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 { 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\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(getKubbHome(), 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 { 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, getKubbHome, readCredentials, writeCredentials } from './credentials.ts'\n\nconst ACTIONS = ['connect', 'login', 'logout', 'status'] 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\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 */\nasync 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(path.join(getKubbHome(), 'cache')))\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 if (options.logLevel !== 'silent') {\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 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 })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,KAAK,MAA+B;CACxD,IAAI,QAAQ,OACV,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,KAAK;CAE7B,OAAO,SAAS,MAAM,EAAE,UAAU,OAAO,CAAC;AAC5C;;;;;;;;;AAsGA,eAAsB,MAAM,MAA6B;CACvD,OAAO,GAAG,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;AAClD;;;;;;;ACrIA,SAAgB,cAAsB;CACpC,OAAO,QAAQ,IAAI,aAAa,KAAK,KAAK,QAAQ,GAAG,OAAO;AAC9D;AAEA,MAAM,uBAAuB;;;;AAK7B,SAAgB,qBAA6B;CAC3C,OAAO,KAAK,KAAK,YAAY,GAAG,oBAAoB;AACtD;;;;;;AAyBA,eAAsB,kBAA+C;CACnE,MAAM,MAAM,MAAM,KAAK,mBAAmB,CAAC,CAAC,CAAC,YAAY,IAAI;CAC7D,IAAI,CAAC,KACH,OAAO;CAGT,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAOA,eAAsB,iBAAiB,aAAyC;CAC9E,MAAM,OAAO,mBAAmB;CAEhC,MAAM,MAAM,KAAK,QAAQ,IAAI,GAAG;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CAChE,MAAM,UAAU,MAAM,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,EAAE,MAAM,IAAM,CAAC;AAC7E;;;;AAKA,eAAsB,mBAAkC;CACtD,MAAM,MAAM,mBAAmB,CAAC;AAClC;;;AC7CA,MAAM,UAAU;CAAC;CAAW;CAAS;CAA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Q,IAAI,4BAA4B;IACxC;GACF,KAAK;IACH,MAAM,OAAO,OAAO;IACpB;GACF,KAAK;IACH,MAAM,QAAQ,OAAO;IACrB;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;CACnB,CAAC;AACH"}
@@ -1,8 +1,8 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { t as toError } from "./errors-C8yNfV7w.js";
3
- import { i as KUBB_NPM_PACKAGE_URL, o as UPDATE_CHECK_TIMEOUT_MS, r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-BCTY-Nzq.js";
4
- import { a as startWatcher, c as FORMATTER_PREFERENCE, d as formatters, f as linters, i as runPostGenerate, l as LINTER_PREFERENCE, n as isNewerVersion, o as selectReporters, r as runHook, s as setupReporters, t as getConfigs, u as detectTool } from "./utils-CzoNURwq.js";
5
- import { t as version } from "./package-CDmvOHxC.js";
3
+ import { i as KUBB_NPM_PACKAGE_URL, o as UPDATE_CHECK_TIMEOUT_MS, r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-DIDDCARm.js";
4
+ import { a as runPostGenerate, c as selectReporters, d as LINTER_PREFERENCE, f as detectTool, i as runHook, l as setupReporters, m as linters, n as getConfigs, o as startUrlWatcher, p as formatters, r as isNewerVersion, s as startWatcher, t as fetchUrlBody, u as FORMATTER_PREFERENCE } from "./utils-DOpJIiJM.js";
5
+ import { t as version } from "./package-DtLAJtma.js";
6
6
  import { i as logInfo, r as logError, s as logStep } from "./output-LZvrgF3z.js";
7
7
  import { styleText } from "node:util";
8
8
  import { randomUUID } from "node:crypto";
@@ -233,7 +233,8 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
233
233
  let anyFailed = false;
234
234
  for (const config of configs) {
235
235
  const effectiveInput = input ?? config.input;
236
- const watchPath = typeof effectiveInput === "string" && getInputKind(effectiveInput) === "file" ? effectiveInput : void 0;
236
+ const inputKind = typeof effectiveInput === "string" ? getInputKind(effectiveInput) : void 0;
237
+ const watchPath = inputKind === "file" || inputKind === "url" ? effectiveInput : void 0;
237
238
  if (watchPath && watch) {
238
239
  const watchedPaths = [watchPath];
239
240
  const build = async (paths) => {
@@ -246,12 +247,20 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
246
247
  });
247
248
  logStep(styleText("yellow", `Watching for changes in ${paths.join(" and ")}`));
248
249
  };
250
+ const initialBody = inputKind === "url" ? await fetchUrlBody(watchPath) : void 0;
249
251
  try {
250
252
  await build(watchedPaths);
251
253
  } catch (buildError) {
252
254
  await hooks.callHook("kubb:error", { error: toError(buildError) });
253
255
  }
254
- await startWatcher(watchedPaths, build, {
256
+ if (inputKind === "url") startUrlWatcher(watchPath, build, {
257
+ log: {
258
+ info: logInfo,
259
+ error: logError
260
+ },
261
+ initialBody
262
+ });
263
+ else await startWatcher(watchedPaths, build, {
255
264
  info: logInfo,
256
265
  error: logError
257
266
  });
@@ -278,4 +287,4 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
278
287
  //#endregion
279
288
  export { run };
280
289
 
281
- //# sourceMappingURL=run-DOKY1xdi.js.map
290
+ //# sourceMappingURL=run-CE7d8LvB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-CE7d8LvB.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const available = configs[0]?.reporters ?? []\n const reporters = selectReporters(available, requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAA,YAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,IAAI,UA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./errors-C-wEou02.cjs");
3
- const require_Telemetry = require("./Telemetry-DKfJQxnC.cjs");
4
- const require_package = require("./package-B45PcHOn.cjs");
3
+ const require_Telemetry = require("./Telemetry-C-y1OMHs.cjs");
4
+ const require_package = require("./package-BtgEczay.cjs");
5
5
  let node_util = require("node:util");
6
6
  let node_process = require("node:process");
7
7
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
@@ -54,4 +54,4 @@ const runner = async ({ values }) => {
54
54
  //#endregion
55
55
  exports.runner = runner;
56
56
 
57
- //# sourceMappingURL=run-Bwj2qS0v.cjs.map
57
+ //# sourceMappingURL=run-Ce3ZoyDU.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-Bwj2qS0v.cjs","names":["process","sendTelemetry","buildTelemetryEvent","styleText","toError"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/validate.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, version }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'validate', kubbVersion: version, hrStart, status }))\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n const adapter = adapterOas()\n if (!adapter.validate) {\n throw new Error('The loaded adapter does not support validation.')\n }\n\n await adapter.validate(input, { throwOnError: true })\n await report('success')\n\n console.log('✅ Validation success')\n } catch (error) {\n await report('failed')\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(toError(error).message)\n\n process.exit(1)\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/adapter-oas` stays out of the process for every other\n * command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({ input: values.input, version })\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,WAA2C;CAC5E,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiCC,kBAAAA,cAAcC,kBAAAA,oBAAoB;EAAE,SAAS;EAAY,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAElJ,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,MAAM,iDAAiD;EAGnE,MAAM,QAAQ,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACpD,MAAM,OAAO,SAAS;EAEtB,QAAQ,IAAI,sBAAsB;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,IAAI,iBAAiB,SAAS,qBAAqB,KAAK,MAAM,OAAO,GAAG;GACtE,QAAQ,OAAA,GAAMC,UAAAA,UAAAA,CAAU,OAAO,iDAAiD,CAAC;GACjF,QAAQ,MAAM,EAAE;GAChB,QAAQ,MAAM,kBAAkB;GAChC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,CAAC;GAClE,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,QAAQ,CAAC;GACzC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,kCAAkC,CAAC;GACnE,QAAQ,MAAM,EAAE;EAClB;EACA,QAAQ,MAAM,qBAAqB;EACnC,QAAQ,MAAMC,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EAEpC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EAAE,OAAO,OAAO;EAAO,SAAA,gBAAA;CAAQ,CAAC;AAC5C"}
1
+ {"version":3,"file":"run-Ce3ZoyDU.cjs","names":["process","sendTelemetry","buildTelemetryEvent","styleText","toError"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/validate.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, version }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'validate', kubbVersion: version, hrStart, status }))\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n const adapter = adapterOas()\n if (!adapter.validate) {\n throw new Error('The loaded adapter does not support validation.')\n }\n\n await adapter.validate(input, { throwOnError: true })\n await report('success')\n\n console.log('✅ Validation success')\n } catch (error) {\n await report('failed')\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(toError(error).message)\n\n process.exit(1)\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/adapter-oas` stays out of the process for every other\n * command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({ input: values.input, version })\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,WAA2C;CAC5E,MAAM,UAAUA,aAAAA,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiCC,kBAAAA,cAAcC,kBAAAA,oBAAoB;EAAE,SAAS;EAAY,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAElJ,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,MAAM,iDAAiD;EAGnE,MAAM,QAAQ,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACpD,MAAM,OAAO,SAAS;EAEtB,QAAQ,IAAI,sBAAsB;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,IAAI,iBAAiB,SAAS,qBAAqB,KAAK,MAAM,OAAO,GAAG;GACtE,QAAQ,OAAA,GAAMC,UAAAA,UAAAA,CAAU,OAAO,iDAAiD,CAAC;GACjF,QAAQ,MAAM,EAAE;GAChB,QAAQ,MAAM,kBAAkB;GAChC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,CAAC;GAClE,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,QAAQ,CAAC;GACzC,QAAQ,OAAA,GAAMA,UAAAA,UAAAA,CAAU,QAAQ,kCAAkC,CAAC;GACnE,QAAQ,MAAM,EAAE;EAClB;EACA,QAAQ,MAAM,qBAAqB;EACnC,QAAQ,MAAMC,eAAAA,QAAQ,KAAK,CAAC,CAAC,OAAO;EAEpC,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EAAE,OAAO,OAAO;EAAO,SAAA,gBAAA;CAAQ,CAAC;AAC5C"}
@@ -1,8 +1,8 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
2
  const require_errors = require("./errors-C-wEou02.cjs");
3
- const require_Telemetry = require("./Telemetry-DKfJQxnC.cjs");
4
- const require_utils = require("./utils-B0SrWoNh.cjs");
5
- const require_package = require("./package-B45PcHOn.cjs");
3
+ const require_Telemetry = require("./Telemetry-C-y1OMHs.cjs");
4
+ const require_utils = require("./utils-DT_n0UZH.cjs");
5
+ const require_package = require("./package-BtgEczay.cjs");
6
6
  const require_output = require("./output-B2V2MN_C.cjs");
7
7
  let node_util = require("node:util");
8
8
  let node_crypto = require("node:crypto");
@@ -235,7 +235,8 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
235
235
  let anyFailed = false;
236
236
  for (const config of configs) {
237
237
  const effectiveInput = input ?? config.input;
238
- const watchPath = typeof effectiveInput === "string" && (0, _kubb_core.getInputKind)(effectiveInput) === "file" ? effectiveInput : void 0;
238
+ const inputKind = typeof effectiveInput === "string" ? (0, _kubb_core.getInputKind)(effectiveInput) : void 0;
239
+ const watchPath = inputKind === "file" || inputKind === "url" ? effectiveInput : void 0;
239
240
  if (watchPath && watch) {
240
241
  const watchedPaths = [watchPath];
241
242
  const build = async (paths) => {
@@ -248,12 +249,20 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
248
249
  });
249
250
  require_output.logStep((0, node_util.styleText)("yellow", `Watching for changes in ${paths.join(" and ")}`));
250
251
  };
252
+ const initialBody = inputKind === "url" ? await require_utils.fetchUrlBody(watchPath) : void 0;
251
253
  try {
252
254
  await build(watchedPaths);
253
255
  } catch (buildError) {
254
256
  await hooks.callHook("kubb:error", { error: require_errors.toError(buildError) });
255
257
  }
256
- await require_utils.startWatcher(watchedPaths, build, {
258
+ if (inputKind === "url") require_utils.startUrlWatcher(watchPath, build, {
259
+ log: {
260
+ info: require_output.logInfo,
261
+ error: require_output.logError
262
+ },
263
+ initialBody
264
+ });
265
+ else await require_utils.startWatcher(watchedPaths, build, {
257
266
  info: require_output.logInfo,
258
267
  error: require_output.logError
259
268
  });
@@ -280,4 +289,4 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
280
289
  //#endregion
281
290
  exports.run = run;
282
291
 
283
- //# sourceMappingURL=run-DWselriZ.cjs.map
292
+ //# sourceMappingURL=run-CzyLOeT1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-CzyLOeT1.cjs","names":["styleText","existsSync","logLevelMap","randomUUID","runHook","toError","process","memoryStorage","Diagnostics","formatters","detectTool","FORMATTER_PREFERENCE","linters","LINTER_PREFERENCE","runPostGenerate","createKubb","sendTelemetry","buildTelemetryEvent","version","KUBB_NPM_PACKAGE_URL","UPDATE_CHECK_TIMEOUT_MS","isNewerVersion","Hookable","getConfigs","setupReporters","cliReporter","selectReporters","path","getInputKind","fetchUrlBody","logInfo","logError","startWatcher"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const available = configs[0]?.reporters ?? []\n const reporters = selectReporters(available, requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,KAAA,GAAIA,UAAAA,UAAAA,CAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,QAAA,GAAOC,QAAAA,WAAAA,CAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,SAAA,GAAQD,UAAAA,UAAAA,CAAU,OAAO,YAAY;GAC3D,YAAYE,WAAAA,SAAY,OAAO,OAAA,GAAMF,UAAAA,UAAAA,CAAU,OAAO,UAAU,MAAM,KAAA;GACtE;EACF,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;EAEX,IAA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AAOA,eAAAA,QAAQ,KAAK,EAAE,CAAC;EAC5D,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
2
  import { t as toError } from "./errors-C8yNfV7w.js";
3
- import { r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-BCTY-Nzq.js";
4
- import { t as version } from "./package-CDmvOHxC.js";
3
+ import { r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-DIDDCARm.js";
4
+ import { t as version } from "./package-DtLAJtma.js";
5
5
  import { styleText } from "node:util";
6
6
  import process from "node:process";
7
7
  //#region src/runners/mcp/run.ts
@@ -37,4 +37,4 @@ const runner = async () => {
37
37
  //#endregion
38
38
  export { runner };
39
39
 
40
- //# sourceMappingURL=run-CinpPEto.js.map
40
+ //# sourceMappingURL=run-Df7AhaaH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-CinpPEto.js","names":[],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/mcp.ts'\n\ntype McpOptions = {\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run({ version }: McpOptions): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))\n\n try {\n console.log(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n\n await startMcpServer()\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 * Loaded on demand by `index.ts`, so `@kubb/mcp` stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async () => {\n await run({ version })\n}\n"],"mappings":";;;;;;;;;;AAmBA,eAAsB,IAAI,EAAE,WAAsC;CAChE,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiC,cAAc,oBAAoB;EAAE,SAAS;EAAO,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE7I,IAAI;EACF,QAAQ,IAAI,UAAU,QAAQ,0BAA0B,CAAC;EACzD,QAAQ,KAAK,UAAU,UAAU,2DAA2D,CAAC;EAE7F,MAAM,eAAe;EACrB,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF;;;;AAKA,MAAa,SAA0E,YAAY;CACjG,MAAM,IAAI,EAAE,QAAQ,CAAC;AACvB"}
1
+ {"version":3,"file":"run-Df7AhaaH.js","names":[],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/mcp.ts'\n\ntype McpOptions = {\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run({ version }: McpOptions): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))\n\n try {\n console.log(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n\n await startMcpServer()\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 * Loaded on demand by `index.ts`, so `@kubb/mcp` stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async () => {\n await run({ version })\n}\n"],"mappings":";;;;;;;;;;AAmBA,eAAsB,IAAI,EAAE,WAAsC;CAChE,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiC,cAAc,oBAAoB;EAAE,SAAS;EAAO,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE7I,IAAI;EACF,QAAQ,IAAI,UAAU,QAAQ,0BAA0B,CAAC;EACzD,QAAQ,KAAK,UAAU,UAAU,2DAA2D,CAAC;EAE7F,MAAM,eAAe;EACrB,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF;;;;AAKA,MAAa,SAA0E,YAAY;CACjG,MAAM,IAAI,EAAE,QAAQ,CAAC;AACvB"}
@@ -1,9 +1,9 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
2
  const require_errors = require("./errors-C-wEou02.cjs");
3
- const require_Telemetry = require("./Telemetry-DKfJQxnC.cjs");
4
- const require_utils = require("./utils-B0SrWoNh.cjs");
3
+ const require_Telemetry = require("./Telemetry-C-y1OMHs.cjs");
4
+ const require_utils = require("./utils-DT_n0UZH.cjs");
5
5
  const require_env = require("./env-DHaFBZTX.cjs");
6
- const require_package = require("./package-B45PcHOn.cjs");
6
+ const require_package = require("./package-BtgEczay.cjs");
7
7
  const require_output = require("./output-B2V2MN_C.cjs");
8
8
  const require_constants = require("./constants-CdxpgX3_.cjs");
9
9
  let node_util = require("node:util");
@@ -499,4 +499,4 @@ const runner = async ({ values }) => {
499
499
  //#endregion
500
500
  exports.runner = runner;
501
501
 
502
- //# sourceMappingURL=run-gpEaRaDp.cjs.map
502
+ //# sourceMappingURL=run-DmRYvDCi.cjs.map