@kubb/cli 5.11.3 → 5.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Telemetry-DHf64JZ0.js → Telemetry-BlAR8vxu.js} +3 -31
- package/dist/Telemetry-BlAR8vxu.js.map +1 -0
- package/dist/{Telemetry-DyPhPm0f.cjs → Telemetry-CF1YNdR-.cjs} +2 -42
- package/dist/Telemetry-CF1YNdR-.cjs.map +1 -0
- package/dist/{background-qThnqeWn.cjs → background-CaZZul1n.cjs} +5 -4
- package/dist/background-CaZZul1n.cjs.map +1 -0
- package/dist/{background-Doe7_Wwo.js → background-DKyMPeHm.js} +7 -5
- package/dist/background-DKyMPeHm.js.map +1 -0
- package/dist/{background-5cHVRJLj.js → background-DUHqYiuQ.js} +1 -1
- package/dist/config-Bh00Hwpw.js +132 -0
- package/dist/config-Bh00Hwpw.js.map +1 -0
- package/dist/config-D63Gum4F.cjs +169 -0
- package/dist/config-D63Gum4F.cjs.map +1 -0
- package/dist/config-iVdOcpro.js +1 -0
- package/dist/credentials-CZK6zPLv.js.map +1 -1
- package/dist/credentials-DDaKqtJn.cjs.map +1 -1
- package/dist/errors-Cl69p_vI.cjs +43 -0
- package/dist/errors-Cl69p_vI.cjs.map +1 -0
- package/dist/errors-DmC83ALX.js +32 -0
- package/dist/errors-DmC83ALX.js.map +1 -0
- package/dist/index.cjs +874 -309
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +864 -299
- package/dist/index.js.map +1 -1
- package/dist/registry-CfYNeyOc.cjs +272 -0
- package/dist/registry-CfYNeyOc.cjs.map +1 -0
- package/dist/registry-D688-8EH.js +200 -0
- package/dist/registry-D688-8EH.js.map +1 -0
- package/dist/reporters-BHyW4d5Q.js +817 -0
- package/dist/reporters-BHyW4d5Q.js.map +1 -0
- package/dist/reporters-DrQJfnU2.cjs +829 -0
- package/dist/reporters-DrQJfnU2.cjs.map +1 -0
- package/dist/run-B4SKmzAG.js +1 -0
- package/dist/{run-_I3J6qxb.cjs → run-BldagXO-.cjs} +4 -3
- package/dist/{run-_I3J6qxb.cjs.map → run-BldagXO-.cjs.map} +1 -1
- package/dist/{run-CPDiH3Hm.js → run-C1FHgzNR.js} +3 -2
- package/dist/{run-CPDiH3Hm.js.map → run-C1FHgzNR.js.map} +1 -1
- package/dist/run-CYHpe0V_.cjs +227 -0
- package/dist/run-CYHpe0V_.cjs.map +1 -0
- package/dist/run-CaJbZO-f.cjs +94 -0
- package/dist/run-CaJbZO-f.cjs.map +1 -0
- package/dist/run-Cj-HJxYW.js +93 -0
- package/dist/run-Cj-HJxYW.js.map +1 -0
- package/dist/{run-D3JYO5Ha.cjs → run-DkBJkKor.cjs} +172 -76
- package/dist/run-DkBJkKor.cjs.map +1 -0
- package/dist/run-S3xKq4bj.js +224 -0
- package/dist/run-S3xKq4bj.js.map +1 -0
- package/dist/{run-DfCOkPNm.js → run-vBNko5TH.js} +166 -70
- package/dist/run-vBNko5TH.js.map +1 -0
- package/dist/{snapshot-DpaFwPrR.cjs → snapshot-CsIJRKEL.cjs} +51 -64
- package/dist/snapshot-CsIJRKEL.cjs.map +1 -0
- package/dist/{snapshot-C2znYElk.js → snapshot-Cvo94y5d.js} +49 -62
- package/dist/snapshot-Cvo94y5d.js.map +1 -0
- package/dist/status-C-NPN63r.cjs +78 -0
- package/dist/status-C-NPN63r.cjs.map +1 -0
- package/dist/status-DTsZxa5Y.js +77 -0
- package/dist/status-DTsZxa5Y.js.map +1 -0
- package/dist/studioWorker.js +2 -2
- package/dist/summary-C22oNZu_.cjs +46 -0
- package/dist/summary-C22oNZu_.cjs.map +1 -0
- package/dist/summary-F11HQput.js +41 -0
- package/dist/summary-F11HQput.js.map +1 -0
- package/dist/text-28DwO_5A.cjs +341 -0
- package/dist/text-28DwO_5A.cjs.map +1 -0
- package/dist/text-BThr2r0T.js +239 -0
- package/dist/text-BThr2r0T.js.map +1 -0
- package/dist/utils-BLXM2UkN.cjs +727 -0
- package/dist/utils-BLXM2UkN.cjs.map +1 -0
- package/dist/utils-Cv3YUnSi.js +612 -0
- package/dist/utils-Cv3YUnSi.js.map +1 -0
- package/package.json +7 -7
- package/dist/Telemetry-DHf64JZ0.js.map +0 -1
- package/dist/Telemetry-DyPhPm0f.cjs.map +0 -1
- package/dist/background-Doe7_Wwo.js.map +0 -1
- package/dist/background-qThnqeWn.cjs.map +0 -1
- package/dist/config-DJgo6i9_.cjs +0 -113
- package/dist/config-DJgo6i9_.cjs.map +0 -1
- package/dist/config-PG9NSJHL.js +0 -95
- package/dist/config-PG9NSJHL.js.map +0 -1
- package/dist/output-B4fjaKge.cjs +0 -1076
- package/dist/output-B4fjaKge.cjs.map +0 -1
- package/dist/output-B9XbFYXT.js +0 -937
- package/dist/output-B9XbFYXT.js.map +0 -1
- package/dist/registry-CUs-pcSk.js +0 -115
- package/dist/registry-CUs-pcSk.js.map +0 -1
- package/dist/registry-t78Mn8DF.cjs +0 -157
- package/dist/registry-t78Mn8DF.cjs.map +0 -1
- package/dist/run-BtNq-0P2.js +0 -39
- package/dist/run-BtNq-0P2.js.map +0 -1
- package/dist/run-CPhZVSrZ.js +0 -343
- package/dist/run-CPhZVSrZ.js.map +0 -1
- package/dist/run-D3JYO5Ha.cjs.map +0 -1
- package/dist/run-DfCOkPNm.js.map +0 -1
- package/dist/run-DvdBqT9o.cjs +0 -345
- package/dist/run-DvdBqT9o.cjs.map +0 -1
- package/dist/run-EyyX3vvP.js +0 -1
- package/dist/run-pM4T492F.cjs +0 -40
- package/dist/run-pM4T492F.cjs.map +0 -1
- package/dist/snapshot-C2znYElk.js.map +0 -1
- package/dist/snapshot-DpaFwPrR.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-vBNko5TH.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/copyToClipboard.ts","../../../internals/utils/src/openInBrowser.ts","../src/runners/studio/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst COMMANDS: Partial<Record<NodeJS.Platform, [string, ...Array<string>]>> = {\n darwin: ['pbcopy'],\n win32: ['clip.exe'],\n linux: ['xclip', '-selection', 'clipboard'],\n}\n\n/**\n * Copies text to the system clipboard with the platform's own tool. Resolves `false` in CI, on a\n * platform without a known tool, or when the tool is missing or fails.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n // Wayland sessions have no X selection for xclip to serve, so they use `wl-copy`.\n const command = process.platform === 'linux' && process.env.WAYLAND_DISPLAY ? (['wl-copy'] as const) : COMMANDS[process.platform]\n if (!command || isCIEnvironment()) return false\n\n const [name, ...args] = command\n // stdout and stderr are ignored: xclip and wl-copy stay alive to serve the selection and would hold open pipes until the timeout.\n const run = x(name, args, { timeout: 2_000, nodeOptions: { stdio: ['pipe', 'ignore', 'ignore'] } })\n // A missing tool closes stdin before the write lands; the rejection below reports it.\n run.process?.stdin?.once('error', () => {})\n run.process?.stdin?.end(text)\n\n return run.then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","import { hostname } from 'node:os'\nimport { toPermissionFlag } from '../../ui/text.ts'\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 { copyToClipboard, isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { connectAgent, defaultStudioUrl, InvalidAgentTokenError, pairAgent, PairingCanceledError } from '@kubb/studio'\nimport { AgentPermission } from '@kubb/studio/protocol'\nimport { trackRun } from '../../Telemetry.ts'\nimport { plainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { logIntro, logOutro, logTip } from '../../ui/intro.ts'\nimport { logBlock, logStep } from '../../ui/log.ts'\nimport { createSpinner } from '../../ui/spinner.ts'\nimport { canUseTTY, isRichOutput } from '../../utils/env.ts'\nimport { getConfigs } from '../../config.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getMachineId, readCredentials, writeCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\nexport type StudioOptions = {\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<AgentPermission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport type SnapshotOptions = Pick<StudioOptions, 'configPath' | 'studioUrl' | 'logLevel'> & {\n /**\n * Organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * Stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /** Identity of another CI agent to also compare with. Falls back to CI auto-detection. */\n baseId?: string\n /**\n * Package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * Package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\n/** The flags a `kubb studio` subcommand parsed; each one is optional since a subcommand declares only the flags it uses. */\nexport type StudioValues = {\n config?: string\n url?: string\n allowRead?: boolean\n allowReadAst?: boolean\n allowWrite?: boolean\n allowConfigEdit?: boolean\n allowExec?: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\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 */\nexport async function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const spinner = createSpinner()\n // A retry notice stays on screen a while before the countdown takes the line back.\n let retryUntil = 0\n // The spinner only starts once a code is shown.\n let waiting = false\n let countdown: NodeJS.Timeout | undefined\n\n try {\n const { token, agent } = await pairAgent({\n studioUrl,\n type: 'cli',\n name: path.basename(process.cwd()),\n hostname: hostname(),\n machineId: await getMachineId(),\n signal,\n onCode: (session) => {\n logStep(\n [\n 'Pair this machine',\n `${styleText('dim', 'Open')} ${styleText('cyan', session.verification_uri)}`,\n `${styleText('dim', 'Code')} ${styleText('bold', session.user_code)}`,\n ].join('\\n'),\n )\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n // Same fallback as the poll in `@kubb/studio`, so the countdown ends when polling does.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let copied = false\n const waitingText = () =>\n `Waiting for approval ${styleText('dim', `expires in ${formatCountdown(deadline - Date.now())}${copied ? ' · code copied' : ''} · ctrl+c to cancel`)}`\n clearInterval(countdown)\n spinner.start(waitingText())\n waiting = true\n // Plain output prints every message, so only an animated spinner ticks.\n if (isRichOutput()) countdown = setInterval(() => Date.now() > retryUntil && spinner.message(waitingText()), 1000)\n // Not awaited: the code shows at once, and the spinner picks up the copy when it lands.\n void copyToClipboard(session.user_code).then((done) => {\n copied = done\n })\n },\n onRetry: (error) => {\n retryUntil = Date.now() + 5000\n spinner.message(`Could not reach Kubb Studio, retrying: ${error.message}`)\n },\n })\n clearInterval(countdown)\n spinner.stop(`Paired as ${agent.name}${agent.organizationSlug ? ` · org ${agent.organizationSlug}` : ''}`)\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 ...(agent.organizationSlug ? { organizationSlug: agent.organizationSlug } : {}),\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 clearInterval(countdown)\n if (waiting) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n }\n throw error\n }\n}\n\n/** Time left on a pairing code as `m:ss`, never below `0:00`. */\nexport function formatCountdown(ms: number): string {\n const seconds = Math.max(0, Math.ceil(ms / 1000))\n\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`\n}\n\n/**\n * What each permission is asked as, in the order the list shows them.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: AgentPermission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n title: (configPath: string) => string\n hint: string\n}> = [\n { key: AgentPermission.READ, label: 'read source', title: () => 'Read generated files', hint: 'show code in the browser' },\n { key: AgentPermission.READ_AST, label: 'read spec', title: () => 'Read the parsed spec', hint: 'browse schemas and operations' },\n { key: AgentPermission.WRITE, label: 'write files', title: () => 'Write files to disk', hint: 'generate from the browser' },\n { key: AgentPermission.CONFIG_EDIT, label: 'edit config', title: (configPath) => `Change ${configPath}`, hint: 'edit plugin options' },\n { key: AgentPermission.EXEC, label: 'run tools', title: () => 'Run the formatter, linter, and postGenerate', hint: 'after each generation' },\n]\n\n/**\n * Two permissions per row, each marked granted or not, with the flags that grant the missing ones\n * after the last row. For `kubb studio status`.\n */\nexport function formatPermissionRows(granted: Partial<Record<AgentPermission, boolean>>): Array<string> {\n const width = Math.max(...PERMISSIONS.map(({ label }) => label.length))\n const cells = PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✓') : styleText('red', '✖')} ${label.padEnd(width)}`)\n const rows = Array.from({ length: Math.ceil(cells.length / 2) }, (_, index) => cells.slice(index * 2, index * 2 + 2).join(' '))\n const flags = PERMISSIONS.filter(({ key }) => !granted[key])\n .map(({ key }) => toPermissionFlag(key))\n .join(' ')\n\n return flags ? [...rows.slice(0, -1), `${rows.at(-1)} ${styleText('dim', flags)}`] : rows\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and the rest are asked in one list whose answers are stored\n * in `~/.kubb/credentials.json`.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n): Promise<Record<AgentPermission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted = Object.fromEntries(PERMISSIONS.map(({ key }) => [key, options.permission[key] || remembered?.[key] === true])) as Record<\n AgentPermission,\n boolean\n >\n const pending = PERMISSIONS.filter(({ key }) => !options.permission[key] && typeof remembered?.[key] !== 'boolean')\n\n if (!pending.length || isCIEnvironment() || !canUseTTY()) return granted\n\n prompts.updateSettings({ withGuide: true })\n const selected = await prompts.multiselect({\n message: 'What may Kubb Studio do in this project?',\n options: pending.map(({ key, title, hint }) => ({ value: key, label: title(configPath), hint })),\n required: false,\n })\n // A canceled list grants nothing and saves nothing, so the next run asks again.\n if (prompts.isCancel(selected)) return granted\n\n const answers = Object.fromEntries(pending.map(({ key }) => [key, selected.includes(key)]))\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n\n return { ...granted, ...answers }\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nexport async function loadConfigs(options: Pick<StudioOptions, 'configPath' | 'logLevel'>): 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 Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Config not defined, create a kubb.config.ts or pass it with --config',\n })\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\nexport type PreparedConnection = {\n configPath: string\n credentials: Credentials\n permissions: StudioOptions['permission']\n}\n\n/** Validates the project and resolves pairing and permissions before starting its worker. */\nexport async function prepareConnection(options: StudioOptions, signal?: AbortSignal): Promise<PreparedConnection> {\n const { configPath } = await loadConfigs(options)\n const stored = await readCredentials()\n const credentials = await (async () => {\n if (stored?.studioUrl === options.studioUrl) return stored\n if (isCIEnvironment()) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `Not paired with ${options.studioUrl}. In CI, run \\`kubb studio snapshot\\` instead, or run \\`kubb studio login\\` on a machine with a browser.`,\n })\n }\n return login(options, { signal })\n })()\n const permissions = await resolvePermissions(options, credentials, configPath)\n return { configPath, credentials, permissions }\n}\n\nexport type WorkerState = 'starting' | 'connected' | 'reconnecting' | 'authentication required' | 'stopped'\n\n/** Runs the same project connection in the foreground or in a background worker. */\nexport async function connect(\n options: StudioOptions,\n context: {\n prepared?: PreparedConnection\n signal?: AbortSignal\n onState?: (state: WorkerState) => void | Promise<void>\n } = {},\n): Promise<void> {\n const shutdown = new AbortController()\n const signal = context.signal ?? shutdown.signal\n const stop = () => shutdown.abort()\n const events = process as unknown as NodeJS.EventEmitter\n if (!context.signal) {\n events.once('SIGINT', stop)\n events.once('SIGTERM', stop)\n }\n let unwatch: (() => void) | undefined\n try {\n if (!context.prepared) {\n const { getWorkerStatus } = await import('./background.ts')\n const worker = await getWorkerStatus()\n if (worker.running)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'This project is running in the background. Run `kubb studio stop` first.',\n })\n }\n const prepared = context.prepared ?? (await prepareConnection(options, signal))\n let { credentials, permissions } = prepared\n const { configPath } = prepared\n let hinted = false\n // Set by a fresh pairing until it connects, so a token rejected right after approval fails the run instead of looping.\n let pairedAgain = false\n\n // The background worker writes to a log file, so it gets the plain logger rather than the\n // animated one. The logger also covers the `studio:*` events and each generation run.\n const hooks = new Hookable<KubbHooks>()\n setupReporters(hooks, {\n logLevel: logLevelMap[options.logLevel ?? 'info'],\n reporters: [cliReporter],\n ...(context.onState ? { writer: plainWriter } : {}),\n })\n // `b` hands the session to the background worker; only a foreground run in a terminal listens.\n const listens = !context.onState && process.stdin.isTTY === true && canUseTTY()\n let background = false\n hooks.hook('studio:connected', async () => {\n pairedAgain = false\n await context.onState?.('connected')\n if (listens && !unwatch) {\n unwatch = watchKeys({\n onBackground: () => {\n background = true\n stop()\n },\n onStop: stop,\n })\n }\n if (hinted || context.onState || options.logLevel === 'silent') return\n hinted = true\n logBlock([\n `${styleText('dim', 'Project')} ${path.basename(process.cwd())} ${styleText(\n 'dim',\n PERMISSIONS.filter(({ key }) => permissions[key])\n .map(({ label }) => label)\n .join(' · ') || 'no permissions',\n )}`,\n styleText('dim', listens ? 'Press b to keep running in the background, Ctrl+C to disconnect' : 'Press Ctrl+C to disconnect'),\n ])\n logTip()\n })\n hooks.hook('studio:reconnecting', () => context.onState?.('reconnecting'))\n\n for (;;) {\n try {\n await connectAgent({\n token: credentials.token,\n studioUrl: options.studioUrl,\n configPath,\n version: options.version,\n root: process.cwd(),\n permissions,\n loadConfig: async () => (await loadConfigs(options)).config,\n hooks,\n signal,\n })\n break\n } catch (error) {\n if (!(error instanceof InvalidAgentTokenError)) throw error\n await context.onState?.('authentication required')\n await clearCredentials()\n if (pairedAgain) throw new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n if (context.onState || isCIEnvironment() || !canUseTTY()) throw new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n\n // The pairing prompts need stdin back.\n unwatch?.()\n unwatch = undefined\n console.log(styleText('yellow', `${error.message} Pairing again...`))\n credentials = await login(options, { signal, previousCredentials: credentials })\n pairedAgain = true\n permissions = await resolvePermissions(options, credentials, configPath)\n }\n }\n // Stops the \"Ready for jobs\" spinner, which would otherwise keep drawing under the closing line.\n await hooks.callHook('kubb:lifecycle:end')\n unwatch?.()\n if (background) {\n const { startWorker } = await import('./background.ts')\n await startWorker(options)\n if (options.logLevel !== 'silent') logOutro('Running in the background · kubb studio stop')\n return\n }\n if (!context.onState && signal.aborted && options.logLevel !== 'silent') logOutro('Disconnected')\n } catch (error) {\n if (!(error instanceof PairingCanceledError)) throw error\n } finally {\n unwatch?.()\n events.off('SIGINT', stop)\n events.off('SIGTERM', stop)\n }\n}\n\n/**\n * Listens for single keys on a TTY stdin. Raw mode turns Ctrl+C into a key instead of SIGINT, so it\n * is handled here too. Returns the function that restores the terminal, safe to call twice.\n */\nexport function watchKeys({ onBackground, onStop }: { onBackground: () => void; onStop: () => void }): () => void {\n const stdin = process.stdin\n const onData = (data: Buffer) => {\n const key = data.toString()\n if (key === 'b' || key === 'B') onBackground()\n if (key === '\\u0003') onStop()\n }\n // A clack spinner reads stdin too and exits the process on Ctrl+C, before the session can close\n // its socket, so its Ctrl+C alias is lifted while these keys are read.\n const cancelAlias = prompts.settings.aliases.get('\\u0003')\n prompts.settings.aliases.delete('\\u0003')\n stdin.setRawMode(true)\n stdin.on('data', onData)\n stdin.resume()\n let restored = false\n\n return () => {\n if (restored) return\n restored = true\n if (cancelAlias) prompts.settings.aliases.set('\\u0003', cancelAlias)\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n }\n}\n\n/**\n * Runs a Studio command from its parsed flags: builds the {@link StudioOptions}, prints the intro,\n * and reports the run to telemetry. A failure is printed and sets the exit code instead of throwing.\n */\nexport async function runStudio(\n values: StudioValues,\n action: (options: StudioOptions) => Promise<unknown>,\n { block = false, json = false }: { block?: boolean; json?: boolean } = {},\n): Promise<void> {\n const options: StudioOptions = {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: Object.fromEntries(Object.values(AgentPermission).map((key) => [key, values[key] ?? false])) as Record<AgentPermission, boolean>,\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\n const report = trackRun({ command: 'studio', hrStart: process.hrtime() })\n\n try {\n if (options.logLevel !== 'silent' && !json) {\n logIntro({\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n block,\n })\n }\n\n await action(options)\n\n await report({ status: 'success' })\n } catch (error) {\n await report({ status: 'failed' })\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,WAAyE;CAC7E,QAAQ,CAAC,QAAQ;CACjB,OAAO,CAAC,UAAU;CAClB,OAAO;EAAC;EAAS;EAAc;CAAW;AAC5C;;;;;AAMA,eAAsB,gBAAgB,MAAgC;CAEpE,MAAM,UAAU,QAAQ,aAAa,WAAW,QAAQ,IAAI,kBAAmB,CAAC,SAAS,IAAc,SAAS,QAAQ;CACxH,IAAI,CAAC,WAAW,gBAAgB,GAAG,OAAO;CAE1C,MAAM,CAAC,MAAM,GAAG,QAAQ;CAExB,MAAM,MAAM,EAAE,MAAM,MAAM;EAAE,SAAS;EAAO,aAAa,EAAE,OAAO;GAAC;GAAQ;GAAU;EAAQ,EAAE;CAAE,CAAC;CAElG,IAAI,SAAS,OAAO,KAAK,eAAe,CAAC,CAAC;CAC1C,IAAI,SA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SAAS;EAAE,SAAS;EAAU,SAAS,QAAQ,OAAO;CAAE,CAAC;CAExE,IAAI;EACF,IAAI,QAAQ,aAAa,YAAY,CAAC,MACpC,SAAS;GACP,SAAS,UAAU,UAAU,2DAA2D;GACxF;EACF,CAAC;EAGH,MAAM,OAAO,OAAO;EAEpB,MAAM,OAAO,EAAE,QAAQ,UAAU,CAAC;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,EAAE,QAAQ,SAAS,CAAC;EACjC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF"}
|
|
@@ -1,31 +1,16 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
|
|
2
|
-
const require_Telemetry = require("./Telemetry-
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const
|
|
2
|
+
const require_Telemetry = require("./Telemetry-CF1YNdR-.cjs");
|
|
3
|
+
const require_utils = require("./utils-BLXM2UkN.cjs");
|
|
4
|
+
const require_text = require("./text-28DwO_5A.cjs");
|
|
5
|
+
const require_reporters = require("./reporters-DrQJfnU2.cjs");
|
|
6
|
+
const require_run = require("./run-DkBJkKor.cjs");
|
|
6
7
|
let node_util = require("node:util");
|
|
7
8
|
let node_process = require("node:process");
|
|
8
9
|
node_process = require_rolldown_runtime.__toESM(node_process, 1);
|
|
9
|
-
let node_fs_promises = require("node:fs/promises");
|
|
10
10
|
let node_path = require("node:path");
|
|
11
|
-
let _kubb_core = require("@kubb/core");
|
|
12
11
|
let node_fs = require("node:fs");
|
|
12
|
+
let _kubb_core = require("@kubb/core");
|
|
13
13
|
let _kubb_studio = require("@kubb/studio");
|
|
14
|
-
//#region ../../internals/utils/src/fs.ts
|
|
15
|
-
/**
|
|
16
|
-
* Reads the file at `path` as a UTF-8 string.
|
|
17
|
-
* Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
|
|
18
|
-
*
|
|
19
|
-
* @example
|
|
20
|
-
* ```ts
|
|
21
|
-
* const source = await read('./src/Pet.ts')
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
async function read(path) {
|
|
25
|
-
if (require_Telemetry.runtime.isBun) return Bun.file(path).text();
|
|
26
|
-
return (0, node_fs_promises.readFile)(path, { encoding: "utf8" });
|
|
27
|
-
}
|
|
28
|
-
//#endregion
|
|
29
14
|
//#region src/runners/studio/ci.ts
|
|
30
15
|
function readGithubPullRequest(eventPath) {
|
|
31
16
|
if (!eventPath) return;
|
|
@@ -101,7 +86,7 @@ function detectCi(env = node_process.default.env) {
|
|
|
101
86
|
* Walks up from `directory` to the first package.json with a name and a version.
|
|
102
87
|
*/
|
|
103
88
|
async function findPackageJson(directory) {
|
|
104
|
-
const packageJson = JSON.parse(await read((0, node_path.join)(directory, "package.json")).catch(() => "{}"));
|
|
89
|
+
const packageJson = JSON.parse(await require_utils.read((0, node_path.join)(directory, "package.json")).catch(() => "{}"));
|
|
105
90
|
if (packageJson.name && packageJson.version) return {
|
|
106
91
|
name: packageJson.name,
|
|
107
92
|
version: packageJson.version
|
|
@@ -115,27 +100,6 @@ async function findPackageJson(directory) {
|
|
|
115
100
|
});
|
|
116
101
|
return findPackageJson(parent);
|
|
117
102
|
}
|
|
118
|
-
/** Reads package.json only for whichever of name/version --name and --version did not supply. */
|
|
119
|
-
async function resolvePackageMetadata(options) {
|
|
120
|
-
if (options.name && options.packageVersion) return {
|
|
121
|
-
name: options.name,
|
|
122
|
-
version: options.packageVersion
|
|
123
|
-
};
|
|
124
|
-
const found = await findPackageJson(node_process.default.cwd());
|
|
125
|
-
return {
|
|
126
|
-
name: options.name ?? found.name,
|
|
127
|
-
version: options.packageVersion ?? found.version
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
function resolveToken(options) {
|
|
131
|
-
const token = options.token ?? node_process.default.env.KUBB_TOKEN;
|
|
132
|
-
if (!token) throw new _kubb_core.Diagnostics.Error({
|
|
133
|
-
code: _kubb_core.Diagnostics.code.unknown,
|
|
134
|
-
severity: "error",
|
|
135
|
-
message: "An organization CI API key is required. Pass --token or set KUBB_TOKEN."
|
|
136
|
-
});
|
|
137
|
-
return token;
|
|
138
|
-
}
|
|
139
103
|
function resolveCiIdentity(options) {
|
|
140
104
|
const detected = detectCi();
|
|
141
105
|
const ci = options.id ? {
|
|
@@ -163,11 +127,13 @@ function absoluteUrl(studioUrl, path) {
|
|
|
163
127
|
function toResult({ studioUrl, snapshot, ci }) {
|
|
164
128
|
return {
|
|
165
129
|
id: snapshot.id,
|
|
130
|
+
number: snapshot.number,
|
|
166
131
|
name: snapshot.name,
|
|
167
132
|
version: snapshot.version,
|
|
168
133
|
integrity: snapshot.integrity,
|
|
169
134
|
url: absoluteUrl(studioUrl, snapshot.url),
|
|
170
135
|
snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),
|
|
136
|
+
webUrl: snapshot.webUrl ? absoluteUrl(studioUrl, snapshot.webUrl) : void 0,
|
|
171
137
|
expiresAt: snapshot.expiresAt,
|
|
172
138
|
agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),
|
|
173
139
|
changes: snapshot.changes,
|
|
@@ -180,49 +146,69 @@ function toResult({ studioUrl, snapshot, ci }) {
|
|
|
180
146
|
/** How many files differ, `against` what. */
|
|
181
147
|
function describeChanges(changes, against) {
|
|
182
148
|
const { added, changed, removed } = changes;
|
|
183
|
-
|
|
149
|
+
const parts = [
|
|
150
|
+
added.length && `+${require_text.pluralize(added.length, "file")}`,
|
|
151
|
+
changed.length && `~${changed.length} changed`,
|
|
152
|
+
removed.length && `-${removed.length} removed`
|
|
153
|
+
].filter(Boolean);
|
|
154
|
+
return parts.length ? `${parts.join(" ")} ${against}` : `No changes ${against}`;
|
|
184
155
|
}
|
|
185
156
|
/** One summary line: how many files changed, and since which run. */
|
|
186
157
|
function formatChanges(changes) {
|
|
187
158
|
if (!changes.base) return "First snapshot";
|
|
188
|
-
|
|
159
|
+
const { number, commit, createdAt } = changes.base;
|
|
160
|
+
return describeChanges(changes, `vs ${number ? `#${number}` : commit?.slice(0, 7) ?? createdAt}`);
|
|
189
161
|
}
|
|
190
162
|
/** One summary line: how the snapshot differs from the base branch's latest one. */
|
|
191
163
|
function formatBranchChanges(changes) {
|
|
192
|
-
if (changes.base) return describeChanges(changes, `
|
|
164
|
+
if (changes.base) return describeChanges(changes, `vs ${changes.branch}`);
|
|
193
165
|
return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`;
|
|
194
166
|
}
|
|
195
167
|
function printSummary(result) {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
...result.
|
|
201
|
-
...result.
|
|
202
|
-
|
|
203
|
-
|
|
168
|
+
const row = (label, value) => ` ${(0, node_util.styleText)("dim", label.padEnd(7))} ${value}`;
|
|
169
|
+
console.log([
|
|
170
|
+
"",
|
|
171
|
+
...result.webUrl ? [row("View", (0, node_util.styleText)("cyan", result.webUrl))] : [],
|
|
172
|
+
...result.changes ? [row("Diff", formatChanges(result.changes))] : [],
|
|
173
|
+
...result.branchChanges ? [row("Branch", formatBranchChanges(result.branchChanges))] : [],
|
|
174
|
+
row("Use", `npm i ${result.url}`),
|
|
175
|
+
row("Expires", result.expiresAt.slice(0, 10))
|
|
176
|
+
].join("\n"));
|
|
204
177
|
}
|
|
205
178
|
/**
|
|
206
179
|
* Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI
|
|
207
180
|
* agent the run's identity names.
|
|
208
181
|
*/
|
|
209
182
|
async function snapshot(options) {
|
|
210
|
-
const token =
|
|
183
|
+
const token = options.token ?? node_process.default.env.KUBB_TOKEN;
|
|
184
|
+
if (!token) throw new _kubb_core.Diagnostics.Error({
|
|
185
|
+
code: _kubb_core.Diagnostics.code.unknown,
|
|
186
|
+
severity: "error",
|
|
187
|
+
message: "An organization CI API key is required. Pass --token or set KUBB_TOKEN."
|
|
188
|
+
});
|
|
211
189
|
const { config } = await require_run.loadConfigs(options);
|
|
212
190
|
const ci = resolveCiIdentity(options);
|
|
213
|
-
const { name, version: packageVersion } =
|
|
191
|
+
const { name, version: packageVersion } = options.name && options.packageVersion ? {
|
|
192
|
+
name: options.name,
|
|
193
|
+
version: options.packageVersion
|
|
194
|
+
} : await findPackageJson(node_process.default.cwd()).then((found) => ({
|
|
195
|
+
name: options.name ?? found.name,
|
|
196
|
+
version: options.packageVersion ?? found.version
|
|
197
|
+
}));
|
|
214
198
|
const logLevel = _kubb_core.logLevel[options.logLevel ?? "info"];
|
|
215
199
|
const write = options.json ? (line) => console.error(line) : (line) => console.log(line);
|
|
216
200
|
const hooks = new _kubb_core.Hookable();
|
|
217
|
-
|
|
218
|
-
logLevel,
|
|
201
|
+
require_reporters.setupReporters(hooks, {
|
|
202
|
+
logLevel: logLevel > _kubb_core.logLevel.info ? logLevel : _kubb_core.logLevel.silent,
|
|
219
203
|
reporters: [_kubb_core.cliReporter],
|
|
220
|
-
|
|
204
|
+
writer: require_text.createPlainWriter(write)
|
|
221
205
|
});
|
|
222
206
|
const step = (message) => {
|
|
223
207
|
if (logLevel > _kubb_core.logLevel.silent) write(message);
|
|
224
208
|
};
|
|
225
|
-
|
|
209
|
+
hooks.hook("kubb:generation:end", ({ filesCreated = 0, status, hrStart }) => {
|
|
210
|
+
if (status !== "failed" && hrStart) step(`✓ Generated ${require_text.pluralize(filesCreated, "file")} in ${require_Telemetry.formatMs(require_Telemetry.getElapsedMs(hrStart))}`);
|
|
211
|
+
});
|
|
226
212
|
try {
|
|
227
213
|
const published = await (0, _kubb_studio.createSnapshot)({
|
|
228
214
|
studioUrl: options.studioUrl,
|
|
@@ -241,11 +227,12 @@ async function snapshot(options) {
|
|
|
241
227
|
snapshot: published,
|
|
242
228
|
ci
|
|
243
229
|
});
|
|
244
|
-
step(
|
|
230
|
+
step(`✓ Packed ${result.name ?? name}@${result.version ?? packageVersion}`);
|
|
231
|
+
step(`✓ Published snapshot ${result.number ? `#${result.number}` : result.id} for ${ci.name}${ci.commit ? `@${ci.commit.slice(0, 7)}` : ""}`);
|
|
245
232
|
if (options.json) console.log(JSON.stringify(result));
|
|
246
|
-
|
|
233
|
+
else printSummary(result);
|
|
247
234
|
} catch (error) {
|
|
248
|
-
step("Snapshot failed");
|
|
235
|
+
step("✖ Snapshot failed");
|
|
249
236
|
throw error;
|
|
250
237
|
}
|
|
251
238
|
}
|
|
@@ -261,4 +248,4 @@ const runner = ({ values }) => require_run.runStudio(values, (options) => snapsh
|
|
|
261
248
|
//#endregion
|
|
262
249
|
exports.runner = runner;
|
|
263
250
|
|
|
264
|
-
//# sourceMappingURL=snapshot-
|
|
251
|
+
//# sourceMappingURL=snapshot-CsIJRKEL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot-CsIJRKEL.cjs","names":["readFileSync","process","read","join","dirname","Diagnostics","process","pluralize","styleText","loadConfigs","logLevelMap","Hookable","cliReporter","createPlainWriter","formatMs","getElapsedMs","createSnapshot","runStudio"],"sources":["../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs, read } from '@internals/utils'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { pluralize } from '../../ui/text.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, runStudio, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `No package.json with a name and a version found above ${process.cwd()}`,\n help: 'Pass `--name` and `--version`, or run from a package with a package.json.',\n })\n\n return findPackageJson(parent)\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.',\n })\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n /** Sequence number on the CI agent, when Studio sends one. */\n number?: number\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n /** Studio page of the snapshot, when Studio sends one. */\n webUrl?: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n number: snapshot.number,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n webUrl: snapshot.webUrl ? absoluteUrl(studioUrl, snapshot.webUrl) : undefined,\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n const parts = [\n added.length && `+${pluralize(added.length, 'file')}`,\n changed.length && `~${changed.length} changed`,\n removed.length && `-${removed.length} removed`,\n ].filter(Boolean)\n\n return parts.length ? `${parts.join(' ')} ${against}` : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n const { number, commit, createdAt } = changes.base\n\n return describeChanges(changes, `vs ${number ? `#${number}` : (commit?.slice(0, 7) ?? createdAt)}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `vs ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n const row = (label: string, value: string) => ` ${styleText('dim', label.padEnd(7))} ${value}`\n\n console.log(\n [\n '',\n ...(result.webUrl ? [row('View', styleText('cyan', result.webUrl))] : []),\n ...(result.changes ? [row('Diff', formatChanges(result.changes))] : []),\n ...(result.branchChanges ? [row('Branch', formatBranchChanges(result.branchChanges))] : []),\n row('Use', `npm i ${result.url}`),\n row('Expires', result.expiresAt.slice(0, 10)),\n ].join('\\n'),\n )\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = options.token ?? process.env.KUBB_TOKEN\n if (!token) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'An organization CI API key is required. Pass --token or set KUBB_TOKEN.',\n })\n }\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n // package.json is read only for whichever of name/version --name and --version did not supply.\n const { name, version: packageVersion } =\n options.name && options.packageVersion\n ? { name: options.name, version: options.packageVersion }\n : await findPackageJson(process.cwd()).then((found) => ({ name: options.name ?? found.name, version: options.packageVersion ?? found.version }))\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n // The steps below are the CI log; the run's own per-file output only shows when asked for with --log-level verbose.\n setupReporters(hooks, { logLevel: logLevel > logLevelMap.info ? logLevel : logLevelMap.silent, reporters: [cliReporter], writer: createPlainWriter(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n hooks.hook('kubb:generation:end', ({ filesCreated = 0, status, hrStart }) => {\n if (status !== 'failed' && hrStart) step(`✓ Generated ${pluralize(filesCreated, 'file')} in ${formatMs(getElapsedMs(hrStart))}`)\n })\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step(`✓ Packed ${result.name ?? name}@${result.version ?? packageVersion}`)\n step(`✓ Published snapshot ${result.number ? `#${result.number}` : result.id} for ${ci.name}${ci.commit ? `@${ci.commit.slice(0, 7)}` : ''}`)\n\n if (options.json) console.log(JSON.stringify(result))\n else printSummary(result)\n } catch (error) {\n step('✖ Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = ({ values }) =>\n runStudio(\n values,\n (options) =>\n snapshot({\n ...options,\n token: values.token,\n id: values.id,\n baseId: values.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AAG,MAAM;EACnB,CAAC;EACD,MAAM,SAAS,SAAS;GAAE,WAAW,QAAQ;GAAW,UAAU;GAAW;EAAG,CAAC;EAEjF,KAAK,YAAY,OAAO,QAAQ,KAAK,GAAG,OAAO,WAAW,gBAAgB;EAC1E,KAAK,wBAAwB,OAAO,SAAS,IAAI,OAAO,WAAW,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS,IAAI,GAAG,OAAO,MAAM,GAAG,CAAC,MAAM,IAAI;EAE5I,IAAI,QAAQ,MAAM,QAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;OAC/C,aAAa,MAAM;CAC1B,SAAS,OAAO;EACd,KAAK,mBAAmB;EACxB,MAAM;CACR;AACF;AAEA,MAAa,UAAwE,EAAE,aACrFC,YAAAA,UACE,SACC,YACC,SAAS;CACP,GAAG;CACH,OAAO,OAAO;CACd,IAAI,OAAO;CACX,QAAQ,OAAO;CACf,MAAM,OAAO;CACb,gBAAgB,OAAO;CACvB,MAAM,OAAO;AACf,CAAC,GACH,EAAE,MAAM,OAAO,KAAK,CACtB"}
|
|
@@ -1,30 +1,15 @@
|
|
|
1
1
|
import "./rolldown-runtime-CRm0XQPb.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
2
|
+
import { a as getElapsedMs, i as formatMs } from "./Telemetry-BlAR8vxu.js";
|
|
3
|
+
import { c as runStudio, i as loadConfigs } from "./run-vBNko5TH.js";
|
|
4
|
+
import { v as read } from "./utils-Cv3YUnSi.js";
|
|
5
|
+
import { m as createPlainWriter, t as pluralize } from "./text-BThr2r0T.js";
|
|
6
|
+
import { n as setupReporters } from "./reporters-BHyW4d5Q.js";
|
|
6
7
|
import { styleText } from "node:util";
|
|
7
8
|
import process from "node:process";
|
|
8
|
-
import { readFile } from "node:fs/promises";
|
|
9
9
|
import { dirname, join } from "node:path";
|
|
10
|
-
import { Diagnostics, Hookable, cliReporter, logLevel } from "@kubb/core";
|
|
11
10
|
import { readFileSync } from "node:fs";
|
|
11
|
+
import { Diagnostics, Hookable, cliReporter, logLevel } from "@kubb/core";
|
|
12
12
|
import { createSnapshot } from "@kubb/studio";
|
|
13
|
-
//#region ../../internals/utils/src/fs.ts
|
|
14
|
-
/**
|
|
15
|
-
* Reads the file at `path` as a UTF-8 string.
|
|
16
|
-
* Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
|
|
17
|
-
*
|
|
18
|
-
* @example
|
|
19
|
-
* ```ts
|
|
20
|
-
* const source = await read('./src/Pet.ts')
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
async function read(path) {
|
|
24
|
-
if (runtime.isBun) return Bun.file(path).text();
|
|
25
|
-
return readFile(path, { encoding: "utf8" });
|
|
26
|
-
}
|
|
27
|
-
//#endregion
|
|
28
13
|
//#region src/runners/studio/ci.ts
|
|
29
14
|
function readGithubPullRequest(eventPath) {
|
|
30
15
|
if (!eventPath) return;
|
|
@@ -114,27 +99,6 @@ async function findPackageJson(directory) {
|
|
|
114
99
|
});
|
|
115
100
|
return findPackageJson(parent);
|
|
116
101
|
}
|
|
117
|
-
/** Reads package.json only for whichever of name/version --name and --version did not supply. */
|
|
118
|
-
async function resolvePackageMetadata(options) {
|
|
119
|
-
if (options.name && options.packageVersion) return {
|
|
120
|
-
name: options.name,
|
|
121
|
-
version: options.packageVersion
|
|
122
|
-
};
|
|
123
|
-
const found = await findPackageJson(process.cwd());
|
|
124
|
-
return {
|
|
125
|
-
name: options.name ?? found.name,
|
|
126
|
-
version: options.packageVersion ?? found.version
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
function resolveToken(options) {
|
|
130
|
-
const token = options.token ?? process.env.KUBB_TOKEN;
|
|
131
|
-
if (!token) throw new Diagnostics.Error({
|
|
132
|
-
code: Diagnostics.code.unknown,
|
|
133
|
-
severity: "error",
|
|
134
|
-
message: "An organization CI API key is required. Pass --token or set KUBB_TOKEN."
|
|
135
|
-
});
|
|
136
|
-
return token;
|
|
137
|
-
}
|
|
138
102
|
function resolveCiIdentity(options) {
|
|
139
103
|
const detected = detectCi();
|
|
140
104
|
const ci = options.id ? {
|
|
@@ -162,11 +126,13 @@ function absoluteUrl(studioUrl, path) {
|
|
|
162
126
|
function toResult({ studioUrl, snapshot, ci }) {
|
|
163
127
|
return {
|
|
164
128
|
id: snapshot.id,
|
|
129
|
+
number: snapshot.number,
|
|
165
130
|
name: snapshot.name,
|
|
166
131
|
version: snapshot.version,
|
|
167
132
|
integrity: snapshot.integrity,
|
|
168
133
|
url: absoluteUrl(studioUrl, snapshot.url),
|
|
169
134
|
snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),
|
|
135
|
+
webUrl: snapshot.webUrl ? absoluteUrl(studioUrl, snapshot.webUrl) : void 0,
|
|
170
136
|
expiresAt: snapshot.expiresAt,
|
|
171
137
|
agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),
|
|
172
138
|
changes: snapshot.changes,
|
|
@@ -179,49 +145,69 @@ function toResult({ studioUrl, snapshot, ci }) {
|
|
|
179
145
|
/** How many files differ, `against` what. */
|
|
180
146
|
function describeChanges(changes, against) {
|
|
181
147
|
const { added, changed, removed } = changes;
|
|
182
|
-
|
|
148
|
+
const parts = [
|
|
149
|
+
added.length && `+${pluralize(added.length, "file")}`,
|
|
150
|
+
changed.length && `~${changed.length} changed`,
|
|
151
|
+
removed.length && `-${removed.length} removed`
|
|
152
|
+
].filter(Boolean);
|
|
153
|
+
return parts.length ? `${parts.join(" ")} ${against}` : `No changes ${against}`;
|
|
183
154
|
}
|
|
184
155
|
/** One summary line: how many files changed, and since which run. */
|
|
185
156
|
function formatChanges(changes) {
|
|
186
157
|
if (!changes.base) return "First snapshot";
|
|
187
|
-
|
|
158
|
+
const { number, commit, createdAt } = changes.base;
|
|
159
|
+
return describeChanges(changes, `vs ${number ? `#${number}` : commit?.slice(0, 7) ?? createdAt}`);
|
|
188
160
|
}
|
|
189
161
|
/** One summary line: how the snapshot differs from the base branch's latest one. */
|
|
190
162
|
function formatBranchChanges(changes) {
|
|
191
|
-
if (changes.base) return describeChanges(changes, `
|
|
163
|
+
if (changes.base) return describeChanges(changes, `vs ${changes.branch}`);
|
|
192
164
|
return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`;
|
|
193
165
|
}
|
|
194
166
|
function printSummary(result) {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
...result.
|
|
200
|
-
...result.
|
|
201
|
-
|
|
202
|
-
|
|
167
|
+
const row = (label, value) => ` ${styleText("dim", label.padEnd(7))} ${value}`;
|
|
168
|
+
console.log([
|
|
169
|
+
"",
|
|
170
|
+
...result.webUrl ? [row("View", styleText("cyan", result.webUrl))] : [],
|
|
171
|
+
...result.changes ? [row("Diff", formatChanges(result.changes))] : [],
|
|
172
|
+
...result.branchChanges ? [row("Branch", formatBranchChanges(result.branchChanges))] : [],
|
|
173
|
+
row("Use", `npm i ${result.url}`),
|
|
174
|
+
row("Expires", result.expiresAt.slice(0, 10))
|
|
175
|
+
].join("\n"));
|
|
203
176
|
}
|
|
204
177
|
/**
|
|
205
178
|
* Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI
|
|
206
179
|
* agent the run's identity names.
|
|
207
180
|
*/
|
|
208
181
|
async function snapshot(options) {
|
|
209
|
-
const token =
|
|
182
|
+
const token = options.token ?? process.env.KUBB_TOKEN;
|
|
183
|
+
if (!token) throw new Diagnostics.Error({
|
|
184
|
+
code: Diagnostics.code.unknown,
|
|
185
|
+
severity: "error",
|
|
186
|
+
message: "An organization CI API key is required. Pass --token or set KUBB_TOKEN."
|
|
187
|
+
});
|
|
210
188
|
const { config } = await loadConfigs(options);
|
|
211
189
|
const ci = resolveCiIdentity(options);
|
|
212
|
-
const { name, version: packageVersion } =
|
|
190
|
+
const { name, version: packageVersion } = options.name && options.packageVersion ? {
|
|
191
|
+
name: options.name,
|
|
192
|
+
version: options.packageVersion
|
|
193
|
+
} : await findPackageJson(process.cwd()).then((found) => ({
|
|
194
|
+
name: options.name ?? found.name,
|
|
195
|
+
version: options.packageVersion ?? found.version
|
|
196
|
+
}));
|
|
213
197
|
const logLevel$1 = logLevel[options.logLevel ?? "info"];
|
|
214
198
|
const write = options.json ? (line) => console.error(line) : (line) => console.log(line);
|
|
215
199
|
const hooks = new Hookable();
|
|
216
200
|
setupReporters(hooks, {
|
|
217
|
-
logLevel: logLevel$1,
|
|
201
|
+
logLevel: logLevel$1 > logLevel.info ? logLevel$1 : logLevel.silent,
|
|
218
202
|
reporters: [cliReporter],
|
|
219
|
-
|
|
203
|
+
writer: createPlainWriter(write)
|
|
220
204
|
});
|
|
221
205
|
const step = (message) => {
|
|
222
206
|
if (logLevel$1 > logLevel.silent) write(message);
|
|
223
207
|
};
|
|
224
|
-
|
|
208
|
+
hooks.hook("kubb:generation:end", ({ filesCreated = 0, status, hrStart }) => {
|
|
209
|
+
if (status !== "failed" && hrStart) step(`✓ Generated ${pluralize(filesCreated, "file")} in ${formatMs(getElapsedMs(hrStart))}`);
|
|
210
|
+
});
|
|
225
211
|
try {
|
|
226
212
|
const published = await createSnapshot({
|
|
227
213
|
studioUrl: options.studioUrl,
|
|
@@ -240,11 +226,12 @@ async function snapshot(options) {
|
|
|
240
226
|
snapshot: published,
|
|
241
227
|
ci
|
|
242
228
|
});
|
|
243
|
-
step(
|
|
229
|
+
step(`✓ Packed ${result.name ?? name}@${result.version ?? packageVersion}`);
|
|
230
|
+
step(`✓ Published snapshot ${result.number ? `#${result.number}` : result.id} for ${ci.name}${ci.commit ? `@${ci.commit.slice(0, 7)}` : ""}`);
|
|
244
231
|
if (options.json) console.log(JSON.stringify(result));
|
|
245
|
-
|
|
232
|
+
else printSummary(result);
|
|
246
233
|
} catch (error) {
|
|
247
|
-
step("Snapshot failed");
|
|
234
|
+
step("✖ Snapshot failed");
|
|
248
235
|
throw error;
|
|
249
236
|
}
|
|
250
237
|
}
|
|
@@ -260,4 +247,4 @@ const runner = ({ values }) => runStudio(values, (options) => snapshot({
|
|
|
260
247
|
//#endregion
|
|
261
248
|
export { runner };
|
|
262
249
|
|
|
263
|
-
//# sourceMappingURL=snapshot-
|
|
250
|
+
//# sourceMappingURL=snapshot-Cvo94y5d.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshot-Cvo94y5d.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/studio/ci.ts","../src/runners/studio/snapshot.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport process from 'node:process'\n\n/**\n * Stable identity for the CI agent a snapshot run registers or reuses.\n */\nexport type CiContext = {\n /**\n * Fed into the machine token, so the same merge or pull request reuses one agent.\n */\n id: string\n /**\n * Agent display name shown in Studio.\n */\n name: string\n /** The commit this run builds, so the next snapshot can diff against it. */\n commit?: string\n /** The branch a pull request merges into, and the `id` runs on that branch register under. */\n base?: { branch: string; id: string }\n}\n\ntype GithubPullRequest = { number: number; head?: { sha?: string }; base?: { ref?: string } }\n\nfunction readGithubPullRequest(eventPath: string | undefined): GithubPullRequest | undefined {\n if (!eventPath) {\n return undefined\n }\n\n try {\n const event = JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request?: GithubPullRequest }\n return event.pull_request?.number ? event.pull_request : undefined\n } catch {\n return undefined\n }\n}\n\n/** Reproduces GitLab's `CI_COMMIT_REF_SLUG` for a branch it gives no slug of, like a merge request's target. */\nexport function gitlabRefSlug(ref: string): string {\n return ref\n .toLowerCase()\n .replace(/[^a-z0-9]/gu, '-')\n .slice(0, 63)\n .replace(/^-+|-+$/g, '')\n}\n\n/**\n * Detects the CI provider from its environment variables and derives a stable identity from it.\n * The GitHub row reproduces `gh:<repositoryId>:<prNumber>`, the identity `kubb-labs/action` has\n * always registered agents under, so an existing repository keeps reusing its agent.\n */\nexport function detectCi(env: Record<string, string | undefined> = process.env): CiContext | null {\n if (env.GITHUB_ACTIONS) {\n const pullRequest = readGithubPullRequest(env.GITHUB_EVENT_PATH)\n const repositoryId = env.GITHUB_REPOSITORY_ID ?? env.GITHUB_REPOSITORY ?? ''\n const branch = env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice('refs/heads/'.length) : undefined\n // A branch run is scoped by its ref, which a pull request number never collides with.\n const scope = pullRequest?.number ?? (branch ? `refs/heads/${branch}` : env.GITHUB_RUN_ID) ?? ''\n const baseBranch = pullRequest?.base?.ref\n\n return {\n id: `gh:${repositoryId}:${scope}`,\n name: `${env.GITHUB_REPOSITORY ?? 'github'}#${pullRequest?.number ?? branch ?? scope}`,\n // The head commit, not the merge commit a pull request run checks out.\n commit: pullRequest?.head?.sha ?? env.GITHUB_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gh:${repositoryId}:refs/heads/${baseBranch}` } : undefined,\n }\n }\n\n if (env.GITLAB_CI) {\n const scope = env.CI_MERGE_REQUEST_IID ?? env.CI_COMMIT_REF_SLUG ?? ''\n const baseBranch = env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME\n\n return {\n id: `gl:${env.CI_PROJECT_ID ?? ''}:${scope}`,\n name: `${env.CI_PROJECT_PATH ?? 'gitlab'}#${scope}`,\n commit: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || env.CI_COMMIT_SHA,\n base: baseBranch ? { branch: baseBranch, id: `gl:${env.CI_PROJECT_ID ?? ''}:${gitlabRefSlug(baseBranch)}` } : undefined,\n }\n }\n\n if (env.BITBUCKET_BUILD_NUMBER) {\n const scope = env.BITBUCKET_PR_ID ?? env.BITBUCKET_BRANCH ?? ''\n\n return { id: `bb:${env.BITBUCKET_REPO_UUID ?? ''}:${scope}`, name: `${env.BITBUCKET_REPO_FULL_NAME ?? 'bitbucket'}#${scope}`, commit: env.BITBUCKET_COMMIT }\n }\n\n if (env.CIRCLECI) {\n // Owner-qualified: two projects with the same name under different CircleCI orgs must not\n // collide on one agent, since registering it purges the other project's live sessions.\n const owner = env.CIRCLE_PROJECT_USERNAME ?? ''\n const project = env.CIRCLE_PROJECT_REPONAME ?? 'circleci'\n const scope = env.CIRCLE_PR_NUMBER ?? env.CIRCLE_BRANCH ?? ''\n\n return { id: `circle:${owner}:${project}:${scope}`, name: `${owner ? `${owner}/` : ''}${project}#${scope}`, commit: env.CIRCLE_SHA1 }\n }\n\n return null\n}\n","import { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs, read } from '@internals/utils'\nimport { cliReporter, Diagnostics, Hookable, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'\nimport { createSnapshot } from '@kubb/studio'\nimport type { BranchSnapshotChanges, PublishedSnapshot, SnapshotChanges } from '@kubb/studio/protocol'\nimport { pluralize } from '../../ui/text.ts'\nimport { createPlainWriter } from '../../loggers/plainWriter.ts'\nimport setupReporters from '../../loggers/reporters.ts'\nimport { type CiContext, detectCi } from './ci.ts'\nimport { loadConfigs, runStudio, type SnapshotOptions } from './run.ts'\nimport type { command } from '../../commands/studio/snapshot.ts'\nimport type { CommandRunner } from 'gunshi'\n\n/**\n * Walks up from `directory` to the first package.json with a name and a version.\n */\nasync function findPackageJson(directory: string): Promise<{ name: string; version: string }> {\n const packageJson = JSON.parse(await read(join(directory, 'package.json')).catch(() => '{}')) as Partial<{ name: string; version: string }>\n if (packageJson.name && packageJson.version) return { name: packageJson.name, version: packageJson.version }\n\n const parent = dirname(directory)\n if (parent === directory)\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `No package.json with a name and a version found above ${process.cwd()}`,\n help: 'Pass `--name` and `--version`, or run from a package with a package.json.',\n })\n\n return findPackageJson(parent)\n}\n\nfunction resolveCiIdentity(options: SnapshotOptions): CiContext {\n const detected = detectCi()\n // A custom --id drops the detected base, since runs on that branch may use a custom id too.\n const ci = options.id ? { id: options.id, name: detected?.name ?? options.id, commit: detected?.commit } : detected\n\n if (!ci) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'Could not detect a supported CI provider (GitHub Actions, GitLab CI, Bitbucket Pipelines, CircleCI). Pass --id.',\n })\n }\n\n // An explicit --base-id may not name a branch, so it labels the comparison itself.\n const base = options.baseId ? { branch: options.baseId, id: options.baseId } : ci.base\n\n return { ...ci, base: base?.id === ci.id ? undefined : base }\n}\n\nfunction absoluteUrl(studioUrl: string, path: string): string {\n return new URL(path, `${studioUrl}/`).toString()\n}\n\ntype SnapshotResult = {\n id: string\n /** Sequence number on the CI agent, when Studio sends one. */\n number?: number\n name: string | null\n version: string | null\n integrity: string | null\n url: string\n snapshotIdUrl: string\n /** Studio page of the snapshot, when Studio sends one. */\n webUrl?: string\n expiresAt: string\n agentUrl: string\n /** What changed since the previous snapshot of this package on this agent. */\n changes?: SnapshotChanges\n /** What differs from the latest snapshot of the base branch, named by `branch`. */\n branchChanges?: BranchSnapshotChanges & { branch: string }\n}\n\nfunction toResult({ studioUrl, snapshot, ci }: { studioUrl: string; snapshot: PublishedSnapshot; ci: CiContext }): SnapshotResult {\n return {\n id: snapshot.id,\n number: snapshot.number,\n name: snapshot.name,\n version: snapshot.version,\n integrity: snapshot.integrity,\n url: absoluteUrl(studioUrl, snapshot.url),\n snapshotIdUrl: absoluteUrl(studioUrl, snapshot.snapshotIdUrl),\n webUrl: snapshot.webUrl ? absoluteUrl(studioUrl, snapshot.webUrl) : undefined,\n expiresAt: snapshot.expiresAt,\n agentUrl: absoluteUrl(studioUrl, `/agents/${snapshot.agent.slug ?? snapshot.agent.id}`),\n changes: snapshot.changes,\n branchChanges: snapshot.branchChanges && ci.base ? { ...snapshot.branchChanges, branch: ci.base.branch } : undefined,\n }\n}\n\n/** How many files differ, `against` what. */\nfunction describeChanges(changes: SnapshotChanges, against: string): string {\n const { added, changed, removed } = changes\n const parts = [\n added.length && `+${pluralize(added.length, 'file')}`,\n changed.length && `~${changed.length} changed`,\n removed.length && `-${removed.length} removed`,\n ].filter(Boolean)\n\n return parts.length ? `${parts.join(' ')} ${against}` : `No changes ${against}`\n}\n\n/** One summary line: how many files changed, and since which run. */\nexport function formatChanges(changes: SnapshotChanges): string {\n if (!changes.base) {\n return 'First snapshot'\n }\n const { number, commit, createdAt } = changes.base\n\n return describeChanges(changes, `vs ${number ? `#${number}` : (commit?.slice(0, 7) ?? createdAt)}`)\n}\n\n/** One summary line: how the snapshot differs from the base branch's latest one. */\nexport function formatBranchChanges(changes: BranchSnapshotChanges & { branch: string }): string {\n if (changes.base) return describeChanges(changes, `vs ${changes.branch}`)\n\n return changes.baseFound ? `No snapshot of ${changes.branch} for this package yet` : `No snapshot of ${changes.branch} to compare with`\n}\n\nfunction printSummary(result: SnapshotResult): void {\n const row = (label: string, value: string) => ` ${styleText('dim', label.padEnd(7))} ${value}`\n\n console.log(\n [\n '',\n ...(result.webUrl ? [row('View', styleText('cyan', result.webUrl))] : []),\n ...(result.changes ? [row('Diff', formatChanges(result.changes))] : []),\n ...(result.branchChanges ? [row('Branch', formatBranchChanges(result.branchChanges))] : []),\n row('Use', `npm i ${result.url}`),\n row('Expires', result.expiresAt.slice(0, 10)),\n ].join('\\n'),\n )\n}\n\n/**\n * Generates the project, packs it, and publishes it to Kubb Studio in one request, under the CI\n * agent the run's identity names.\n */\nexport async function snapshot(options: SnapshotOptions): Promise<void> {\n const token = options.token ?? process.env.KUBB_TOKEN\n if (!token) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: 'An organization CI API key is required. Pass --token or set KUBB_TOKEN.',\n })\n }\n const { config } = await loadConfigs(options)\n const ci = resolveCiIdentity(options)\n // package.json is read only for whichever of name/version --name and --version did not supply.\n const { name, version: packageVersion } =\n options.name && options.packageVersion\n ? { name: options.name, version: options.packageVersion }\n : await findPackageJson(process.cwd()).then((found) => ({ name: options.name ?? found.name, version: options.packageVersion ?? found.version }))\n const logLevel = logLevelMap[options.logLevel ?? 'info']\n\n const write = options.json ? (line: string) => console.error(line) : (line: string) => console.log(line)\n const hooks = new Hookable<KubbHooks>()\n // The steps below are the CI log; the run's own per-file output only shows when asked for with --log-level verbose.\n setupReporters(hooks, { logLevel: logLevel > logLevelMap.info ? logLevel : logLevelMap.silent, reporters: [cliReporter], writer: createPlainWriter(write) })\n const step = (message: string) => {\n if (logLevel > logLevelMap.silent) {\n write(message)\n }\n }\n\n hooks.hook('kubb:generation:end', ({ filesCreated = 0, status, hrStart }) => {\n if (status !== 'failed' && hrStart) step(`✓ Generated ${pluralize(filesCreated, 'file')} in ${formatMs(getElapsedMs(hrStart))}`)\n })\n\n try {\n const published = await createSnapshot({\n studioUrl: options.studioUrl,\n apiKey: token,\n config,\n hooks,\n id: ci.id,\n name: ci.name,\n packageName: name,\n version: packageVersion,\n commit: ci.commit,\n baseId: ci.base?.id,\n })\n const result = toResult({ studioUrl: options.studioUrl, snapshot: published, ci })\n\n step(`✓ Packed ${result.name ?? name}@${result.version ?? packageVersion}`)\n step(`✓ Published snapshot ${result.number ? `#${result.number}` : result.id} for ${ci.name}${ci.commit ? `@${ci.commit.slice(0, 7)}` : ''}`)\n\n if (options.json) console.log(JSON.stringify(result))\n else printSummary(result)\n } catch (error) {\n step('✖ Snapshot failed')\n throw error\n }\n}\n\nexport const runner: CommandRunner<{ args: typeof command.args; extensions: {} }> = ({ values }) =>\n runStudio(\n values,\n (options) =>\n snapshot({\n ...options,\n token: values.token,\n id: values.id,\n baseId: values.baseId,\n name: values.name,\n packageVersion: values.packageVersion,\n json: values.json,\n }),\n { json: values.json },\n )\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,sBAAsB,WAA8D;CAC3F,IAAI,CAAC,WACH;CAGF,IAAI;EACF,MAAM,QAAQ,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC;EACxD,OAAO,MAAM,cAAc,SAAS,MAAM,eAAe,KAAA;CAC3D,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,cAAc,KAAqB;CACjD,OAAO,IACJ,YAAY,CAAC,CACb,QAAQ,eAAe,GA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 @@
|
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-CPE0t6oh.cjs");
|
|
2
|
+
const require_utils = require("./utils-BLXM2UkN.cjs");
|
|
3
|
+
const require_run = require("./run-DkBJkKor.cjs");
|
|
4
|
+
let node_util = require("node:util");
|
|
5
|
+
let node_os = require("node:os");
|
|
6
|
+
let node_path = require("node:path");
|
|
7
|
+
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
8
|
+
//#region src/runners/studio/status.ts
|
|
9
|
+
/** How long a worker has run, such as `2h 14m`, `5m` or `40s`. */
|
|
10
|
+
function formatUptime(ms) {
|
|
11
|
+
const minutes = Math.floor(ms / 6e4);
|
|
12
|
+
if (minutes < 1) return `${Math.max(0, Math.floor(ms / 1e3))}s`;
|
|
13
|
+
if (minutes < 60) return `${minutes}m`;
|
|
14
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
15
|
+
}
|
|
16
|
+
const tilde = (file) => require_utils.isPathInside(file, (0, node_os.homedir)()) ? `~${file.slice((0, node_os.homedir)().length)}` : file;
|
|
17
|
+
/**
|
|
18
|
+
* The `kubb studio status` table: one row per topic, each ending with the command that changes it.
|
|
19
|
+
*/
|
|
20
|
+
function formatStatus({ studioUrl, credentials, worker, project, logPath, now = Date.now() }) {
|
|
21
|
+
const pairing = (() => {
|
|
22
|
+
if (!credentials) return {
|
|
23
|
+
value: `${(0, node_util.styleText)("red", "✖")} not paired`,
|
|
24
|
+
command: "kubb studio login"
|
|
25
|
+
};
|
|
26
|
+
const name = `${credentials.agentSlug || credentials.agentId}${credentials.organizationSlug ? ` · org ${credentials.organizationSlug}` : ""}`;
|
|
27
|
+
if (credentials.studioUrl !== studioUrl) return {
|
|
28
|
+
value: `${(0, node_util.styleText)("yellow", "!")} ${name} · ${credentials.studioUrl}`,
|
|
29
|
+
command: "kubb studio login"
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
value: `${(0, node_util.styleText)("green", "✓")} ${name}`,
|
|
33
|
+
command: "kubb studio logout"
|
|
34
|
+
};
|
|
35
|
+
})();
|
|
36
|
+
const uptime = worker.startedAt ? ` · up ${formatUptime(now - worker.startedAt)}` : "";
|
|
37
|
+
const workerRow = worker.running ? {
|
|
38
|
+
value: `${(0, node_util.styleText)("green", "●")} ${worker.state} · PID ${worker.pid}${uptime}`,
|
|
39
|
+
command: "kubb studio stop"
|
|
40
|
+
} : {
|
|
41
|
+
value: `${(0, node_util.styleText)("dim", "○")} ${worker.state}`,
|
|
42
|
+
command: "kubb studio start"
|
|
43
|
+
};
|
|
44
|
+
const remembered = credentials?.projects?.[project];
|
|
45
|
+
const permissions = remembered ? require_run.formatPermissionRows(remembered) : [(0, node_util.styleText)("dim", "not chosen yet")];
|
|
46
|
+
const rows = [
|
|
47
|
+
{
|
|
48
|
+
label: "Pairing",
|
|
49
|
+
...pairing
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
label: "Worker",
|
|
53
|
+
...workerRow
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
label: "Project",
|
|
57
|
+
value: `${node_path.default.basename(project)} · ${tilde(project)}`
|
|
58
|
+
},
|
|
59
|
+
...permissions.map((value, index) => ({
|
|
60
|
+
label: index === 0 ? "Permissions" : "",
|
|
61
|
+
value,
|
|
62
|
+
command: !remembered && index === 0 ? "kubb studio connect" : void 0
|
|
63
|
+
})),
|
|
64
|
+
{
|
|
65
|
+
label: "Logs",
|
|
66
|
+
value: tilde(logPath)
|
|
67
|
+
}
|
|
68
|
+
];
|
|
69
|
+
const width = Math.max(...rows.filter((row) => row.command).map((row) => (0, node_util.stripVTControlCharacters)(row.value).length));
|
|
70
|
+
return rows.map(({ label, value, command }) => {
|
|
71
|
+
const line = ` ${label.padEnd(11)} ${value}`;
|
|
72
|
+
return command ? `${line}${" ".repeat(width - (0, node_util.stripVTControlCharacters)(value).length + 3)}${(0, node_util.styleText)("dim", command)}` : line;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
exports.formatStatus = formatStatus;
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=status-C-NPN63r.cjs.map
|