@kubb/studio 5.6.0 → 5.6.2

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["process","delay","process","kubbVersion","version","delay","delay"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/time.ts","../src/operations/machine.ts","../src/operations/api.ts","../src/operations/constants.ts","../package.json","../src/operations/generations.ts","../src/operations/generationEvents.ts","../src/operations/rpc.ts","../src/runtime/StudioSession.ts","../src/runtime/runConnection.ts","../src/runtime/client.ts","../src/operations/pair.ts"],"sourcesContent":["/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","import { hash, randomBytes } from 'node:crypto'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createStorage, type Storage } from 'unstorage'\nimport fsDriver from 'unstorage/drivers/fs'\n\n/**\n * Key-value storage the runtime uses for its machine secret and the last Studio config.\n *\n * One storage per process, since one process serves one config file. Hosts install their own\n * driver on startup: Nitro passes its `kubb` mount, the CLI an fs driver under `~/.kubb/cache`.\n * The in-memory default keeps the runtime usable without a host, at the cost of a machine\n * identity that changes on every restart.\n */\nlet storage: Storage = createStorage()\nlet hasInstalledStorage = false\n\n/**\n * Installs the storage driver the runtime persists to. Call once, before connecting.\n */\nexport function setStorage(next: Storage): void {\n storage = next\n hasInstalledStorage = true\n}\n\n/**\n * A storage backed by files under `base`, so the machine secret and the last Studio config\n * survive a restart. Repeated pairings of one machine depend on that secret staying put.\n */\nexport function createFileStorage(base: string): Storage {\n return createStorage({ driver: fsDriver({ base }) })\n}\n\nlet fallbackSecretPromise: Promise<string> | null = null\n\n/**\n * Loads the fallback machine secret from the runtime storage.\n * On first use it generates a secret and persists it, so the machine identity stays\n * stable across restarts. An identity that changes on every boot breaks session\n * creation with Studio whenever the startup registration call fails.\n */\nasync function loadOrCreateFallbackSecret(): Promise<string> {\n // The secret is memoized for the life of the process, so a host that reads the machine token\n // before installing its storage is bound to the throwaway in-memory default. Nothing else\n // surfaces that: the write succeeds, and the identity silently changes on every restart, which\n // Studio rejects with a 403 on the next session create.\n if (!hasInstalledStorage) {\n console.warn(\n styleText('yellow', 'Deriving the machine token before a storage driver was installed'),\n 'call setStorage() first, or set KUBB_AGENT_SECRET, to keep a stable machine identity across restarts',\n )\n }\n\n const stored = await storage.getItem('machine-secret').catch(() => null)\n\n if (typeof stored === 'string' && stored) {\n return stored\n }\n\n const secret = randomBytes(32).toString('hex')\n\n await storage.setItem('machine-secret', secret).catch(() => {\n console.warn(\n styleText('yellow', 'Could not persist the generated machine secret'),\n 'set KUBB_AGENT_SECRET to keep a stable machine identity across restarts',\n )\n })\n\n return secret\n}\n\n/**\n * Hashes a stable secret into the machine token Studio expects, so a host can derive one from its\n * own identity without duplicating `getMachineToken`'s SHA-256 step.\n */\nexport function machineTokenFrom(secret: string): string {\n return hash('sha256', secret)\n}\n\n/**\n * Returns the machine token derived from the `KUBB_AGENT_SECRET` environment variable.\n * Falls back to a generated secret persisted in the runtime storage if the env var is not set.\n * The token is hashed with SHA-256.\n */\nexport async function getMachineToken(): Promise<string> {\n if (process.env.KUBB_AGENT_SECRET) {\n return machineTokenFrom(process.env.KUBB_AGENT_SECRET)\n }\n\n fallbackSecretPromise ??= loadOrCreateFallbackSecret()\n\n return machineTokenFrom(await fallbackSecretPromise)\n}\n","import { setTimeout as delay } from 'node:timers/promises'\nimport { getErrorMessage } from '@internals/utils'\nimport { FetchError, ofetch } from 'ofetch'\nimport type { AgentCapacity, AgentRegisterInput, AgentRegisterResponse } from '../protocol/index.ts'\nimport { getMachineToken } from './machine.ts'\n\n/**\n * Reads a human-readable message from a Studio JSON error body, when it has one. `FetchError`'s own\n * message stops at the status line, so the detail Studio sends with a failure (an agent limit, a\n * revoked token) would otherwise never reach the user.\n */\nfunction responseMessage(data: unknown): string | undefined {\n if (!data || typeof data !== 'object') {\n return undefined\n }\n\n const body = data as { error_description?: unknown; message?: unknown; error?: unknown }\n for (const value of [body.error_description, body.message, body.error]) {\n if (typeof value === 'string' && value) {\n return value\n }\n }\n\n return undefined\n}\n\n/**\n * Thrown when Studio rejects the agent token itself (401). Retrying cannot help: the token was\n * revoked, or the agent it belonged to was deleted in the Studio UI. Hosts catch this to forget\n * the stored credential and pair again.\n */\nexport class InvalidAgentTokenError extends Error {\n constructor(studioUrl: string, options?: ErrorOptions) {\n super(`Kubb Studio rejected this agent's token. It was revoked or the agent was deleted in ${studioUrl}.`, options)\n this.name = 'InvalidAgentTokenError'\n }\n}\n\n/**\n * Thrown when Studio refuses this agent's protocol version (426). Retrying cannot help until the\n * agent is upgraded, so hosts stop instead of reconnecting.\n */\nexport class IncompatibleAgentError extends Error {\n constructor(studioUrl: string, detail?: string, options?: ErrorOptions) {\n super(`Kubb Studio at ${studioUrl} requires a newer agent${detail ? `: ${detail}` : ''}. Upgrade @kubb/studio or the Kubb agent image.`, options)\n this.name = 'IncompatibleAgentError'\n }\n}\n\n/**\n * Whether a thrown value carries `statusCode`. Not narrowed to `FetchError`: a host wrapper can\n * throw its own error shape with the same field.\n */\nfunction rejectedWith(error: unknown, statusCode: number): boolean {\n return (error as { statusCode?: number } | undefined)?.statusCode === statusCode\n}\n\nfunction registrationError(cause: unknown): Error {\n const detail = (cause instanceof FetchError ? responseMessage(cause.data) : undefined) ?? getErrorMessage(cause)\n return new Error(detail ? `Failed to register with Kubb Studio: ${detail}` : 'Failed to register with Kubb Studio', { cause })\n}\n\ntype RegisterProps = {\n studioUrl: string\n token: string\n /** Names this agent process, so Studio tells two processes sharing one token apart. */\n instanceId: string\n capacity: AgentCapacity\n signal?: AbortSignal\n}\n\n/**\n * Registers this agent process with Kubb Studio (`POST /api/agent/connect`): binds the machine\n * identity to the token, reports what the process can take on, and gets back the URL of the one\n * socket it keeps open.\n *\n * Makes one bounded attempt; `runConnection` owns retries. A rejected token (401) throws\n * {@link InvalidAgentTokenError} and an unsupported agent version (426) throws\n * {@link IncompatibleAgentError}, since retrying either cannot help.\n */\nexport async function registerAgent({ token, studioUrl, instanceId, capacity, signal }: RegisterProps): Promise<AgentRegisterResponse> {\n const body: AgentRegisterInput = { machineToken: await getMachineToken(), instanceId, capacity }\n\n try {\n return await ofetch<AgentRegisterResponse>(`${studioUrl}/api/agent/connect`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body,\n retry: 0,\n timeout: 10_000,\n signal,\n })\n } catch (error) {\n if (rejectedWith(error, 401)) throw new InvalidAgentTokenError(studioUrl, { cause: error })\n if (rejectedWith(error, 426))\n throw new IncompatibleAgentError(studioUrl, error instanceof FetchError ? responseMessage(error.data) : undefined, { cause: error })\n throw registrationError(error)\n }\n}\n\n/**\n * Status values returned by Studio's jobs API.\n */\nexport type StudioJobStatus = 'queued' | 'running' | 'success' | 'failed' | 'canceled'\n\n/** How a snapshot's files differ from an earlier snapshot of the same package, relative to `output.path`. */\nexport type StudioSnapshotChanges = {\n /** The snapshot these changes are measured against, `null` when there is none to compare with. */\n base: {\n id: string\n version: string | null\n /** The commit the base snapshot was built from, when reported. */\n commit?: string\n createdAt: string\n } | null\n added: Array<string>\n changed: Array<string>\n removed: Array<string>\n}\n\n/**\n * `StudioSnapshotChanges` against a pull request's base branch. `baseFound` tells apart the two\n * reasons `base` can be `null`: `false` when no CI agent is registered for the branch yet (the\n * workflow has never run there), `true` when that agent exists but has no snapshot of this package\n * to compare with.\n */\nexport type StudioBranchSnapshotChanges = StudioSnapshotChanges & { baseFound: boolean }\n\n/**\n * Package view returned on a successful snapshot job from Studio.\n */\nexport type StudioSnapshot = {\n /**\n * Immutable snapshot id.\n */\n id: string\n /**\n * npm package name, or `null` when Studio stored none.\n */\n name: string | null\n /**\n * npm package version, or `null` when Studio stored none.\n */\n version: string | null\n /**\n * Subresource integrity hash for the tarball, or `null` when unavailable.\n */\n integrity: string | null\n /**\n * Preferable download path, often the readable `/packages/{agentSlug}/{name}.tgz` form.\n */\n url: string\n /**\n * Stable download path keyed by snapshot id.\n */\n snapshotIdUrl: string\n /**\n * ISO timestamp after which Studio may delete the tarball.\n */\n expiresAt: string\n /** What changed since the previous snapshot on the same agent. Absent when Studio or the agent predates it. */\n changes?: StudioSnapshotChanges\n /** What differs from the latest snapshot of the CI agent `baseId` names. Absent without a base. */\n branchChanges?: StudioBranchSnapshotChanges\n}\n\n/**\n * Job record from `POST /api/jobs` and `GET /api/jobs/{id}`.\n */\nexport type StudioJob = {\n /**\n * Job id returned by Studio when the job was queued.\n */\n id: string\n /**\n * Current status. Poll until `success`, `failed`, or `canceled`.\n */\n status: StudioJobStatus\n /**\n * Failure message when `status` is `failed`.\n */\n error?: string\n /**\n * Package view when a snapshot job finished successfully.\n */\n snapshot?: StudioSnapshot\n}\n\n/**\n * First wait before `createJob` retries a busy or queue-full response, absent a `Retry-After` hint.\n */\nconst CREATE_JOB_INITIAL_DELAY_MS = 1_000\n\n/**\n * Slowest `createJob` backs off to between retries.\n */\nconst CREATE_JOB_MAX_INTERVAL_MS = 10_000\n\n/**\n * Statuses worth retrying: the agent has no free connection yet (409, a stale conflict a moment\n * later resolves), its queue is momentarily full (429), or it has no live connection at all yet\n * (503, an agent process that is mid-reconnect). Anything else (404 agent not found, 401/403 auth)\n * is thrown straight away, since retrying cannot change the outcome.\n */\nconst CREATE_JOB_RETRYABLE_STATUSES = new Set([409, 429, 503])\n\n/**\n * Reads Studio's `Retry-After` header (seconds) off a thrown `ofetch` error, when present.\n */\nfunction retryAfterMs(error: unknown): number | undefined {\n const seconds = Number((error as { response?: Response }).response?.headers.get('retry-after'))\n return Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : undefined\n}\n\n/**\n * Adds up to 30% jitter, so every CI run queued behind the same busy agent does not retry in\n * lockstep.\n */\nfunction withJitter(ms: number): number {\n return ms + Math.random() * ms * 0.3\n}\n\n/**\n * Queues a generation or snapshot job on Studio (`POST /api/jobs`).\n *\n * Returns as soon as Studio accepts the job (`202`). Poll with {@link waitForJob} until it finishes.\n * Authenticates with the organization CI API key via `x-api-key`.\n *\n * A busy agent, a full queue, or a momentary lack of a live connection (409, 429, 503) retries with\n * exponential backoff and jitter, honoring Studio's `Retry-After` header when it sends one, up to\n * `timeoutMs`. Every other failure, including a missing agent (404), throws immediately.\n *\n * @example Snapshot job\n * ```ts\n * const job = await createJob({\n * studioUrl: 'https://kubb.studio',\n * token: process.env.KUBB_TOKEN!,\n * type: 'snapshot',\n * agentId: agent.id,\n * name: '@kubb/demo',\n * version: '1.0.0',\n * })\n * const finished = await waitForJob({ studioUrl, token, id: job.id })\n * ```\n */\nexport async function createJob({\n studioUrl,\n token,\n type,\n agentId,\n name,\n version,\n commit,\n baseId,\n config,\n instanceId,\n timeoutMs = 60_000,\n signal,\n}: {\n studioUrl: string\n token: string\n type: 'generation' | 'snapshot'\n agentId: string\n name?: string\n version?: string\n /** The commit this snapshot is built from, so the next one can diff against it. */\n commit?: string\n /** The `id` another CI agent's runs register under, such as the base branch's; this snapshot is also compared with its latest one. */\n baseId?: string\n config?: Record<string, unknown>\n /**\n * The agent process to run the job on, the `instanceId` its client connected with. A CI run passes\n * its own, so an overlapping pipeline under the same CI agent never builds its checkout.\n */\n instanceId?: string\n /**\n * How long to keep retrying a busy or queue-full response before giving up, in milliseconds.\n *\n * @default 60000\n */\n timeoutMs?: number\n signal?: AbortSignal\n}): Promise<StudioJob> {\n const deadline = Date.now() + timeoutMs\n let interval = CREATE_JOB_INITIAL_DELAY_MS\n\n for (;;) {\n signal?.throwIfAborted()\n\n try {\n const { job } = await ofetch<{ job: StudioJob }>(`${studioUrl}/api/jobs`, {\n method: 'POST',\n headers: { 'x-api-key': token },\n body: { type, agentId, name, version, commit, baseId, config, instanceId },\n retry: false,\n timeout: Math.max(deadline - Date.now(), 1),\n signal,\n })\n\n return job\n } catch (error) {\n signal?.throwIfAborted()\n\n const status = (error as { response?: { status?: number } }).response?.status\n if (!status || !CREATE_JOB_RETRYABLE_STATUSES.has(status) || Date.now() >= deadline) throw error\n\n const wait = Math.min(retryAfterMs(error) ?? withJitter(interval), Math.max(deadline - Date.now(), 0))\n if (signal) {\n await delay(wait, undefined, { signal })\n } else {\n await new Promise((resolve) => setTimeout(resolve, wait))\n }\n if (Date.now() >= deadline) throw error\n interval = Math.min(interval * 2, CREATE_JOB_MAX_INTERVAL_MS)\n }\n }\n}\n\n/**\n * A job runs a generation and packs a tarball, so it is never done the instant it is queued.\n */\nconst INITIAL_POLL_DELAY_MS = 2_000\n\n/**\n * Slowest the poll backs off to. Requests per run are roughly `timeoutMs` divided by this, and\n * every concurrent run on the same organization key draws on one budget.\n */\nconst MAX_POLL_INTERVAL_MS = 30_000\n\n/**\n * Polls `GET /api/jobs/{id}` until the job reaches a terminal status, waiting\n * {@link INITIAL_POLL_DELAY_MS} first and doubling up to {@link MAX_POLL_INTERVAL_MS} so a long\n * job stays inside the API key's rate limit.\n *\n * A `failed` job resolves normally. Check `job.status` and `job.error`. Throws only when the\n * deadline passes before Studio finishes.\n */\nexport async function waitForJob({\n studioUrl,\n token,\n id,\n timeoutMs = 60_000,\n signal,\n}: {\n studioUrl: string\n token: string\n id: string\n /**\n * How long to keep polling before throwing, in milliseconds.\n *\n * @default 60000\n */\n timeoutMs?: number\n signal?: AbortSignal\n}): Promise<StudioJob> {\n const deadline = Date.now() + timeoutMs\n let interval = INITIAL_POLL_DELAY_MS\n\n for (;;) {\n signal?.throwIfAborted()\n\n const wait = Math.max(Math.min(interval, deadline - Date.now()), 0)\n if (signal) {\n await delay(wait, undefined, { signal })\n } else {\n await new Promise((resolve) => setTimeout(resolve, wait))\n }\n\n if (Date.now() >= deadline) throw new Error('Timed out waiting for the Studio job')\n\n interval = Math.min(interval * 2, MAX_POLL_INTERVAL_MS)\n\n try {\n // ofetch retries a 429 immediately, which spends the rate limit faster than not retrying.\n const { job } = await ofetch<{ job: StudioJob }>(`${studioUrl}/api/jobs/${id}`, {\n headers: { 'x-api-key': token },\n retry: false,\n timeout: Math.max(deadline - Date.now(), 1),\n signal,\n })\n\n if (job.status === 'success' || job.status === 'failed' || job.status === 'canceled') return job\n } catch (error) {\n signal?.throwIfAborted()\n\n const response = (error as { response?: { status?: number; _data?: { data?: { tryAgainIn?: unknown } } } }).response\n\n if (response?.status !== 429) throw error\n\n const retryAfter = response._data?.data?.tryAgainIn\n const usable = typeof retryAfter === 'number' && Number.isFinite(retryAfter) && retryAfter > 0\n\n // Studio's wait may exceed the ceiling, and a refusal must never shorten the next poll.\n interval = Math.max(interval, usable ? retryAfter : MAX_POLL_INTERVAL_MS)\n }\n }\n}\n\n/**\n * CI agent returned by {@link createAgent}. The token is issued only once, at creation or reuse.\n */\nexport type StudioAgent = {\n /**\n * Agent id, passed to {@link createJob} as `agentId`.\n */\n id: string\n /**\n * Human-readable slug, used to build the readable snapshot URL and the agent's Studio page.\n */\n slug: string\n /**\n * Agent display name.\n */\n name: string\n /**\n * Bearer token for the WebSocket agent session. Mask it before logging.\n */\n token: string\n}\n\n/**\n * Creates or reuses a CI agent (`POST /api/agents`), keyed by `(organization, machineToken)`.\n * Authenticates via `x-api-key`. Reusing the same `machineToken` reuses the same agent instead of\n * consuming a new one from the organization's agent limit.\n */\nexport async function createAgent({\n studioUrl,\n token,\n name,\n machineToken,\n}: {\n studioUrl: string\n token: string\n name: string\n machineToken: string\n}): Promise<StudioAgent> {\n try {\n return await ofetch<StudioAgent>(`${studioUrl}/api/agents`, {\n method: 'POST',\n headers: { 'x-api-key': token },\n body: { name, machineToken },\n })\n } catch (error: unknown) {\n if (error instanceof FetchError) {\n const upgradeUrl = (error.data as { data?: { upgradeUrl?: string } } | undefined)?.data?.upgradeUrl\n const detail = responseMessage(error.data) ?? getErrorMessage(error)\n const hint = upgradeUrl ? ` Agent limit reached; upgrade at ${upgradeUrl}.` : ''\n throw new Error(`Failed to create a Kubb Studio agent: ${detail}${hint}`, { cause: error })\n }\n\n throw error\n }\n}\n","import type { AgentCapacity } from '../protocol/index.ts'\n\n/**\n * Hosted Kubb Studio URL. Exported so credential stores can bind tokens to the resolved instance,\n * not whatever default the client would pick on its own.\n */\nexport const defaultStudioUrl = 'https://kubb.studio'\n\n/**\n * Defaults the Studio client uses when a host passes nothing.\n * Config path is left out on purpose: each host discovers that itself.\n */\nexport const agentDefaults = {\n studioUrl: defaultStudioUrl,\n retryIntervalMs: 30_000,\n heartbeatIntervalMs: 30_000,\n /**\n * Slowest heartbeat a host may ask for. Studio drops an agent from the active list once its\n * stored ping is older than its liveness window, and it persists a ping at most once an hour,\n * so a slower cadence would make a healthy agent look dead after a single missed ping.\n */\n maxHeartbeatIntervalMs: 60_000,\n /** How long a heartbeat ping may take before the session is treated as dead. */\n heartbeatTimeoutMs: 10_000,\n maxConcurrent: 1,\n maxGenerations: 8,\n maxGenerationsMb: 100,\n maxSnapshotMb: 50,\n} as const\n\nfunction positiveNumber(value: string | undefined): number | undefined {\n const parsed = Number(value)\n return value && Number.isFinite(parsed) && parsed > 0 ? parsed : undefined\n}\n\n/**\n * How many generations an agent keeps and how large they may get, read from\n * `KUBB_AGENT_MAX_GENERATIONS`, `KUBB_AGENT_MAX_GENERATIONS_MB` and `KUBB_AGENT_MAX_SNAPSHOT_MB`.\n * An unset or invalid value keeps the default.\n */\nexport function resolveGenerationLimits(env: NodeJS.ProcessEnv = process.env): { maxCount: number; maxMb: number; maxSnapshotMb: number } {\n return {\n maxCount: Math.max(1, Math.floor(positiveNumber(env.KUBB_AGENT_MAX_GENERATIONS) ?? agentDefaults.maxGenerations)),\n maxMb: positiveNumber(env.KUBB_AGENT_MAX_GENERATIONS_MB) ?? agentDefaults.maxGenerationsMb,\n maxSnapshotMb: positiveNumber(env.KUBB_AGENT_MAX_SNAPSHOT_MB) ?? agentDefaults.maxSnapshotMb,\n }\n}\n\n/**\n * An agent's capacity read from `KUBB_AGENT_MAX_CONCURRENT`. An unset or invalid value keeps the\n * default: one job at a time.\n */\nexport function resolveAgentCapacity(env: NodeJS.ProcessEnv = process.env): AgentCapacity {\n return {\n maxConcurrent: Math.max(1, Math.floor(positiveNumber(env.KUBB_AGENT_MAX_CONCURRENT) ?? agentDefaults.maxConcurrent)),\n }\n}\n","","import { createHash } from 'node:crypto'\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\nimport { inParallel } from '@internals/utils'\nimport { fsStorage, type Storage } from '@kubb/core'\nimport type { FilePage, FileSource, ReadFilesResult } from '../protocol/index.ts'\n\nconst READ_CONCURRENCY = 50\nconst MB = 1024 * 1024\nconst INDEX_KEY = 'studio/generations.json'\n\n/**\n * Files a run produced, or the output directory held, keyed by path relative to `root`.\n */\nexport type SourceFiles = { storage: Storage; root: string; paths: Set<string> }\n\n/**\n * The path form {@link SourceFiles} keys on: relative to `root`, with forward slashes.\n */\nexport function relativeStoragePath({ root, filePath }: { root: string; filePath: string }): string {\n return (isAbsolute(filePath) ? relative(resolve(root), filePath) : filePath).replaceAll('\\\\', '/')\n}\n\n/**\n * A set as kept in the store.\n */\ntype KeptSet = {\n /**\n * The paths a read is checked against. Empty when the set was too large to keep its content.\n */\n paths: Array<string>\n hashes: Record<string, string>\n bytes: number\n}\n\ntype KeptGeneration = {\n jobId: string\n /** When the store took it, in epoch milliseconds. Absent on an index written before it existed. */\n keptAt?: number\n output: KeptSet\n disk?: KeptSet\n peerDependencies: Record<string, string>\n missingDependencies: Array<string>\n}\n\nconst hashOf = (content: string) => createHash('sha1').update(content).digest('hex').slice(0, 16)\n\nconst totalBytes = (entries: Array<KeptGeneration>) => entries.reduce((sum, { output, disk }) => sum + output.bytes + (disk?.bytes ?? 0), 0)\n\n/**\n * What the output directory holds on disk before a run. `undefined` when `outputPath` is not a real\n * subdirectory of `root` (listing the root would take in every source file) or holds more than `maxFiles`.\n */\nexport async function listDisk({ root, outputPath, maxFiles }: { root: string; outputPath: string; maxFiles: number }): Promise<SourceFiles | undefined> {\n const outputDir = resolve(root, outputPath)\n const fromRoot = relative(resolve(root), outputDir)\n if (!fromRoot || fromRoot.startsWith('..') || fromRoot.startsWith(sep)) return undefined\n\n const storage = fsStorage()\n const keys = await storage.readKeys(outputDir)\n if (keys.length > maxFiles) return undefined\n\n const paths = keys\n .filter((key) => !key.split('/').includes('node_modules'))\n .map((key) => relative(resolve(root), resolve(outputDir, key)).replaceAll('\\\\', '/'))\n return { storage, root, paths: new Set(paths) }\n}\n\n/**\n * Keeps recent generations by job id in `storage`, with an index next to them so a store on disk\n * survives a restart. A generation is only ever looked up by its job id, so on a pooled sandbox one\n * tenant never reaches another's output. The oldest go past `maxCount` or `maxMb`, but the newest\n * always stays.\n */\nexport function createGenerationStore({\n storage,\n maxCount,\n maxMb,\n ttlMs,\n now = Date.now,\n}: {\n storage: Storage\n maxCount: number\n maxMb: number\n /** How long a generation stays readable. Unset, it stays until count or size pushes it out. */\n ttlMs?: number\n now?: () => number\n}) {\n let index: Array<KeptGeneration> | undefined\n\n // An entry from before `keptAt` existed never expires, so upgrading drops nothing.\n const isLive = (generation: KeptGeneration) => ttlMs === undefined || generation.keptAt === undefined || now() - generation.keptAt < ttlMs\n\n // Hashed so a job id from the wire can never point outside the store.\n const dirOf = (jobId: string) => `studio/generations/${hashOf(jobId)}/`\n\n async function load(): Promise<Array<KeptGeneration>> {\n if (index) return index\n const stored = await storage.readItem(INDEX_KEY).catch(() => null)\n try {\n index = stored ? (JSON.parse(stored) as Array<KeptGeneration>) : []\n } catch {\n index = []\n }\n return index\n }\n\n /**\n * Copies `files` into the store as one set of `jobId`. Above `maxSetMb` only the hashes are kept.\n */\n async function keep({ jobId, source, files, maxSetMb }: { jobId: string; source: FileSource; files: SourceFiles; maxSetMb: number }): Promise<KeptSet> {\n const maxSetBytes = maxSetMb * MB\n const hashes: Record<string, string> = {}\n let bytes = 0\n await inParallel({\n items: [...files.paths],\n limit: READ_CONCURRENCY,\n run: async (path) => {\n // Output outside the root would land outside the store too.\n if (path.split('/').includes('..')) return\n const content = await files.storage.readItem(resolve(files.root, path))\n if (content === null) return\n hashes[path] = hashOf(content)\n bytes += Buffer.byteLength(content)\n if (bytes <= maxSetBytes) await storage.writeItem(`${dirOf(jobId)}${source}/${path}`, content)\n },\n })\n if (bytes > maxSetBytes) {\n await storage.empty(`${dirOf(jobId)}${source}/`)\n return { paths: [], hashes, bytes: 0 }\n }\n return { paths: Object.keys(hashes), hashes, bytes }\n }\n\n async function drop(jobId: string): Promise<void> {\n await storage.empty(dirOf(jobId))\n }\n\n return {\n keep,\n drop,\n get: async (jobId: string) => (await load()).find((generation) => generation.jobId === jobId && isLive(generation)),\n latest: async () => (await load()).filter(isLive).at(-1),\n /** Total bytes of every set the store holds, expired ones too until the next add drops them. */\n bytes: async () => totalBytes(await load()),\n async add(generation: KeptGeneration): Promise<void> {\n const current = await load()\n for (const expired of current.filter((entry) => !isLive(entry))) await drop(expired.jobId)\n const entries = current.filter((entry) => entry.jobId !== generation.jobId && isLive(entry))\n entries.push({ ...generation, keptAt: now() })\n while (entries.length > 1 && (entries.length > maxCount || totalBytes(entries) > maxMb * MB)) {\n await drop(entries.shift()!.jobId)\n }\n index = entries\n await storage.writeItem(INDEX_KEY, JSON.stringify(entries))\n },\n /**\n * Reads the requested paths the set holds, skipping any it does not, one page of lines when `limit` is given.\n */\n async read({\n generation,\n source,\n paths,\n cursor = 0,\n limit,\n }: {\n generation: KeptGeneration\n source: FileSource\n paths: Array<string>\n cursor?: number\n limit?: number\n }): Promise<ReadFilesResult> {\n const kept = new Set(generation[source]?.paths)\n const files: Record<string, string> = {}\n const pages: Record<string, FilePage> = {}\n await inParallel({\n items: paths.filter((path) => kept.has(path)),\n limit: READ_CONCURRENCY,\n run: async (path) => {\n const content = await storage.readItem(`${dirOf(generation.jobId)}${source}/${path}`)\n if (content === null) return\n if (limit === undefined) {\n files[path] = content\n return\n }\n const lines = content.split(/\\r\\n|\\r|\\n/)\n const end = Math.min(cursor + limit, lines.length)\n files[path] = lines.slice(cursor, end).join('\\n')\n pages[path] = { nextCursor: end < lines.length ? end : null, totalLines: lines.length }\n },\n })\n return limit === undefined ? { files } : { files, pages }\n },\n }\n}\n\nexport type GenerationStore = ReturnType<typeof createGenerationStore>\n","import { stripVTControlCharacters } from 'node:util'\nimport { getElapsedMs } from '@internals/utils'\nimport { Diagnostics, type Hookable, type KubbHooks } from '@kubb/core'\nimport { type GenerationEvent, type GenerationEventPayloads, type GenerationEventType, generationEventTypes } from '../protocol/index.ts'\nimport { relativeStoragePath } from './generations.ts'\n\n/** How each published hook's context becomes its wire payload; a hook without a projection fails to compile. */\ntype Projections = { [Type in GenerationEventType]: (...args: KubbHooks[Type]) => GenerationEventPayloads[Type] }\n\nconst MAX_QUEUED_EVENTS = 1_024\nconst RESERVED_EVENTS = 64\nconst isDiscardable = (event: GenerationEvent) => event.type === 'kubb:files:processing:update' || event.type === 'kubb:info' || event.type === 'kubb:success'\n\n/** Forwards selected Kubb lifecycle events to a native Cap'n Web stream. */\nexport function createGenerationStream(\n hooks: Hookable<KubbHooks>,\n jobId: string,\n): { stream: ReadableStream<GenerationEvent>; close: () => Promise<void>; dispose: () => void; fail: (error: unknown) => void } {\n const unhooks: Array<() => void> = []\n let root = ''\n let controller!: ReadableStreamDefaultController<GenerationEvent>\n let closed = false\n const stream = new ReadableStream<GenerationEvent>(\n {\n start: (value) => {\n controller = value\n },\n cancel: () => {\n closed = true\n detach()\n },\n },\n { highWaterMark: MAX_QUEUED_EVENTS },\n )\n\n /**\n * Registers a listener and keeps its remover, so one generation's listeners come off the session\n * emitter again when that generation ends.\n */\n function on<TName extends keyof KubbHooks & string>(name: TName, handler: (...args: KubbHooks[TName]) => unknown): void {\n unhooks.push(hooks.hook(name, handler))\n }\n\n function emitEvent<Type extends GenerationEventType>(type: Type, data: GenerationEventPayloads[Type]): void {\n if (closed) return\n const event = { jobId, type, data, version: 1 as const, timestamp: Date.now() } as unknown as GenerationEvent\n if (controller.desiredSize! <= RESERVED_EVENTS && isDiscardable(event)) return\n if (controller.desiredSize! <= 0) {\n fail(new Error(`Generation event stream exceeded ${MAX_QUEUED_EVENTS} queued events`))\n return\n }\n controller.enqueue(event)\n }\n\n const projections: Projections = {\n 'kubb:plugin:start': ({ plugin }) => [{ plugin: { name: plugin.name } }],\n 'kubb:plugin:end': ({ plugin, duration, success }) => [{ plugin: { name: plugin.name }, duration, success }],\n 'kubb:build:start': ({ config, adapter }) => [{ config: { name: config.name }, adapter: { name: adapter.name } }],\n 'kubb:build:end': ({ files, config, outputDir }) => [\n { files: files.map((file) => ({ path: relativeStoragePath({ root: config.root, filePath: file.path }), name: file.name })), outputDir },\n ],\n 'kubb:files:processing:start': ({ files }) => [{ total: files.length }],\n 'kubb:files:processing:update': ({ files }) => [\n {\n files: files.map(({ file, processed, total, percentage }) => ({\n file: relativeStoragePath({ root, filePath: file.path }),\n processed,\n total,\n percentage,\n })),\n },\n ],\n 'kubb:files:processing:end': ({ files }) => [{ total: files.length }],\n 'kubb:info': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:success': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:warn': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:error': ({ error }) => [{ message: error.message, stack: error.stack }],\n 'kubb:diagnostic': ({ diagnostic }) => [\n {\n code: diagnostic.code,\n message: diagnostic.message,\n severity: diagnostic.severity,\n location: 'location' in diagnostic ? diagnostic.location : undefined,\n help: 'help' in diagnostic ? diagnostic.help : undefined,\n plugin: 'plugin' in diagnostic ? diagnostic.plugin : undefined,\n stack: 'cause' in diagnostic ? diagnostic.cause?.stack : undefined,\n },\n ],\n 'kubb:generation:start': ({ config }) => [{ name: config.name, plugins: config.plugins.length }],\n 'kubb:generation:end': () => [],\n 'kubb:generation:summary': ({ duration, fileCount, failedPlugins, status }) => [{ duration, fileCount, failedPlugins, status }],\n 'kubb:lifecycle:start': () => [],\n 'kubb:lifecycle:end': () => [],\n 'kubb:format:start': () => [],\n 'kubb:format:end': () => [],\n 'kubb:lint:start': () => [],\n 'kubb:lint:end': () => [],\n 'kubb:hooks:start': () => [],\n 'kubb:hooks:end': () => [],\n 'kubb:hook:start': ({ id, command, args }) => [{ id, command, args: args ? [...args] : undefined }],\n 'kubb:hook:line': ({ id, line }) => [{ id, line }],\n 'kubb:hook:end': ({ id, command, args, success, error }) => [\n { id, command, args: args ? [...args] : undefined, success, error: error ? { message: error.message, stack: error.stack } : undefined },\n ],\n }\n\n function forward<Type extends GenerationEventType>(type: Type): void {\n on(type, (...args: KubbHooks[Type]) => emitEvent(type, projections[type](...args)))\n }\n\n // Paths in `kubb:files:processing:update` are made relative to the root the build announced.\n on('kubb:build:start', ({ config }) => {\n root = config.root\n })\n\n for (const type of generationEventTypes) forward(type)\n\n // Registered after the loop so the summary follows its `kubb:generation:end`; core never emits it.\n on('kubb:generation:end', ({ diagnostics = [], status, hrStart, filesCreated }) => {\n if (!hrStart) {\n return\n }\n\n const duration = Math.round(getElapsedMs(hrStart))\n\n emitEvent('kubb:generation:summary', [\n { duration, fileCount: filesCreated ?? 0, failedPlugins: Diagnostics.failedPlugins(diagnostics).length, status: status ?? 'success' },\n ])\n })\n\n /**\n * Takes this generation's listeners off the session emitter. Safe to call twice.\n */\n function detach(): void {\n for (const unhook of unhooks) unhook()\n unhooks.length = 0\n }\n\n async function close(): Promise<void> {\n if (closed) {\n return\n }\n closed = true\n detach()\n controller.close()\n }\n\n function fail(error?: unknown): void {\n detach()\n if (closed) {\n return\n }\n closed = true\n controller.error(error)\n }\n\n return { stream, close, dispose: () => fail(), fail }\n}\n","import { newWebSocketRpcSession, RpcTarget } from 'capnweb'\nimport type {\n AgentApi,\n GenerateInput,\n PublishSnapshotInput,\n ReadFilesInput,\n RpcClose,\n RpcConnection,\n RpcConnector,\n SaveConfigInput,\n StudioApi,\n} from '../protocol/index.ts'\nimport { AGENT_INSTANCE_HEADER } from '../protocol/index.ts'\nimport { isLoopbackHost } from './url.ts'\n\nconst CONNECT_TIMEOUT_MS = 5_000\n\n/**\n * The only methods Studio may call on an agent. A `StudioSession` carries far more than\n * {@link AgentApi}, so it is wrapped rather than exposed: what Cap'n Web can reach is exactly what\n * this class re-declares.\n */\nclass AgentRpcTarget extends RpcTarget implements AgentApi {\n constructor(private readonly api: AgentApi) {\n super()\n }\n\n connect() {\n return this.api.connect()\n }\n startGeneration(input: GenerateInput) {\n return this.api.startGeneration(input)\n }\n saveConfig(input: SaveConfigInput) {\n return this.api.saveConfig(input)\n }\n publishSnapshot(input: PublishSnapshotInput) {\n return this.api.publishSnapshot(input)\n }\n readFiles(input: ReadFilesInput) {\n return this.api.readFiles(input)\n }\n cancel(jobId: string) {\n return this.api.cancel(jobId)\n }\n}\n\n/** Node's `WebSocket` takes undici's `headers` option, which the DOM typing leaves out. */\ntype NodeWebSocket = new (url: string, init: { headers: Record<string, string> }) => WebSocket\n\n/**\n * Opens a Studio WebSocket, closing it when the handshake exceeds {@link CONNECT_TIMEOUT_MS}. Node\n * fires no `close` event when the handshake itself fails, only `error`, so `closed` settles as 1006 there.\n */\nfunction openSocket({ url, headers }: { url: string; headers: Record<string, string> }): { socket: WebSocket; closed: Promise<RpcClose> } {\n const socket = new (WebSocket as unknown as NodeWebSocket)(url, { headers })\n\n const closed = new Promise<RpcClose>((resolve) => {\n let opened = false\n const timer = setTimeout(() => {\n if (socket.readyState === WebSocket.CONNECTING) {\n socket.close(3008, 'Connection timeout')\n }\n }, CONNECT_TIMEOUT_MS)\n\n socket.addEventListener(\n 'open',\n () => {\n opened = true\n clearTimeout(timer)\n },\n { once: true },\n )\n socket.addEventListener(\n 'close',\n (event) => {\n clearTimeout(timer)\n resolve({ code: event.code, reason: event.reason })\n },\n { once: true },\n )\n socket.addEventListener('error', () => {\n if (opened) return\n clearTimeout(timer)\n resolve({ code: 1006, reason: '' })\n })\n })\n\n return { socket, closed }\n}\n\n/**\n * Opens an authenticated Cap'n Web session to Studio over a WebSocket. Rejects an unencrypted URL\n * before opening the socket, so a bearer token never reaches a plaintext host.\n *\n * @example\n * ```ts\n * const rpc = await connectWebSocketRpc({ url: 'wss://studio.kubb.dev/s/1', token, local: session })\n * await rpc.studio.ping()\n * ```\n */\nexport const connectWebSocketRpc: RpcConnector = async ({ url, token, instanceId, local }): Promise<RpcConnection> => {\n const { protocol, hostname, host } = new URL(url)\n if (protocol !== 'wss:' && !(protocol === 'ws:' && isLoopbackHost(hostname))) {\n throw new Error(`Refusing unencrypted WebSocket to ${host}`)\n }\n\n const { socket, closed } = openSocket({ url, headers: { Authorization: `Bearer ${token}`, [AGENT_INSTANCE_HEADER]: instanceId } })\n const studio = newWebSocketRpcSession<StudioApi>(socket, new AgentRpcTarget(local))\n studio.onRpcBroken(() => socket.close())\n\n return {\n studio,\n closed,\n close: () => studio[Symbol.dispose](),\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { getErrorMessage, read, toError } from '@internals/utils'\nimport {\n cacheStorage,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n fsStorage,\n Hookable,\n type KubbHooks,\n memoryStorage,\n resolveCacheDir,\n} from '@kubb/core'\nimport { version as kubbVersion } from '../../package.json'\nimport {\n type AgentApi,\n type AgentCapacity,\n type AgentRegisterResponse,\n type AgentLoad,\n type AgentPermissions,\n type ConfigFileView,\n type ConnectMessagePayload,\n type GenerateInput,\n type GenerateResult,\n type GenerationEvent,\n type GenerationRun,\n GENERATION_GONE_MESSAGE,\n MAX_FILES_PER_REQUEST,\n MAX_PAGE_LINES,\n type ReadFilesInput,\n type ReadFilesResult,\n type SaveConfigInput,\n type SaveResult,\n type PublishSnapshotInput,\n type PublishSnapshotResult,\n AgentCloseCode,\n type RpcClose,\n type RpcConnector,\n type RpcConnection,\n} from '../protocol/index.ts'\nimport { registerAgent } from '../operations/api.ts'\nimport { agentDefaults, resolveAgentCapacity, resolveGenerationLimits } from '../operations/constants.ts'\nimport { mergeAdapter, mergePlugins, resolvePeerDependencies, toPackageName } from '../operations/resolveConfig.ts'\nimport { RpcTarget } from 'capnweb'\nimport { createGenerationStore, type GenerationStore, listDisk, relativeStoragePath } from '../operations/generations.ts'\nimport { createGenerationStream } from '../operations/generationEvents.ts'\nimport { connectWebSocketRpc } from '../operations/rpc.ts'\n\nconst DISK_SNAPSHOT_MAX_FILES = 10_000\n\n/**\n * Folds error-severity diagnostics into one thrown error so logs name the failing plugin or pass.\n */\nfunction generationFailure(diagnostics: ReadonlyArray<Diagnostic>): Error {\n const reasons = diagnostics\n .filter(Diagnostics.isProblem)\n .filter((diagnostic) => diagnostic.severity === 'error')\n .map((diagnostic) => (diagnostic.plugin ? `${diagnostic.plugin}: ${diagnostic.message}` : diagnostic.message))\n\n if (!reasons.length) return new Error('Generation failed')\n\n return new Error(`Generation failed: ${reasons.length} error${reasons.length === 1 ? '' : 's'}: ${reasons.join('; ')}`)\n}\n\n/** A sandbox shares one in-memory generation store across tenants, so old generations expire. */\nconst SANDBOX_GENERATION_TTL_MS = 15 * 60_000\n\n/**\n * A fresh root for one sandbox job. Kubb keys its output manifest cache by root, so tenants that\n * shared the agent's own root would read each other's manifest.\n */\nfunction createJobRoot(): Promise<string> {\n return mkdtemp(path.join(tmpdir(), 'kubb-job-'))\n}\n\n/**\n * Removes a job root and the manifest cache Kubb derived from it. Best effort: a leftover temp\n * directory must not fail a job that already finished.\n */\nasync function removeJobRoot(jobRoot: string): Promise<void> {\n await Promise.all([rm(jobRoot, { recursive: true, force: true }), rm(resolveCacheDir(jobRoot), { recursive: true, force: true })]).catch(() => {})\n}\n\nclass GenerationRunTarget extends RpcTarget implements GenerationRun {\n constructor(\n private readonly generationStream: ReadableStream<GenerationEvent>,\n private readonly generationResult: Promise<GenerateResult>,\n private readonly cancelGeneration: () => Promise<void>,\n /** Stops the run. Cap'n Web calls this on explicit disposal and on a dropped session alike. */\n private readonly stopGeneration: () => void,\n ) {\n super()\n }\n\n async events() {\n return this.generationStream\n }\n result() {\n return this.generationResult\n }\n cancel() {\n return this.cancelGeneration()\n }\n // Cap'n Web also calls this when the peer session is torn down, so a dropped socket stops the run.\n [Symbol.dispose]() {\n this.stopGeneration()\n }\n}\n\nexport type StudioSessionOptions = {\n connector?: RpcConnector\n token: string\n studioUrl?: string\n configPath: string\n /**\n * Loads the on-disk Kubb config. Injected so each host resolves config its own way: the Docker\n * agent from an explicit `KUBB_AGENT_CONFIG` path, the CLI through the same discovery\n * `kubb generate` uses.\n */\n loadConfig: () => Promise<Config>\n /**\n * The runtime's own version, reported to Studio next to the `kubb` version.\n */\n version: string\n /**\n * What Studio may do in this project, off unless the host grants it. A sandbox session narrows\n * them further: it never writes to disk and never edits a config file, and it always generates\n * from the spec Studio sends.\n */\n permissions?: Partial<AgentPermissions>\n root?: string\n /**\n * Maximum reconnect backoff in milliseconds.\n */\n retryInterval?: number\n /**\n * Milliseconds between keep-alive pings, clamped to `agentDefaults.maxHeartbeatIntervalMs`.\n * Raise it to halve the traffic and database writes a long-lived agent costs, at the price of\n * Studio taking that much longer to notice the agent has gone. Lower it in development to see\n * connection state move immediately.\n */\n heartbeatInterval?: number\n /**\n * What this agent process can take on, reported to Studio at registration. Unset fields come from\n * `KUBB_AGENT_MAX_CONCURRENT`.\n */\n capacity?: Partial<AgentCapacity>\n /**\n * Names this agent process to Studio, sent at registration and as {@link AGENT_INSTANCE_HEADER}\n * on the socket. `runConnection` sets one per process, so a reconnect is the same instance and a\n * restart is a new one. Not meant to be set directly by a host.\n */\n instanceId?: string\n /**\n * Aborting this disconnects the session and stops the reconnect loop. Hosts wire it to their own\n * shutdown signal, usually `SIGINT` or `SIGTERM`.\n */\n signal?: AbortSignal\n /**\n * Installs listeners on the session's event emitter, which carries both the session events and\n * the generations it runs. Left out, the runtime prints nothing, which is what a library should\n * default to.\n */\n installLogger?: (hooks: Hookable<KubbHooks>) => void | Promise<void>\n}\n\n/**\n * A session's options with every default filled in, so nothing downstream repeats a fallback.\n */\ntype ResolvedOptions = StudioSessionOptions & {\n studioUrl: string\n root: string\n permissions: AgentPermissions\n heartbeatInterval: number\n capacity: AgentCapacity\n instanceId: string\n /**\n * Absolute path to the config file, for reading and patching it. `configPath` keeps the form the\n * host gave, which is what Studio shows.\n */\n configFile: string\n}\n\n/**\n * Fills in a host's options: the hosted Studio URL, the current working directory, and every\n * permission off unless granted. Idempotent, so a reconnect can pass an already-resolved bag\n * back in.\n */\nfunction applyStudioDefaults(options: StudioSessionOptions): ResolvedOptions {\n const root = options.root ?? process.cwd()\n\n return {\n ...options,\n studioUrl: options.studioUrl ?? agentDefaults.studioUrl,\n root,\n // `configPath` is relative to the agent's root unless it is already absolute, which is what\n // `resolve` does on its own.\n configFile: path.resolve(root, options.configPath),\n permissions: { allowWrite: false, allowConfigEdit: false, allowExec: false, allowRead: false, ...options.permissions },\n // Studio counts an agent offline once its last ping is older than its liveness window, so a\n // slower cadence would make a healthy agent invisible. Clamped here rather than in a host's\n // env parsing, so every host is held to the contract.\n heartbeatInterval: Math.min(options.heartbeatInterval ?? agentDefaults.heartbeatIntervalMs, agentDefaults.maxHeartbeatIntervalMs),\n capacity: { ...resolveAgentCapacity(), ...options.capacity },\n instanceId: options.instanceId ?? randomUUID(),\n }\n}\n\n/**\n * Jobs one agent process can run at once today. Two runs would share this session's hook emitter,\n * and with it each other's events, so the connection keeps this limit.\n */\nconst RUNTIME_MAX_CONCURRENT = 1\n\n/**\n * How a session ends: what the host is told, and whether it reconnects.\n */\ntype SessionEnd = {\n reason: string\n retry: boolean\n /** Reported through `studio:error` when the end needs the user to act. */\n error?: Error\n}\n\n/**\n * Reads what Studio meant by closing the connection. A code Studio did not send on purpose is an\n * ordinary drop, and the agent reconnects as it always has.\n */\nfunction planEnd(close: RpcClose | void): SessionEnd {\n const code = close?.code\n // Every connection attempt registers first, so reconnecting is how the agent registers again.\n if (code === AgentCloseCode.REAUTHENTICATE) return { reason: 'Kubb Studio asked the agent to register again', retry: true }\n if (code === AgentCloseCode.SUPERSEDED) return { reason: 'another instance of this agent took over', retry: false }\n if (code === AgentCloseCode.INCOMPATIBLE) {\n return {\n reason: 'this agent is too old for Kubb Studio, or was deleted',\n retry: false,\n error: new Error('Kubb Studio closed the connection: this agent is too old for it, or was deleted. Upgrade the agent, or pair it again.'),\n }\n }\n return { reason: 'connection closed', retry: true }\n}\n\nfunction isValidPage({ cursor, limit }: Pick<ReadFilesInput, 'cursor' | 'limit'>): boolean {\n if (limit === undefined) return cursor === undefined\n if (cursor !== undefined && (!Number.isSafeInteger(cursor) || cursor < 0)) return false\n return Number.isSafeInteger(limit) && limit >= 1 && limit <= MAX_PAGE_LINES\n}\n\n/**\n * One agent-to-Studio RPC transport: opening it, keeping it alive, and serving remote methods.\n * `runConnection` owns the lifetime and retry of each attempt.\n */\nexport class StudioSession implements AgentApi {\n readonly #options: ResolvedOptions\n // Each session gets its own isolated event emitter so generation events from one session do not\n // bleed into another session's WebSocket stream.\n readonly #hooks = new Hookable<KubbHooks>()\n /**\n * Removers for every listener this session added (socket, shutdown signal, hooks) so `dispose`\n * detaches them in one pass. Listeners a host attached itself through `installLogger` survive.\n */\n readonly #unhooks: Array<() => void> = []\n\n /**\n * What registration handed back, and the marker for whether the agent registered at all.\n * Before it resolves there is no sandbox flag to read.\n */\n #registration: AgentRegisterResponse | undefined\n #rpc: RpcConnection | undefined\n\n // Whether the session is over: guards the close event from tearing down twice, and a shutdown\n // from being turned into a reconnect.\n #disposed = false\n // Guards against a second `generate` command starting while one is already running. Without\n // this, two concurrent `generate()` calls share this socket via `setupEventsStream`, and their\n // events interleave with no way for Studio to tell the two runs apart.\n #isGenerating = false\n #activeJob: { jobId: string; cancel: () => Promise<void> } | undefined\n #heartbeatTimer: ReturnType<typeof setTimeout> | undefined\n #store: GenerationStore | undefined\n readonly #limits = resolveGenerationLimits()\n /**\n * Resolves when Studio calls {@link StudioSession.connect}. `studio:ready` waits on this so the\n * host does not queue jobs before the agent session is registered.\n */\n readonly #connectAck = Promise.withResolvers<void>()\n readonly #ended = Promise.withResolvers<SessionEnd>()\n readonly closed = this.#ended.promise\n #generationResult: Promise<GenerateResult> | undefined\n\n constructor(options: StudioSessionOptions) {\n this.#options = applyStudioDefaults(options)\n // dispose() may reject this before start() awaits it\n void this.#connectAck.promise.catch(() => {})\n }\n\n /**\n * A sandbox agent runs on Studio's own infrastructure, so it has no user project to touch.\n */\n get #isSandbox(): boolean {\n return this.#registration?.isSandbox === true\n }\n\n /**\n * Kept in the project's cache directory, so it survives a restart, except on a sandbox: its pool\n * sessions run every tenant's jobs, so it keeps them in memory. Looked up by job id only.\n */\n get #generations(): GenerationStore {\n this.#store ??= createGenerationStore({\n storage: this.#isSandbox ? memoryStorage() : cacheStorage({ root: this.#options.root }),\n maxCount: this.#limits.maxCount,\n maxMb: this.#limits.maxMb,\n ttlMs: this.#isSandbox ? SANDBOX_GENERATION_TTL_MS : undefined,\n })\n return this.#store\n }\n\n get #canWrite(): boolean {\n return !this.#isSandbox && this.#options.permissions.allowWrite\n }\n\n get #canEditConfig(): boolean {\n return !this.#isSandbox && this.#options.permissions.allowConfigEdit\n }\n\n /**\n * A sandbox agent always allows reading its output back; a local agent only when opted in.\n */\n get #canRead(): boolean {\n return this.#isSandbox || this.#options.permissions.allowRead\n }\n\n async start(): Promise<void> {\n const { token, studioUrl, signal, heartbeatInterval, installLogger, instanceId, capacity } = this.#options\n\n await installLogger?.(this.#hooks)\n signal?.addEventListener('abort', this.#onAbort, { once: true })\n this.#unhooks.push(() => signal?.removeEventListener('abort', this.#onAbort))\n\n try {\n signal?.throwIfAborted()\n // Before registering, so a host can cover the wait: registration is a round trip and the\n // socket after it opens without being awaited.\n await this.#hooks.callHook('studio:connecting', { url: studioUrl })\n\n if (capacity.maxConcurrent > RUNTIME_MAX_CONCURRENT) {\n await this.#warn(\n `Running ${RUNTIME_MAX_CONCURRENT} job at a time: KUBB_AGENT_MAX_CONCURRENT=${capacity.maxConcurrent} needs per-job workers, which this agent does not have yet`,\n )\n }\n\n const registration = await registerAgent({\n signal,\n token,\n studioUrl,\n instanceId,\n capacity: { ...capacity, maxConcurrent: Math.min(capacity.maxConcurrent, RUNTIME_MAX_CONCURRENT) },\n })\n\n signal?.throwIfAborted()\n this.#registration = registration\n\n const rpc = await (this.#options.connector ?? connectWebSocketRpc)({ url: registration.socketUrl, token, instanceId, local: this })\n this.#rpc = rpc\n void rpc.closed.then(this.#onClose)\n\n if (signal?.aborted || this.#disposed) {\n rpc.close()\n throw new Error('Connection stopped during startup')\n }\n\n this.#scheduleHeartbeat(heartbeatInterval)\n await this.#hooks.callHook('studio:connected', {\n url: studioUrl,\n versions: { studio: registration.version, kubb: kubbVersion, agent: this.#options.version },\n agentSlug: registration.agentSlug,\n organizationSlug: registration.organizationSlug,\n })\n // Studio registers the agent by calling connect() over RPC. Ready means that handshake landed.\n await this.#connectAck.promise\n await this.#hooks.callHook('studio:ready', {})\n } catch (error) {\n await this.dispose()\n if (!signal?.aborted) await this.#hooks.callHook('studio:error', { error: toError(error) })\n throw error\n }\n }\n\n reportRetry(delayMs: number): Promise<void> | void {\n return this.#hooks.callHook('studio:reconnecting', { delayMs })\n }\n\n #warn(message: string, permission?: keyof AgentPermissions): Promise<void> | void {\n return this.#hooks.callHook('studio:warn', { message, permission })\n }\n\n /**\n * Declines a request: logs why locally, then tells Studio. The two wordings differ on purpose,\n * since the log names the request that was ignored and the error names what the caller can do.\n */\n async #refuse(reason: string, message: string, permission?: keyof AgentPermissions): Promise<never> {\n await this.#warn(reason, permission)\n throw new Error(message)\n }\n\n /**\n * Brackets one Studio command with `studio:command:start` and `studio:command:end`. A command\n * that declined its request reports no `info`, and only the start is heard.\n */\n async #command<T>({ command, run }: { command: string; run: () => Promise<{ value: T; info?: string }> }): Promise<T> {\n await this.#hooks.callHook('studio:command:start', { command })\n const { value, info } = await run()\n if (info !== undefined) await this.#hooks.callHook('studio:command:end', { command, info })\n return value\n }\n\n #scheduleHeartbeat(interval: number): void {\n const rpc = this.#rpc\n if (!rpc) {\n return\n }\n this.#heartbeatTimer = setTimeout(async () => {\n try {\n await this.#ping(rpc)\n } catch {\n if (this.#rpc === rpc) {\n rpc.close()\n }\n return\n }\n\n if (this.#rpc === rpc) {\n this.#scheduleHeartbeat(interval)\n }\n }, interval)\n }\n\n /**\n * Races `studio.ping()` against a deadline, so a half-open socket can't hang it forever.\n * */\n async #ping(rpc: RpcConnection): Promise<void> {\n const { promise: timedOut, reject: onTimeout } = Promise.withResolvers<never>()\n const timer = setTimeout(() => onTimeout(new Error('Heartbeat ping timed out')), agentDefaults.heartbeatTimeoutMs)\n\n try {\n // A load report that fails to build must not cost the heartbeat itself.\n const load = await Promise.race([this.#load().catch(() => undefined), timedOut])\n await Promise.race([rpc.studio.ping(load), timedOut])\n } finally {\n clearTimeout(timer)\n }\n }\n\n async #load(): Promise<AgentLoad> {\n return {\n running: this.#isGenerating ? 1 : 0,\n rssMb: Math.round(process.memoryUsage().rss / (1024 * 1024)),\n storeBytes: await this.#generations.bytes(),\n accepting: true,\n }\n }\n\n /**\n * Reads `kubb.config.ts` and reports which plugin options Studio may edit.\n *\n * Skipped when the host did not grant `allowConfigEdit`. Not cached: the user can edit the file\n * between two Studio actions.\n */\n async #readConfigFileView(source?: string): Promise<ConfigFileView | undefined> {\n if (!this.#canEditConfig) {\n return undefined\n }\n\n try {\n const { readConfig } = await import('../operations/configFile.ts')\n return readConfig(source ?? (await read(this.#options.configFile)))\n } catch (error) {\n await this.#warn(`Could not read ${this.#options.configFile}: ${getErrorMessage(error)}`)\n\n return undefined\n }\n }\n\n async connect(): Promise<ConnectMessagePayload> {\n const { configPath, root, version, loadConfig, permissions } = this.#options\n const [config, file] = await Promise.all([loadConfig(), this.#readConfigFileView()])\n\n const payload: ConnectMessagePayload = {\n versions: { kubb: kubbVersion, agent: version },\n root,\n config: {\n path: configPath,\n file,\n plugins: config.plugins.map((plugin) => ({\n name: toPackageName(plugin.name),\n options: plugin.options ?? {},\n })),\n },\n permissions: {\n ...permissions,\n allowWrite: this.#canWrite,\n allowConfigEdit: this.#canEditConfig,\n allowRead: this.#canRead,\n },\n }\n this.#connectAck.resolve()\n return payload\n }\n\n #onAbort = (): void => void this.#end({ reason: 'shutdown', retry: false }).catch(() => {})\n\n #onClose = (close: RpcClose | void): void => void this.#end(planEnd(close)).catch(() => {})\n\n /** Closes this attempt and waits for its generation to stop before another can start. */\n dispose(): Promise<void> {\n return this.#end({ reason: 'shutdown', retry: false })\n }\n\n async #end(plan: SessionEnd): Promise<void> {\n if (this.#disposed) {\n await this.closed\n return\n }\n this.#disposed = true\n clearTimeout(this.#heartbeatTimer)\n this.#rpc?.close()\n this.#rpc = undefined\n this.#connectAck.reject(new Error('Session ended before Studio called connect()'))\n for (const unhook of this.#unhooks) unhook()\n this.#unhooks.length = 0\n\n try {\n await this.#activeJob?.cancel()\n await this.#generationResult?.catch(() => {})\n await this.#hooks.callHook('studio:disconnected', { reason: plan.reason })\n if (plan.error) await this.#hooks.callHook('studio:error', { error: plan.error })\n } finally {\n this.#ended.resolve(plan)\n }\n }\n\n startGeneration(data: GenerateInput): GenerationRun {\n const generationStream = createGenerationStream(this.#hooks, data.jobId)\n const controller = new AbortController()\n const cancelRun = async () => {\n controller.abort(new Error('Generation canceled'))\n }\n const result = this.#runGeneration(data, controller, cancelRun)\n .then(async (value) => {\n await generationStream.close()\n return value\n })\n .catch((error) => {\n generationStream.fail(error)\n throw error\n })\n .finally(() => {\n if (this.#activeJob?.cancel === cancelRun) this.#activeJob = undefined\n })\n if (this.#activeJob?.cancel === cancelRun) this.#generationResult = result\n // A disconnect can reject this after the remote caller disappeared.\n void result.catch(() => {})\n\n return new GenerationRunTarget(generationStream.stream, result, cancelRun, () => {\n controller.abort(new Error('Generation canceled'))\n generationStream.dispose()\n })\n }\n\n /**\n * Cancels the currently running job when its id matches `jobId`.\n */\n async cancel(jobId: string): Promise<void> {\n if (this.#activeJob?.jobId === jobId) await this.#activeJob.cancel()\n }\n\n async #runGeneration(data: GenerateInput, controller: AbortController, cancelRun: () => Promise<void>): Promise<GenerateResult> {\n // Checked before the first `await`, so two calls in the same tick can't both pass.\n if (this.#disposed) throw new Error('Connection is closed')\n if (this.#isGenerating) {\n return this.#refuse('Ignored generate: a generation is already in progress', 'A generation is already in progress, please wait for it to finish')\n }\n this.#isGenerating = true\n this.#activeJob = { jobId: data.jobId, cancel: cancelRun }\n\n let root = this.#options.root\n\n try {\n if (this.#isSandbox) root = await createJobRoot()\n return await this.#command<GenerateResult>({ command: 'generate', run: () => this.#generate({ data, root, signal: controller.signal }) })\n } finally {\n if (root !== this.#options.root) await removeJobRoot(root)\n this.#isGenerating = false\n }\n }\n\n async #generate({ data, root, signal }: { data: GenerateInput; root: string; signal: AbortSignal }): Promise<{ value: GenerateResult; info: string }> {\n const { loadConfig, permissions } = this.#options\n const config = await loadConfig()\n const patch = data.config\n const plugins = await mergePlugins(config.plugins, patch?.plugins)\n const adapter = await mergeAdapter(config.adapter, patch?.adapter)\n\n // A sandbox agent always uses the inline spec (empty string included, since it has no disk\n // file); a non-sandbox agent always reads its spec from disk.\n const inputOverride = this.#isSandbox ? (patch?.input ?? '') : undefined\n\n if (permissions.allowWrite && this.#isSandbox) {\n await this.#warn('Running in a sandbox, so writing files is disabled')\n }\n\n if (patch?.input && !this.#isSandbox) {\n await this.#warn('Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox agent')\n }\n\n const resolvedPlugins = plugins ?? config.plugins\n\n const storage = this.#canWrite ? fsStorage() : memoryStorage()\n const diskFiles = this.#hasProjectOnDisk ? await listDisk({ root, outputPath: config.output.path, maxFiles: DISK_SNAPSHOT_MAX_FILES }) : undefined\n const disk = diskFiles\n ? await this.#generations.keep({ jobId: data.jobId, source: 'disk', files: diskFiles, maxSetMb: this.#limits.maxSnapshotMb })\n : undefined\n\n // The session's own emitter carries the run: the host's logger is already on it from\n // `connect`, and the stream's listeners come off again once the run ends, so one run's\n // listeners never see the next.\n const kubb = createKubb(\n {\n ...config,\n root,\n input: inputOverride ?? config.input,\n storage,\n output: permissions.allowExec ? { ...config.output } : { ...config.output, format: false, lint: false, postGenerate: [] },\n plugins: resolvedPlugins,\n adapter,\n },\n { hooks: this.#hooks, signal },\n )\n const result = await kubb.generate().catch(async (error: unknown) => {\n await this.#generations.drop(data.jobId)\n throw error\n })\n if (!result.success) {\n await this.#generations.drop(data.jobId)\n throw generationFailure(result.diagnostics)\n }\n\n const paths = new Set(result.files.map((file) => relativeStoragePath({ root, filePath: file.path })))\n const output = await this.#generations.keep({ jobId: data.jobId, source: 'output', files: { storage, root, paths }, maxSetMb: this.#limits.maxMb })\n if (!output.paths.length && Object.keys(output.hashes).length) {\n await this.#warn('Kept only the hashes of this generation: its output is too large to keep')\n }\n const { peerDependencies, missingDependencies } = await resolvePeerDependencies(resolvedPlugins.map(({ name }) => name))\n await this.#generations.add({ jobId: data.jobId, output, disk, peerDependencies, missingDependencies })\n return {\n value: {\n status: 'success',\n files: [...paths],\n fileCount: paths.size,\n hashes: output.hashes,\n disk: disk ? { hashes: disk.hashes } : undefined,\n },\n info: `${resolvedPlugins.length} plugin${resolvedPlugins.length === 1 ? '' : 's'}, ${this.#canWrite ? 'written to disk' : 'in memory'}${inputOverride !== undefined ? ', from a Studio spec' : ''}`,\n }\n }\n\n saveConfig(data: SaveConfigInput): Promise<SaveResult> {\n return this.#command<SaveResult>({ command: 'saveConfig', run: () => this.#saveConfig(data) })\n }\n\n async #saveConfig(data: SaveConfigInput): Promise<{ value: SaveResult; info?: string }> {\n const { configPath, configFile } = this.#options\n\n // Every RPC call gets one result. `edits` is checked before it is walked because values cross\n // the agent trust boundary.\n if (!Array.isArray(data.edits)) {\n await this.#warn('Ignored save: the message carried no edits')\n\n return { value: { outcomes: [], changed: false } }\n }\n\n const edits = data.edits\n const refuse = (reason: string): SaveResult => ({ outcomes: edits.map((edit) => ({ edit, applied: false, reason })), changed: false })\n\n if (!this.#canEditConfig) {\n await this.#warn('Ignored save: editing kubb.config.ts was not granted')\n\n return { value: refuse('the agent was not granted permission to edit kubb.config.ts') }\n }\n\n // A generation reloads the config while it runs, so rewriting the file underneath it would\n // leave that run working from half the change.\n if (this.#isGenerating) {\n return { value: refuse('a generation is in progress') }\n }\n\n try {\n const { writeConfigEdits } = await import('../operations/configFile.ts')\n const { source: patched, outcomes, changed } = await writeConfigEdits({ filePath: configFile, edits })\n\n const applied = outcomes.filter((outcome) => outcome.applied).length\n return {\n value: { outcomes, changed, file: changed ? await this.#readConfigFileView(patched) : undefined },\n info: `applied ${applied}/${outcomes.length} edits to ${configPath}`,\n }\n } catch (error) {\n // An unreadable config, a read-only filesystem. Reported as a refusal of every edit so\n // Studio hears back rather than waiting on a reply that never comes.\n await this.#hooks.callHook('studio:error', { error: toError(error) })\n\n return { value: refuse(getErrorMessage(error)) }\n }\n }\n\n publishSnapshot(data: PublishSnapshotInput): Promise<PublishSnapshotResult> {\n return this.#command<PublishSnapshotResult>({ command: 'snapshot', run: () => this.#publishSnapshot(data) })\n }\n\n async #publishSnapshot(data: PublishSnapshotInput): Promise<{ value: PublishSnapshotResult; info: string }> {\n if (this.#isSandbox) {\n return this.#refuse('Ignored snapshot: a sandbox agent has no project to build a package from', 'A sandbox agent has no project to build a package from')\n }\n\n const { name, version, bundledDependencies, uploadPath } = data\n\n if (!name || !version || !uploadPath) {\n return this.#refuse('Ignored snapshot: the message was missing required fields', 'The request was missing required fields')\n }\n\n const generation = await this.#generations.latest()\n\n if (!generation) {\n return this.#refuse('Ignored snapshot: no prior generation to pack', 'No prior generation exists to pack, run a generation first')\n }\n\n const bundled = new Set(bundledDependencies ?? [])\n const missing = generation.missingDependencies.filter((dependency) => !bundled.has(dependency))\n\n if (missing.length) {\n return this.#refuse(`Ignored snapshot: missing dependencies: ${missing.join(', ')}`, `Missing dependencies: ${missing.join(', ')}`)\n }\n\n try {\n const { createSnapshotPackage, uploadSnapshot } = await import('../operations/snapshotPackage.ts')\n const { files } = await this.#generations.read({ generation, source: 'output', paths: generation.output.paths })\n\n const { bytes, integrity } = await createSnapshotPackage(files, { name, version, peerDependencies: generation.peerDependencies })\n\n const { token, studioUrl, signal } = this.#options\n await uploadSnapshot({ bytes, uploadPath, studioUrl, token, shutdown: signal })\n\n return {\n value: { integrity, peerDependencies: generation.peerDependencies },\n info: `packed ${Object.keys(files).length} file${Object.keys(files).length === 1 ? '' : 's'}`,\n }\n } catch (error) {\n await this.#hooks.callHook('studio:error', { error: toError(error) })\n throw error\n }\n }\n\n /** A sandbox has no project directory to snapshot. */\n get #hasProjectOnDisk(): boolean {\n return !this.#isSandbox && this.#canRead\n }\n\n readFiles(data: ReadFilesInput): Promise<ReadFilesResult> {\n return this.#command<ReadFilesResult>({ command: 'readFiles', run: () => this.#readFiles(data) })\n }\n\n async #readFiles(data: ReadFilesInput): Promise<{ value: ReadFilesResult; info: string }> {\n if (!this.#canRead) {\n return this.#refuse('Ignored files: reading generated files was not granted', 'The agent was not granted permission to read generated files', 'allowRead')\n }\n\n // `paths` came off the wire, so check its shape before walking it.\n if (!Array.isArray(data.paths)) {\n return this.#refuse('Ignored files: the message carried no paths', 'The request carried no paths')\n }\n\n const { paths } = data\n\n if (paths.length > MAX_FILES_PER_REQUEST) {\n return this.#refuse(\n `Ignored files: requested ${paths.length} paths, more than the ${MAX_FILES_PER_REQUEST} allowed per request`,\n `At most ${MAX_FILES_PER_REQUEST} paths may be requested at once`,\n )\n }\n\n if (typeof data.jobId !== 'string' || !data.jobId) {\n return this.#refuse('Ignored files: the message named no job', 'The request named no generation job')\n }\n\n const generation = await this.#generations.get(data.jobId)\n\n if (!generation) {\n return this.#refuse(`Ignored files: job ${data.jobId} is not kept on this agent`, GENERATION_GONE_MESSAGE)\n }\n\n if (!isValidPage(data)) {\n return this.#refuse(\n 'Ignored files: the message carried an invalid page',\n `The cursor must be a whole line from 0 and come with a limit of 1 to ${MAX_PAGE_LINES} lines`,\n )\n }\n\n const source = data.source === 'disk' ? 'disk' : 'output'\n\n if (!generation[source]) {\n return this.#refuse('Ignored files: that job has no snapshot of the files on disk', 'This agent kept no snapshot of the files on disk for that job')\n }\n\n // Only paths the set holds are read, never an arbitrary path.\n const result = await this.#generations.read({ generation, source, paths, cursor: data.cursor, limit: data.limit })\n\n return { value: result, info: `read ${Object.keys(result.files).length}/${paths.length} requested file${paths.length === 1 ? '' : 's'}` }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { IncompatibleAgentError, InvalidAgentTokenError } from '../operations/api.ts'\nimport { agentDefaults } from '../operations/constants.ts'\nimport { StudioSession, type StudioSessionOptions } from './StudioSession.ts'\n\ntype ConnectionOutcome = 'shutdown' | 'stopped'\n\ntype TokenRejection<TCredentials> = {\n error: InvalidAgentTokenError\n credentials: TCredentials\n /** Whether this credential already served a ready session. */\n live: boolean\n}\n\nexport type ConnectionOptions<TCredentials extends { token: string }> = {\n credentials: TCredentials\n clientOptions: (credentials: TCredentials) => Omit<StudioSessionOptions, 'token' | 'signal'>\n onTokenRejected: (rejection: TokenRejection<TCredentials>) => Promise<TCredentials | null>\n signal?: AbortSignal\n /** Used by the client facade once startup succeeds or schedules its first retry. */\n onStarted?: () => void\n}\n\n/** Runs the process's one connection loop, including retries and credential replacement. */\nexport async function runConnection<TCredentials extends { token: string }>({\n credentials,\n clientOptions,\n onTokenRejected,\n signal,\n onStarted,\n}: ConnectionOptions<TCredentials>): Promise<ConnectionOutcome> {\n let current = credentials\n const initialOptions = clientOptions(current)\n const instanceId = initialOptions.instanceId ?? randomUUID()\n let options = initialOptions\n let attempt = 0\n let live = false\n\n while (!signal?.aborted) {\n const session = new StudioSession({ ...options, instanceId, token: current.token, signal })\n try {\n await session.start()\n live = true\n attempt = 0\n onStarted?.()\n const end = await session.closed\n if (!end.retry) return signal?.aborted ? 'shutdown' : 'stopped'\n } catch (error) {\n if (signal?.aborted) return 'shutdown'\n if (error instanceof IncompatibleAgentError) throw error\n await session.dispose()\n const end = await session.closed\n // A terminal socket close during the handshake must not become a network retry.\n if (!end.retry && end.reason !== 'shutdown') return 'stopped'\n if (error instanceof InvalidAgentTokenError) {\n const next = await onTokenRejected({ error, credentials: current, live })\n if (!next) return 'stopped'\n current = next\n options = clientOptions(current)\n live = false\n attempt = 0\n continue\n }\n } finally {\n await session.dispose()\n }\n\n onStarted?.()\n const cap = Math.min(1_000 * 2 ** Math.min(attempt++, 16), options.retryInterval ?? agentDefaults.retryIntervalMs)\n const delayMs = Math.random() * cap\n await session.reportRetry(delayMs)\n try {\n await delay(delayMs, undefined, { signal })\n } catch (error) {\n if (!signal?.aborted) throw error\n }\n }\n return 'shutdown'\n}\n","import type { InvalidAgentTokenError } from '../operations/api.ts'\nimport type { StudioSessionOptions } from './StudioSession.ts'\nimport { runConnection } from './runConnection.ts'\n\nexport type ClientOptions = Omit<StudioSessionOptions, 'signal'> & {\n /** Called once when a background reconnect rejects the credential. */\n onAuthRequired?: (error: InvalidAgentTokenError) => void\n}\n\nexport type Client = {\n connect: () => Promise<void>\n disconnect: () => void\n}\n\n/** Compatibility facade over the shared connection loop. */\nexport function createClient({ onAuthRequired, ...options }: ClientOptions): Client {\n const shutdown = new AbortController()\n const started = Promise.withResolvers<void>()\n let resolved = false\n let running: Promise<unknown> | undefined\n\n return {\n connect() {\n running ??= runConnection({\n credentials: { token: options.token },\n clientOptions: () => options,\n signal: shutdown.signal,\n onStarted: () => {\n resolved = true\n started.resolve()\n },\n onTokenRejected: async ({ error }) => {\n if (!resolved) throw error\n onAuthRequired?.(error)\n return null\n },\n }).then(\n () => started.resolve(),\n (error: unknown) => started.reject(error),\n )\n return started.promise\n },\n disconnect() {\n shutdown.abort()\n },\n }\n}\n","import { setTimeout as delay } from 'node:timers/promises'\nimport { toError } from '@internals/utils'\nimport { ofetch } from 'ofetch'\nimport { agentDefaults } from './constants.ts'\nimport { getMachineToken } from './machine.ts'\n\n/**\n * RFC 8628 device-authorization response from Studio's `/api/auth/device/code` endpoint.\n * Field names match the RFC; the CLI polls with `device_code` and shows `user_code` to the user.\n */\nexport type PairingSession = {\n device_code: string\n user_code: string\n verification_uri: string\n verification_uri_complete: string\n expires_in: number\n interval: number\n}\n\nexport type PairingResult = {\n /**\n * Bearer token for this machine. Write credentials with mode 0600 and never log the value.\n */\n token: string\n agent: {\n /**\n * Stable agent id in Studio.\n */\n id: string\n /**\n * Short slug used in logs and the UI (for example `brave-otter`).\n */\n slug: string\n /**\n * Display name chosen at pairing time.\n */\n name: string\n /**\n * This agent's organization slug, absent for a sandbox or global agent, which has none.\n */\n organizationSlug?: string\n }\n}\n\n/**\n * What this machine registers as. Any member may approve `cli` (`kubb studio`); only an admin may\n * approve `user` and `sandbox` (the Docker image). A `ci` agent never pairs.\n */\nexport type PairingAgentType = 'cli' | 'user' | 'sandbox'\n\n/** Labels, not secrets: a person approving the code in the browser is what authorizes a pairing. */\nconst CLIENT_IDS = { cli: 'kubb-cli', agent: 'kubb-agent' } as const\n\n/**\n * Thrown when a caller aborts `startPairing` or `pollForPairingToken` through their `signal`, such\n * as a `kubb studio` shutdown mid-pairing. Distinct from a denial or an expired code, so a host can\n * exit quietly instead of reporting a pairing failure.\n */\nexport class PairingCanceledError extends Error {\n constructor() {\n super('Pairing was canceled')\n this.name = 'PairingCanceledError'\n }\n}\n\n/** Thrown when the code expired unapproved. A fresh code can still succeed. */\nexport class PairingExpiredError extends Error {\n constructor(message = 'The pairing code expired, pair again') {\n super(message)\n this.name = 'PairingExpiredError'\n }\n}\n\n/** Thrown when the pairing was denied in the browser, including by the organization's agent limit. */\nexport class PairingDeniedError extends Error {\n constructor(message = 'Pairing was denied in the browser') {\n super(message)\n this.name = 'PairingDeniedError'\n }\n}\n\ntype StartPairingOptions = {\n studioUrl?: string\n type: PairingAgentType\n /**\n * Display name for the agent, usually the project or machine name.\n */\n name: string\n hostname: string\n /**\n * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.\n */\n signal?: AbortSignal\n}\n\n/**\n * Asks Studio for a pairing code. The machine token travels with the request and is stored against\n * the code, so approval knows which machine it is pairing: the same machine pairing twice rotates\n * one agent's token instead of creating a second agent.\n */\nexport async function startPairing({ studioUrl = agentDefaults.studioUrl, type, name, hostname, signal }: StartPairingOptions): Promise<PairingSession> {\n try {\n return await ofetch<PairingSession>(`${studioUrl}/api/auth/device/code`, {\n method: 'POST',\n body: {\n client_id: type === 'cli' ? CLIENT_IDS.cli : CLIENT_IDS.agent,\n name,\n hostname,\n machine_token: await getMachineToken(),\n agent_kind: type === 'cli' ? undefined : type,\n },\n signal,\n })\n } catch (error) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n throw error\n }\n}\n\ntype PollOptions = {\n studioUrl?: string\n session: PairingSession\n /**\n * Aborting this stops polling and rejects with {@link PairingCanceledError}, whether the abort\n * lands between polls or during the wait for the next one.\n */\n signal?: AbortSignal\n /** Called when a poll could not reach Studio. Polling carries on. */\n onRetry?: (error: Error) => void\n}\n\ntype PollError = 'authorization_pending' | 'slow_down' | 'expired_token' | 'access_denied' | 'invalid_grant'\n\ntype PollResponse =\n | PairingResult\n | {\n error: PollError | string\n /**\n * Why, when Studio has something more useful to say than the RFC code. An approval that hits\n * the organization's agent limit comes back as `access_denied` with the limit spelled out.\n */\n error_description?: string\n }\n\nfunction isPairingResult(response: PollResponse | undefined): response is PairingResult {\n return !!response && typeof response === 'object' && 'token' in response && typeof response.token === 'string'\n}\n\n/**\n * Polls until the user approves or denies, honoring the server's `slow_down` back-off.\n *\n * Studio's own endpoint is used rather than the auth layer's `/device/token`, because an approved\n * Kubb pairing is worth an agent bearer token, not a user session.\n *\n * @throws {PairingExpiredError} when the code expires before anyone approves it.\n * @throws {PairingDeniedError} when the pairing is denied in the browser.\n * @throws {PairingCanceledError} when `signal` aborts.\n */\nexport async function pollForPairingToken({ studioUrl = agentDefaults.studioUrl, session, signal, onRetry }: PollOptions): Promise<PairingResult> {\n // Both fields cross the network, so neither is trusted as-is: a missing or zero `interval` would\n // spin the poll loop, and a missing or zero `expires_in` would expire the code before the first\n // poll. `> 0` is also false for `NaN` and for a missing field, so it doubles as the type guard.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let intervalMs = (session.interval > 0 ? session.interval : 5) * 1000\n\n while (Date.now() < deadline) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n try {\n await delay(intervalMs, undefined, { signal })\n } catch {\n throw new PairingCanceledError()\n }\n\n let response: PollResponse | undefined\n try {\n response = await ofetch<PollResponse | undefined>(`${studioUrl}/api/agent/token`, {\n method: 'POST',\n body: { device_code: session.device_code },\n // A denial, an expiry, and \"not yet\" all come back as 4xx with a body the caller needs to\n // read, so let every response through and switch on `error` instead of catching.\n ignoreResponseError: true,\n signal,\n })\n } catch (error) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n // Studio can be briefly unreachable (a deploy) while the code is still valid, so retry.\n onRetry?.(toError(error))\n continue\n }\n\n if (isPairingResult(response)) {\n return response\n }\n\n if (!response || typeof response !== 'object' || !('error' in response) || typeof response.error !== 'string') {\n throw new Error('Kubb Studio returned an empty pairing response, pair again')\n }\n\n if (response.error === 'authorization_pending') {\n continue\n }\n\n if (response.error === 'slow_down') {\n intervalMs += 5_000\n continue\n }\n\n if (response.error === 'access_denied') {\n throw new PairingDeniedError(response.error_description)\n }\n\n if (response.error === 'expired_token' || response.error === 'invalid_grant') {\n throw new PairingExpiredError(response.error_description)\n }\n\n throw new Error(response.error_description ?? `Pairing failed (${response.error})`)\n }\n\n throw new PairingExpiredError()\n}\n\ntype PairAgentOptions = StartPairingOptions & {\n /** Shows the code to whoever approves it. Called again for each fresh code. */\n onCode: (session: PairingSession, attempt: number) => void | Promise<void>\n /** Called when a poll could not reach Studio. Polling carries on. */\n onRetry?: (error: Error) => void\n /**\n * Codes to ask for in total when one expires unapproved. A denial or abort ends it at once.\n * @default 1\n */\n maxAttempts?: number\n}\n\n/**\n * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.\n */\nexport async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }: PairAgentOptions): Promise<PairingResult> {\n for (let attempt = 1; ; attempt++) {\n const session = await startPairing(options)\n await onCode(session, attempt)\n\n try {\n return await pollForPairingToken({ studioUrl: options.studioUrl, session, signal: options.signal, onRetry })\n } catch (error) {\n if (!(error instanceof PairingExpiredError) || attempt >= maxAttempts) {\n throw error\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;;;;;;;;;;AAWA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;;;;;;ACkEA,eAAsB,WAAkB,EAAE,OAAO,OAAO,OAA8C;CACpG,MAAM,QAAQ,MAAM,QAAQ;CAE5B,MAAM,SAAS,YAA2B;EACxC,KAAK,MAAM,CAAC,OAAO,SAAS,OAAO,MAAM,IAAI,MAAM,KAAK;CAC1D;CAEA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,OAAO,MAAM,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC;AACzF;;;;;;;;;;;;;;ACzFA,SAAgB,aAAa,SAAmC;CAC9D,MAAM,CAAC,SAAS,eAAe,QAAQ,OAAO,OAAO;CACrD,MAAM,KAAK,UAAU,MAAO,cAAc;CAC1C,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI;AAChC;;;;;;;;;;;ACDA,IAAI,UAAmB,cAAc;AACrC,IAAI,sBAAsB;;;;AAK1B,SAAgB,WAAW,MAAqB;CAC9C,UAAU;CACV,sBAAsB;AACxB;;;;;AAMA,SAAgB,kBAAkB,MAAuB;CACvD,OAAO,cAAc,EAAE,QAAQ,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC;AACrD;AAEA,IAAI,wBAAgD;;;;;;;AAQpD,eAAe,6BAA8C;CAK3D,IAAI,CAAC,qBACH,QAAQ,KACN,UAAU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WAAW;EACjC,MAAM,UAAU,MAAM,aAAa,OAAO;EAC1C,MAAM,OAAO,SAAS,OAAO;EAE7B,IAAI;GACF,OAAO,MAAM,oBAAoB;IAAE,WAAW,QAAQ;IAAW;IAAS,QAAQ,QAAQ;IAAQ;GAAQ,CAAC;EAC7G,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,wBAAwB,WAAW,aACxD,MAAM;EAEV;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["process","kubbVersion","version","NodeWebSocket","process","delay","delay"],"sources":["../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/time.ts","../package.json","../src/resolveConfig.ts","../src/configFile.ts","../src/generations.ts","../src/generationEvents.ts","../src/url.ts","../src/connect.ts","../src/pair.ts","../src/snapshot.ts"],"sourcesContent":["type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","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","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\nimport type { Adapter, Plugin } from '@kubb/core'\nimport { camelCase } from '@internals/utils'\nimport type { JSONKubbConfig, OptionValue } from './protocol.ts'\n\n/**\n * Turns the JSON config Studio sends back into live Kubb objects.\n *\n * A plugin or adapter instance carries closures (`parse`, `getImports`, ...) that cannot survive\n * JSON, so both sides pass options over the wire and the factory is re-invoked here with the merged\n * result. Only `@kubb/plugin-*` packages are resolved this way, so the reinstantiated factory is\n * always one Kubb ships, never an arbitrary module the payload names.\n */\n\ntype PluginFactory = (options: unknown) => Plugin\n\n/**\n * Imports a package, falling back to how the user's project would resolve it.\n *\n * `import()` resolves from this file, so a linked or globally installed Studio (`pnpm link`,\n * `npm i -g`) only sees its own `node_modules` and misses the plugins installed next to the user's\n * config. The retry resolves from `process.cwd()` instead.\n */\nasync function importFromProject(packageName: string): Promise<Record<string, unknown>> {\n try {\n return await import(packageName)\n } catch {\n const require = createRequire(pathToFileURL(`${process.cwd()}/`))\n // `require.resolve` picks the package's `require` condition, so prefer the ESM build sitting\n // next to it. Loading the CJS copy would pull in a second `@kubb/core` instance.\n const resolved = require.resolve(packageName)\n const esm = resolved.replace(/\\.cjs$/, '.js')\n\n return await import(pathToFileURL(esm !== resolved && existsSync(esm) ? esm : resolved).href)\n }\n}\n\n/**\n * Strips the `@kubb/` scope from a plugin package name, matching the `name` convention Kubb\n * plugin factories use internally.\n *\n * @example\n * ```ts\n * toPluginName('@kubb/plugin-ts') // 'plugin-ts'\n * ```\n */\nfunction toPluginName(packageName: string): string {\n return packageName.split('/').pop() ?? packageName\n}\n\n/**\n * Adds the `@kubb/` scope a plugin's package carries but its `name` does not, the inverse of\n * {@link toPluginName}. A name outside the `plugin-` convention is left alone, so a third-party\n * plugin is not reported as one of Kubb's.\n *\n * @example\n * ```ts\n * toPackageName('plugin-ts') // '@kubb/plugin-ts'\n * toPackageName('@acme/my-plugin') // '@acme/my-plugin'\n * ```\n */\nexport function toPackageName(name: string): string {\n return name.startsWith('plugin-') ? `@kubb/${name}` : name\n}\n\n/**\n * Derives the conventional named export for a `@kubb/*` plugin package from its package name.\n *\n * @example\n * ```ts\n * toExportName('@kubb/plugin-react-query') // 'pluginReactQuery'\n * toExportName('@kubb/plugin-ts') // 'pluginTs'\n * ```\n */\nexport function toExportName(packageName: string): string {\n return camelCase(toPluginName(packageName))\n}\n\n/**\n * A `@kubb/plugin-*` package specifier. Nothing else may reach `import()`: only Kubb's own\n * plugins are supported, so a payload naming anything else, a third-party package or a path, is\n * refused before it can execute.\n */\nconst KUBB_PLUGIN_SPECIFIER = /^@kubb\\/plugin-[\\w.-]+$/\n\n/**\n * Whether `name` is a `@kubb/plugin-*` specifier. Exported so `configFile.ts` can refuse the same\n * shape before printing a Studio-supplied plugin name into the config file's source text.\n */\nexport function isKubbPluginSpecifier(name: string): boolean {\n return KUBB_PLUGIN_SPECIFIER.test(name)\n}\n\n/**\n * Dynamically imports a `@kubb/plugin-*` package and returns its factory function.\n *\n * Packages must be pre-installed in the Docker image at build time via the `KUBB_PACKAGES`\n * build ARG, no runtime installation is possible in the distroless container.\n *\n * Resolution order: the camelCase named export the package name implies (e.g. `pluginTs`), then\n * the default export.\n *\n * @throws if the package cannot be imported or exports no callable factory.\n */\nasync function loadPluginFactory(packageName: string): Promise<PluginFactory> {\n if (!isKubbPluginSpecifier(packageName)) {\n throw new Error(`Plugin \"${packageName}\" is not a @kubb/plugin-* package. Kubb Studio only supports Kubb's own plugins.`)\n }\n\n let mod: Record<string, unknown>\n try {\n mod = await importFromProject(packageName)\n } catch (cause) {\n throw new Error(`Plugin \"${packageName}\" could not be loaded. Make sure it is installed: \\`npm install ${packageName}\\``, { cause })\n }\n\n const exportName = toExportName(packageName)\n\n if (typeof mod[exportName] === 'function') return mod[exportName] as PluginFactory\n\n if (typeof mod['default'] === 'function') return mod['default'] as PluginFactory\n\n throw new Error(`Plugin \"${packageName}\" does not export a callable factory. Tried the named export \"${exportName}\" and \"default\".`)\n}\n\n/**\n * Resolves each plugin entry by dynamically importing the `@kubb/plugin-*` package and\n * calling its factory with the provided options.\n *\n * Packages must be pre-installed in the Docker image at build time, use the `KUBB_PACKAGES`\n * build ARG to control which ones are available at runtime.\n *\n * @example\n * ```ts\n * { name: '@kubb/plugin-react-query', options: { output: { path: './hooks' } } }\n * { name: '@kubb/plugin-ts', options: { output: { path: './types' } } }\n * ```\n */\nexport async function resolvePlugins(plugins: NonNullable<JSONKubbConfig['plugins']>): Promise<Array<Plugin>> {\n return Promise.all(\n plugins.map(async ({ name, options }) => {\n const factory = await loadPluginFactory(name)\n return factory(options ?? {}) as Plugin\n }),\n )\n}\n\ntype PackageJSON = {\n version?: string\n}\n\n/** The installed version of each plugin's package, plus the names that could not be resolved. */\nexport async function resolvePeerDependencies(names: Array<string>): Promise<{\n peerDependencies: Record<string, string>\n missingDependencies: Array<string>\n}> {\n const require = createRequire(import.meta.url)\n const uniqueNames = [...new Set(names.map(toPackageName))]\n const peerDependencies: Record<string, string> = {}\n const missingDependencies: Array<string> = []\n\n const versions = await Promise.all(\n uniqueNames.map(async (name) => {\n try {\n const path = require.resolve(`${name}/package.json`)\n const packageJSON = JSON.parse(await readFile(path, 'utf8')) as PackageJSON\n return packageJSON.version\n } catch {\n return undefined\n }\n }),\n )\n\n for (const [index, name] of uniqueNames.entries()) {\n const version = versions[index]\n if (version) {\n peerDependencies[name] = version\n continue\n }\n missingDependencies.push(name)\n }\n\n return { peerDependencies, missingDependencies }\n}\n\n/**\n * Whether `value` is an object literal or a null-prototype object, not an array or class instance.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === null || prototype === Object.prototype\n}\n\n/**\n * Whether `value` survives a JSON round trip, so it can be printed into a config file as a literal.\n * A function, `undefined`, a non-finite number or a class instance comes back from Studio as a\n * lossy copy, so an edit carrying one is refused rather than written into the user's source.\n */\nexport function isOptionValue(value: unknown): value is OptionValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true\n if (typeof value === 'number') return Number.isFinite(value)\n if (Array.isArray(value)) return value.every(isOptionValue)\n if (isPlainObject(value)) return Object.values(value).every(isOptionValue)\n\n return false\n}\n\n/**\n * Deep-merges Studio's options over the disk options, with Studio taking priority, except where the\n * disk value cannot survive JSON. Studio only ever saw a lossy copy of such a value, so the disk\n * value is kept rather than replaced by what Studio echoes back. Plain objects merge key by key, so\n * Studio can still change a literal that sits next to a function (e.g. `group.type` beside `group.name`).\n *\n * @example\n * ```ts\n * mergeOptions({ macros: [camelCaseMacro], syntaxType: 'type' }, { macros: [{ name: 'camelCase' }], syntaxType: 'interface' })\n * // { macros: [camelCaseMacro], syntaxType: 'interface' }\n * ```\n */\nexport function mergeOptions(disk: Record<string, unknown>, studio: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...disk }\n\n for (const [key, value] of Object.entries(studio)) {\n const current = disk[key]\n\n if (isPlainObject(current) && isPlainObject(value)) {\n merged[key] = mergeOptions(current, value)\n continue\n }\n if (current !== undefined && !isOptionValue(current)) continue\n\n merged[key] = value\n }\n\n return merged\n}\n\n/**\n * Merges studio plugin options with disk config plugins.\n * Studio takes priority: options from studio win over disk (except values only the disk config\n * can express, see {@link mergeOptions}), and a plugin Studio explicitly\n * disabled is dropped even when the disk config still lists it. Disk plugins without a studio\n * counterpart are kept as-is. Studio plugins not present on disk are appended.\n *\n * For plugins present in both configs, the plugin is re-instantiated with merged options\n * so that all internal closures correctly reference the merged values.\n */\nexport async function mergePlugins(\n diskPlugins: Array<Plugin> | undefined,\n studioPlugins: JSONKubbConfig['plugins'] | undefined,\n): Promise<Array<Plugin> | undefined> {\n // Matched on the package's base name rather than by instantiating first. Every Kubb plugin\n // factory returns exactly that (`@kubb/plugin-ts` → `plugin-ts`), enforced by the `satisfies` on\n // each factory's name.\n const disabledNames = new Set((studioPlugins ?? []).filter((entry) => entry.disabled).map((entry) => toPluginName(entry.name)))\n const activeDiskPlugins = disabledNames.size ? diskPlugins?.filter((plugin) => !disabledNames.has(plugin.name)) : diskPlugins\n const activeStudioPlugins = studioPlugins?.filter((entry) => !entry.disabled)\n\n if (!activeDiskPlugins && !activeStudioPlugins?.length) return undefined\n if (!activeStudioPlugins?.length) return activeDiskPlugins\n\n if (!activeDiskPlugins) return resolvePlugins(activeStudioPlugins)\n\n const studioEntryByName = new Map(activeStudioPlugins.map((entry) => [toPluginName(entry.name), entry] as const))\n const diskNames = new Set(activeDiskPlugins.map((plugin) => plugin.name))\n\n // Each plugin is instantiated once, with its final options. Resolving the whole payload first\n // just to read the names would build every overlapping plugin twice and discard the first.\n const merged = await Promise.all(\n activeDiskPlugins.map(async (diskPlugin) => {\n const studioEntry = studioEntryByName.get(diskPlugin.name)\n if (!studioEntry) return diskPlugin\n\n // Disk as base, studio overrides, then re-instantiate so the plugin's closures reference the\n // merged values. A plugin that never sets `options` (e.g. `@kubb/plugin-barrel`) leaves\n // `diskPlugin.options` undefined.\n const options = mergeOptions((diskPlugin.options as Record<string, unknown>) ?? {}, (studioEntry.options as Record<string, unknown>) ?? {})\n const [resolved] = await resolvePlugins([{ name: studioEntry.name, options }])\n\n return resolved ?? diskPlugin\n }),\n )\n\n const studioOnly = activeStudioPlugins.filter((entry) => !diskNames.has(toPluginName(entry.name)))\n\n return [...merged, ...(await resolvePlugins(studioOnly))]\n}\n\n/**\n * Merges Studio-provided adapter option overrides into the disk config's adapter.\n *\n * Adapter instances carry live functions (`parse`, `getImports`, ...) that can't survive\n * JSON serialization over the WebSocket, so `studioOptions` is treated as an options patch\n * rather than a replacement adapter. Re-invokes the same `@kubb/adapter-<name>` factory the\n * disk config used, with the merged options, so the resulting instance has fresh closures\n * over the merged values instead of a plain object missing `parse`.\n */\nexport async function mergeAdapter(diskAdapter: Adapter | undefined, studioOptions: object | undefined): Promise<Adapter | undefined> {\n if (!studioOptions || !diskAdapter) {\n return diskAdapter\n }\n\n const packageName = `@kubb/adapter-${diskAdapter.name}`\n const mod = await importFromProject(packageName)\n const factory = mod[toExportName(packageName)]\n\n if (typeof factory !== 'function') {\n return diskAdapter\n }\n\n const mergedOptions = mergeOptions((diskAdapter.options as Record<string, unknown>) ?? {}, studioOptions as Record<string, unknown>)\n\n return factory(mergedOptions) as Adapter\n}\n","import { writeFile } from 'node:fs/promises'\nimport { read } from '@internals/utils'\nimport { builders, detectCodeFormat, generateCode, parseModule } from 'magicast'\nimport type { ASTNode, ProxifiedModule } from 'magicast'\nimport type { ConfigEdit, ConfigEditOutcome, ConfigFileView, ConfigRef, ConfigView, OptionValue, PluginView } from './protocol.ts'\nimport { isKubbPluginSpecifier, isOptionValue, toExportName } from './resolveConfig.ts'\n\n/**\n * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,\n * never as source that breaks out of the import statement.\n */\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/\n\n/**\n * A config or plugin options object literal in the file.\n */\ntype ObjectNode = Extract<ASTNode, { type: 'ObjectExpression' }>\n\n/**\n * A `pluginX(...)` call in a config's `plugins` array.\n */\ntype CallNode = Extract<ASTNode, { type: 'CallExpression' }>\n\n/**\n * A `key: value` entry of an object literal.\n */\ntype ObjectPropertyNode = Extract<ASTNode, { type: 'ObjectProperty' }>\n\n/**\n * `key: value` as an object literal property, in the file's quote and key style.\n *\n * Uses magicast's literal builder for the key/value nodes, then wraps them as a Babel\n * `ObjectProperty`, the type the rest of this file reads.\n */\nfunction literalProperty({ key, value }: { key: string; value: OptionValue }): ObjectPropertyNode {\n const built = (builders.literal({ [key]: value }) as unknown as ObjectNode).properties[0] as unknown as ObjectPropertyNode\n return { type: 'ObjectProperty', key: built.key, value: built.value, computed: false, shorthand: false }\n}\n\n/**\n * What `applyConfigEdits` did to a config file.\n */\ntype ApplyResult = {\n /**\n * The file's text after every applicable edit, unchanged from the input when none applied.\n */\n source: string\n /**\n * One entry per edit, in the order they were given.\n */\n outcomes: Array<ConfigEditOutcome>\n /**\n * Whether `source` differs from the input.\n */\n changed: boolean\n}\n\n/**\n * Marks the comment block a `disable-plugin` leaves behind, so `enable-plugin` can find its way\n * back to the exact lines it commented out. Carries the block's line count, so `enable-plugin`\n * restores exactly those lines instead of scanning forward through whatever comments follow.\n */\nconst DISABLED_MARKER = 'kubb:disabled'\n\n/**\n * The plugin and comment-block length a marker line names, when `line` is one.\n */\nfunction parseMarker(line: string): { plugin: string; lineCount: number } | undefined {\n const trimmed = line.trim()\n if (!trimmed.startsWith(`// ${DISABLED_MARKER} `)) {\n return undefined\n }\n\n const match = trimmed.slice(`// ${DISABLED_MARKER} `.length).match(/^(.+)\\s+(\\d+)$/)\n return match ? { plugin: match[1]!, lineCount: Number(match[2]) } : undefined\n}\n\n/**\n * Steps through a config's wrappers to the object literal underneath: a `satisfies`/`as`\n * assertion, a `() => ...` factory, or a factory whose block body returns the config.\n */\nfunction unwrap(node: ASTNode | null | undefined): ASTNode | undefined {\n if (!node) {\n return undefined\n }\n if (node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression') {\n return unwrap(node.expression)\n }\n if (node.type !== 'ArrowFunctionExpression' && node.type !== 'FunctionExpression') {\n return node\n }\n if (node.body.type !== 'BlockStatement') {\n return unwrap(node.body)\n }\n\n const returned = node.body.body.find((statement): statement is Extract<ASTNode, { type: 'ReturnStatement' }> => statement.type === 'ReturnStatement')\n return unwrap(returned?.argument)\n}\n\n/**\n * Every config object in `export default defineConfig(...)`, or why the file is unmanaged.\n *\n * An array export gets one entry per element, matching {@link ConfigRef}'s numeric index.\n *\n * Walks the parsed AST rather than magicast's proxies, which throw on node types they cannot\n * cast, most of what an unmanaged config file is made of.\n */\nfunction findConfigs(mod: ProxifiedModule): { configs: Array<ObjectNode> } | { reason: string } {\n const body = mod.$ast.type === 'Program' ? mod.$ast.body : []\n const declaration = body.find((node): node is Extract<ASTNode, { type: 'ExportDefaultDeclaration' }> => node.type === 'ExportDefaultDeclaration')\n\n const exported = unwrap(declaration?.declaration)\n if (!exported) {\n return { reason: 'no default export found' }\n }\n if (exported.type !== 'CallExpression' || exported.callee.type !== 'Identifier' || exported.callee.name !== 'defineConfig') {\n return { reason: 'default export is not a defineConfig(...) call' }\n }\n\n const argument = unwrap(exported.arguments[0])\n if (!argument) {\n return { reason: 'defineConfig(...) was called without a config' }\n }\n if (argument.type === 'ArrayExpression') {\n const configs: Array<ObjectNode> = []\n\n for (const element of argument.elements) {\n const entry = unwrap(element)\n if (entry?.type !== 'ObjectExpression') {\n return { reason: 'config is not an object literal' }\n }\n configs.push(entry)\n }\n return { configs }\n }\n if (argument.type !== 'ObjectExpression') {\n return { reason: 'config is not an object literal' }\n }\n return { configs: [argument] }\n}\n\n/**\n * The config entry an edit names, defaulting to the first when it names none.\n */\nfunction selectConfig(configs: Array<ObjectNode>, ref: ConfigRef | undefined): ObjectNode | undefined {\n if (ref === undefined) {\n return configs[0]\n }\n if (typeof ref === 'number') {\n return configs[ref]\n }\n return configs.find((config) => configName(config) === ref)\n}\n\nfunction configName(config: ObjectNode): string | undefined {\n const name = property(config, 'name')\n return name?.type === 'StringLiteral' ? name.value : undefined\n}\n\n/**\n * The name of an object literal property, for the two key shapes a config uses: `key: value` and\n * `'key': value`. `undefined` for a computed key, which the patcher never touches.\n */\nfunction propertyKey(entry: Extract<ASTNode, { type: 'ObjectProperty' }>): string | undefined {\n if (entry.key.type === 'Identifier') {\n return entry.key.name\n }\n if (entry.key.type === 'StringLiteral') {\n return entry.key.value\n }\n return undefined\n}\n\n/**\n * The index of an object literal's own property named `key`, `-1` when it has none.\n */\nfunction entryIndex({ node, key }: { node: ObjectNode; key: string }): number {\n return node.properties.findIndex((entry) => entry.type === 'ObjectProperty' && propertyKey(entry) === key)\n}\n\n/**\n * The value node of an object literal's own property.\n */\nfunction property(node: ObjectNode, key: string): ASTNode | undefined {\n const index = entryIndex({ node, key })\n return index === -1 ? undefined : (node.properties[index] as ObjectPropertyNode).value\n}\n\n/**\n * Writes `key: value` on an object literal, replacing the value when the property is already there.\n *\n * An existing property has its value swapped in place rather than being replaced whole, so recast\n * reprints only that value and leaves the object's own layout alone.\n */\nfunction setProperty({ node, key, value }: { node: ObjectNode; key: string; value: OptionValue }): void {\n const entry = literalProperty({ key, value })\n const index = entryIndex({ node, key })\n\n if (index === -1) {\n node.properties.push(entry)\n return\n }\n ;(node.properties[index] as ObjectPropertyNode).value = entry.value\n}\n\n/**\n * Drops `key` from an object literal.\n */\nfunction removeProperty({ node, key }: { node: ObjectNode; key: string }): void {\n const index = entryIndex({ node, key })\n if (index !== -1) {\n node.properties.splice(index, 1)\n }\n}\n\n/**\n * Reads a literal node's value: a primitive, or an object/array built only from primitives.\n * `undefined` for anything else, so a caller can use this both to read a value and to check\n * whether a node is a literal at all.\n */\nfunction readLiteral(node: ASTNode | undefined): OptionValue | undefined {\n if (!node) {\n return undefined\n }\n if (node.type === 'StringLiteral' || node.type === 'NumericLiteral' || node.type === 'BooleanLiteral') {\n return node.value\n }\n if (node.type === 'NullLiteral') {\n return null\n }\n if (node.type === 'TemplateLiteral') {\n return node.expressions.length === 0 ? (node.quasis[0]?.value.cooked ?? '') : undefined\n }\n if (node.type === 'UnaryExpression') {\n const value = readLiteral(node.argument)\n if (typeof value !== 'number') {\n return undefined\n }\n if (node.operator === '-') {\n return -value\n }\n if (node.operator === '+') {\n return value\n }\n return undefined\n }\n if (node.type === 'ArrayExpression') {\n const values = node.elements.map((element) => (element ? readLiteral(element) : undefined))\n return values.every((value) => value !== undefined) ? values : undefined\n }\n if (node.type === 'ObjectExpression') {\n const entries: Record<string, OptionValue> = {}\n for (const entry of node.properties) {\n if (entry.type !== 'ObjectProperty') {\n return undefined\n }\n const key = propertyKey(entry)\n const value = readLiteral(entry.value)\n if (key === undefined || value === undefined) {\n return undefined\n }\n entries[key] = value\n }\n return entries\n }\n return undefined\n}\n\n/**\n * Maps a factory identifier in the file back to the module it was imported from.\n */\nfunction importedFrom(mod: ProxifiedModule): Map<string, string> {\n return new Map(mod.imports.$items.map((item) => [item.local, item.from]))\n}\n\n/**\n * Every `pluginX(...)` element of a config's plugins array that resolves to an import.\n */\nfunction pluginCalls(mod: ProxifiedModule, config: ObjectNode): Array<{ importName: string; packageName: string; call: CallNode }> {\n const plugins = property(config, 'plugins')\n if (plugins?.type !== 'ArrayExpression') {\n return []\n }\n\n const imports = importedFrom(mod)\n\n return plugins.elements.flatMap((element) => {\n if (element?.type !== 'CallExpression' || element.callee.type !== 'Identifier') {\n return []\n }\n const packageName = imports.get(element.callee.name)\n return packageName ? [{ importName: element.callee.name, packageName, call: element }] : []\n })\n}\n\n/**\n * Plugins a previous `disable-plugin` commented out of this config, keyed by package name.\n *\n * Read from the marker lines rather than the AST, since a commented-out call is no longer a node.\n */\nfunction disabledMarkers(source: string): Array<{ packageName: string; line: number }> {\n return source.split('\\n').flatMap((line, index) => {\n const marker = parseMarker(line)\n return marker ? [{ packageName: marker.plugin, line: index + 1 }] : []\n })\n}\n\n/**\n * Reads which plugins the file declares and which of their options Studio may write.\n *\n * @example\n * ```ts\n * const view = readConfig(await readFile('kubb.config.ts', 'utf8'))\n * if (view.managed) {\n * view.configs.forEach((config) => console.log(config.name, config.plugins.length))\n * }\n * ```\n */\nexport function readConfig(source: string): ConfigFileView {\n const parsed = parseConfigs(source)\n if ('reason' in parsed) {\n return { managed: false, reason: parsed.reason }\n }\n\n const { mod, configs } = parsed\n const importNames = new Map([...importedFrom(mod)].map(([local, from]) => [from, local]))\n const disabled = disabledMarkers(source)\n\n return {\n managed: true,\n configs: configs.map((config): ConfigView => {\n const plugins = pluginCalls(mod, config).map(({ importName, packageName, call }): PluginView => {\n const entries: PluginView['options'] = {}\n const options = call.arguments[0]\n\n if (options?.type === 'ObjectExpression') {\n for (const entry of options.properties) {\n if (entry.type !== 'ObjectProperty') {\n continue\n }\n const key = propertyKey(entry)\n if (key === undefined) {\n continue\n }\n const value = readLiteral(entry.value)\n entries[key] = value === undefined ? { literal: false } : { literal: true, value }\n }\n }\n return { importName, packageName, options: entries }\n })\n\n const start = config.loc?.start.line ?? 0\n const end = config.loc?.end.line ?? Number.POSITIVE_INFINITY\n\n for (const { packageName } of disabled.filter((entry) => entry.line >= start && entry.line <= end)) {\n plugins.push({\n importName: importNames.get(packageName) ?? toExportName(packageName),\n packageName,\n options: {},\n disabled: true,\n })\n }\n\n return { name: configName(config), plugins }\n }),\n }\n}\n\n/**\n * The options object of a plugin call, when it was called with one.\n */\nfunction getOptions(call: CallNode): ObjectNode | undefined {\n const options = call.arguments[0]\n return options?.type === 'ObjectExpression' ? options : undefined\n}\n\n/**\n * The options object of a plugin call, creating an empty one when the plugin was called bare.\n */\nfunction ensureOptions(call: CallNode): ObjectNode | undefined {\n if (call.arguments.length === 0) {\n call.arguments.push({ type: 'ObjectExpression', properties: [] })\n }\n return getOptions(call)\n}\n\n/**\n * Walks `path` down to the object holding its last key, descending only through object literals.\n */\nfunction optionParent(options: ObjectNode, path: Array<string>): { object: ObjectNode; key: string } | { reason: string } {\n let object = options\n\n for (const [index, key] of path.entries()) {\n if (index === path.length - 1) {\n return { object, key }\n }\n\n if (property(object, key) === undefined) {\n setProperty({ node: object, key, value: {} })\n }\n\n const next = property(object, key)\n if (next?.type !== 'ObjectExpression') {\n return { reason: `${key} is not an object, so ${path.join('.')} cannot be reached` }\n }\n object = next\n }\n return { reason: 'no option path given' }\n}\n\n/**\n * Writes `value` at `path` inside a plugin call's options, creating the options object and any\n * intermediate object along the path as needed. Refuses when the current value at `path` is\n * something other than a literal, so an option customized in code is never overwritten.\n */\nfunction applySet(call: CallNode, path: Array<string>, value: unknown): string | undefined {\n if (!isOptionValue(value)) {\n return 'the value is not a literal that can be written to a config file'\n }\n\n const options = ensureOptions(call)\n if (!options) {\n return 'the plugin was not called with an object literal'\n }\n\n const target = optionParent(options, path)\n if ('reason' in target) {\n return target.reason\n }\n\n const current = property(target.object, target.key)\n if (current !== undefined && readLiteral(current) === undefined) {\n return `${path.join('.')} is customized in code`\n }\n\n setProperty({ node: target.object, key: target.key, value })\n return undefined\n}\n\n/**\n * Deletes the property at `path` inside a plugin call's options, falling the plugin back to its\n * default for that option. Refuses when the value at `path` is not a literal, for the same reason\n * `applySet` does.\n */\nfunction applyRemove(call: CallNode, path: Array<string>): string | undefined {\n const options = getOptions(call)\n if (!options) {\n return 'the plugin has no options to remove'\n }\n\n const target = optionParent(options, path)\n if ('reason' in target) {\n return target.reason\n }\n\n const current = property(target.object, target.key)\n if (current === undefined) {\n return `${path.join('.')} is not set`\n }\n if (readLiteral(current) === undefined) {\n return `${path.join('.')} is customized in code`\n }\n\n removeProperty({ node: target.object, key: target.key })\n return undefined\n}\n\n/**\n * Outcome of `applyAddPlugin`. `addImport` is set when the new plugin call needs an import line\n * the caller must still insert; absent when the import was already there.\n */\ntype AddPluginResult = { reason: string } | { noop: true } | { addImport?: { importName: string; moduleSpecifier: string } }\n\n/**\n * Adds a `pluginX(...)` call to a config's plugins array. Replaying the same add is a no-op, while\n * an import name collision with an unrelated package remains an error.\n */\nfunction applyAddPlugin(mod: ProxifiedModule, config: ObjectNode, edit: Extract<ConfigEdit, { operation: 'add-plugin' }>): AddPluginResult {\n if (!isKubbPluginSpecifier(edit.plugin)) {\n return { reason: `\"${edit.plugin}\" is not a @kubb/plugin-* package` }\n }\n\n const importName = edit.importName ?? toExportName(edit.plugin)\n if (!IDENTIFIER.test(importName)) {\n return { reason: `\"${importName}\" is not a valid import name` }\n }\n\n if (pluginCalls(mod, config).some((plugin) => plugin.packageName === edit.plugin)) {\n return { noop: true }\n }\n\n const taken = importedFrom(mod).get(importName)\n if (taken && taken !== edit.plugin) {\n return { reason: `${importName} is already imported from ${taken}` }\n }\n\n const options = edit.options ?? {}\n if (!isOptionValue(options)) {\n return { reason: 'the options are not literals that can be written to a config file' }\n }\n\n const plugins = property(config, 'plugins')\n if (plugins?.type !== 'ArrayExpression') {\n return { reason: 'plugins is not an array literal' }\n }\n\n const call = Object.keys(options).length ? builders.functionCall(importName, options) : builders.functionCall(importName)\n plugins.elements.push(call.$ast as CallNode)\n\n return taken ? {} : { addImport: { importName, moduleSpecifier: edit.plugin } }\n}\n\n/**\n * Comments out a plugin call in place, keeping its options on disk so `enable-plugin` can restore\n * them exactly. Operates on `source` text rather than the AST: a commented-out call is no longer a\n * node magicast can address, and the surrounding array must not reflow when its element count\n * never actually changes.\n */\nfunction disablePlugin(source: string, mod: ProxifiedModule, config: ObjectNode, plugin: string): { source: string } | { reason: string } {\n const target = pluginCalls(mod, config).find((entry) => entry.packageName === plugin)\n if (!target) {\n return { reason: `${plugin} is not in the plugins array` }\n }\n\n const loc = target.call.loc\n if (!loc?.start || !loc.end) {\n return { reason: `${plugin} has no source location to comment out` }\n }\n\n const lines = source.split('\\n')\n const from = loc.start.line - 1\n const to = loc.end.line - 1\n const firstLine = lines[from] ?? ''\n const lastLine = lines[to] ?? ''\n\n // Only safe to comment out when the call sits alone on its lines: anything else sharing the\n // first line before it, or the last line after it besides a trailing comma, would be swallowed\n // into the comment along with the call, corrupting the file.\n if (firstLine.slice(0, loc.start.column).trim() !== '' || !/^,?\\s*$/.test(lastLine.slice(loc.end.column))) {\n return { reason: `${plugin} shares a line with other code, so it cannot be commented out safely` }\n }\n\n const indent = firstLine.match(/^\\s*/)?.[0] ?? ''\n const commented = lines.slice(from, to + 1).map((line) => (line.trim() ? `${indent}// ${line.slice(indent.length)}` : indent ? `${indent}//` : '//'))\n lines.splice(from, to - from + 1, `${indent}// ${DISABLED_MARKER} ${plugin} ${commented.length}`, ...commented)\n\n return { source: lines.join('\\n') }\n}\n\n/**\n * Uncomments the block a previous `disable-plugin` left behind for `plugin`.\n */\nfunction enablePlugin(source: string, plugin: string): { source: string } | { reason: string } {\n const lines = source.split('\\n')\n\n for (const [index, line] of lines.entries()) {\n const marker = parseMarker(line)\n if (marker?.plugin !== plugin) {\n continue\n }\n\n // Bounded by the marker's own line count rather than scanning for trailing `//` lines, so a\n // comment or another disabled block right after this one is left untouched.\n const end = index + 1 + marker.lineCount\n const restored = lines.slice(index + 1, end).map((commented) => commented.replace(/^(\\s*)\\/\\/ ?/, '$1'))\n lines.splice(index, end - index, ...restored)\n\n return { source: lines.join('\\n') }\n }\n\n return { reason: `${plugin} is not disabled` }\n}\n\n/**\n * Parses `source` and finds the config entries it exports.\n */\nfunction parseConfigs(source: string): { mod: ProxifiedModule; configs: Array<ObjectNode> } | { reason: string } {\n let mod: ProxifiedModule\n try {\n mod = parseModule(source)\n } catch {\n return { reason: 'the config file could not be parsed' }\n }\n\n const found = findConfigs(mod)\n return 'reason' in found ? found : { mod, configs: found.configs }\n}\n\n/**\n * Re-parses `source` and resolves the config entry an edit targets. Every edit re-parses rather\n * than sharing one module across the batch, since the disable/enable edits rewrite `source` as\n * text and would otherwise leave the others working from a stale tree.\n */\nfunction parseTarget(source: string, ref: ConfigRef | undefined): { mod: ProxifiedModule; config: ObjectNode } | { reason: string } {\n const parsed = parseConfigs(source)\n if ('reason' in parsed) {\n return parsed\n }\n\n const config = selectConfig(parsed.configs, ref)\n if (!config) {\n return { reason: `no config entry found for ${JSON.stringify(ref)}` }\n }\n\n return { mod: parsed.mod, config }\n}\n\n/**\n * Applies edits to a `kubb.config.ts` in place. Every node the edits do not touch keeps its\n * original text, so comments, formatting, and hand-written code around the config survive.\n *\n * Edits are independent: one that cannot be applied is reported in `outcomes` and the rest still run.\n *\n * @example\n * ```ts\n * const { source, outcomes } = applyConfigEdits(current, [\n * { operation: 'set', plugin: '@kubb/plugin-ts', path: ['enum', 'type'], value: 'enum' },\n * ])\n * ```\n *\n * @note recast always reprints a semicolon on a reprinted statement, so editing a block-body\n * `defineConfig` in a semicolon-free file adds one to the `return` line. This is a known gap.\n * Strip it when `detectCodeFormat` reports `useSemi: false`, if it turns out to matter in practice.\n */\nexport function applyConfigEdits(source: string, edits: Array<ConfigEdit>): ApplyResult {\n let current = source\n const format = detectCodeFormat(source)\n const endsWithNewline = source.endsWith('\\n')\n\n const outcomes = edits.map((edit): ConfigEditOutcome => {\n const target = parseTarget(current, edit.config)\n if ('reason' in target) {\n return { edit, applied: false, reason: target.reason }\n }\n const { mod, config } = target\n\n if (edit.operation === 'disable-plugin' || edit.operation === 'enable-plugin') {\n const result = edit.operation === 'disable-plugin' ? disablePlugin(current, mod, config, edit.plugin) : enablePlugin(current, edit.plugin)\n if ('reason' in result) {\n return { edit, applied: false, reason: result.reason }\n }\n current = result.source\n return { edit, applied: true }\n }\n\n if (edit.operation === 'add-plugin') {\n const result = applyAddPlugin(mod, config, edit)\n if ('reason' in result) {\n return { edit, applied: false, reason: result.reason }\n }\n if ('noop' in result) {\n return { edit, applied: true }\n }\n const afterLine = lastImportEndLine(mod)\n let next = generateCode(mod, { format }).code\n if (result.addImport) {\n next = insertImportLine({ source: next, afterLine, ...result.addImport })\n }\n current = withTrailingNewline(next, endsWithNewline)\n return { edit, applied: true }\n }\n\n const pluginCall = pluginCalls(mod, config).find((plugin) => plugin.packageName === edit.plugin)\n if (!pluginCall) {\n return { edit, applied: false, reason: `${edit.plugin} is not in the plugins array` }\n }\n\n const reason = edit.operation === 'set' ? applySet(pluginCall.call, edit.path, edit.value) : applyRemove(pluginCall.call, edit.path)\n if (!reason) {\n current = withTrailingNewline(generateCode(mod, { format }).code, endsWithNewline)\n }\n return { edit, applied: !reason, reason }\n })\n\n return { source: current, outcomes, changed: current !== source }\n}\n\nexport async function writeConfigEdits({ filePath, edits }: { filePath: string; edits: Array<ConfigEdit> }): Promise<ApplyResult> {\n const current = await read(filePath)\n const result = applyConfigEdits(current, edits)\n if (result.changed) await writeFile(filePath, result.source, 'utf-8')\n return result\n}\n\n/**\n * The 1-based line where the file's last import declaration ends, or `0` when it has none. Read\n * off the parsed module, so a multi-line `import {\\n x,\\n} from '...'` reports its closing line\n * rather than the `import` keyword.\n */\nfunction lastImportEndLine(mod: ProxifiedModule): number {\n const body = mod.$ast.type === 'Program' ? mod.$ast.body : []\n\n return body.filter((node) => node.type === 'ImportDeclaration').at(-1)?.loc?.end.line ?? 0\n}\n\n/**\n * Writes an import after the last one already in the file, matching its quote style and whether it\n * ends in a semicolon. `afterLine` is where that last import ends, `0` for a file with none.\n *\n * Written as plain text rather than through magicast's import builder, which prints a brand-new\n * import declaration with its own default spacing and a semicolon regardless of `format`, since\n * that formatting only governs nodes recast can diff against the original source.\n */\nfunction insertImportLine({\n source,\n importName,\n moduleSpecifier,\n afterLine,\n}: {\n source: string\n importName: string\n moduleSpecifier: string\n afterLine: number\n}): string {\n const lines = source.split('\\n')\n\n const lastImportLine = afterLine > 0 ? lines[afterLine - 1] : undefined\n const quote = lastImportLine?.includes(`\"`) ? `\"` : `'`\n const semicolon = lastImportLine?.trimEnd().endsWith(';') ? ';' : ''\n const line = `import { ${importName} } from ${quote}${moduleSpecifier}${quote}${semicolon}`\n\n lines.splice(afterLine, 0, ...(afterLine > 0 ? [line] : [line, '']))\n\n return lines.join('\\n')\n}\n\n/**\n * `generateCode` always drops the file's trailing newline. Restore it when the input had one.\n */\nfunction withTrailingNewline(code: string, hadTrailingNewline: boolean): string {\n if (!hadTrailingNewline || code.endsWith('\\n')) {\n return code\n }\n return `${code}\\n`\n}\n","import { createHash } from 'node:crypto'\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\nimport process from 'node:process'\nimport { inParallel } from '@internals/utils'\nimport { type Config, createKubb, type Diagnostic, Diagnostics, fsStorage, type Hookable, type KubbHooks, type Storage } from '@kubb/core'\nimport type { FilePage, FileSource, ReadFilesResult } from './protocol.ts'\n\nconst READ_CONCURRENCY = 50\nconst MB = 1024 * 1024\nconst INDEX_KEY = 'studio/generations.json'\n\n/**\n * Files a run produced, or the output directory held, keyed by path relative to `root`.\n */\nexport type SourceFiles = { storage: Storage; root: string; paths: Set<string> }\n\n/**\n * The path form {@link SourceFiles} keys on: relative to `root`, with forward slashes.\n */\nexport function relativeStoragePath({ root, filePath }: { root: string; filePath: string }): string {\n return (isAbsolute(filePath) ? relative(resolve(root), filePath) : filePath).replaceAll('\\\\', '/')\n}\n\n/**\n * A set as kept in the store.\n */\ntype KeptSet = {\n /**\n * The paths a read is checked against. Empty when the set was too large to keep its content.\n */\n paths: Array<string>\n hashes: Record<string, string>\n bytes: number\n}\n\ntype KeptGeneration = {\n jobId: string\n /** When the store took it, in epoch milliseconds. Absent on an index written before it existed. */\n keptAt?: number\n output: KeptSet\n disk?: KeptSet\n}\n\n/**\n * The content fingerprint Studio compares snapshots by. Agent runs and CI uploads must agree on it.\n */\nexport const hashOf = (content: string) => createHash('sha1').update(content).digest('hex').slice(0, 16)\n\nconst totalBytes = (entries: Array<KeptGeneration>) => entries.reduce((sum, { output, disk }) => sum + output.bytes + (disk?.bytes ?? 0), 0)\n\nfunction positiveNumber(value: string | undefined): number | undefined {\n const parsed = Number(value)\n return value && Number.isFinite(parsed) && parsed > 0 ? parsed : undefined\n}\n\n/**\n * How many generations an agent keeps and how large they may get, read from\n * `KUBB_AGENT_MAX_GENERATIONS`, `KUBB_AGENT_MAX_GENERATIONS_MB` and `KUBB_AGENT_MAX_SNAPSHOT_MB`.\n * An unset or invalid value keeps the default.\n */\nexport function resolveGenerationLimits(): { maxCount: number; maxMb: number; maxSnapshotMb: number } {\n return {\n maxCount: Math.max(1, Math.floor(positiveNumber(process.env.KUBB_AGENT_MAX_GENERATIONS) ?? 8)),\n maxMb: positiveNumber(process.env.KUBB_AGENT_MAX_GENERATIONS_MB) ?? 100,\n maxSnapshotMb: positiveNumber(process.env.KUBB_AGENT_MAX_SNAPSHOT_MB) ?? 50,\n }\n}\n\n/**\n * Folds error-severity diagnostics into one thrown error so logs name the failing plugin or pass.\n */\nfunction generationFailure(diagnostics: ReadonlyArray<Diagnostic>): Error {\n const reasons = diagnostics\n .filter(Diagnostics.isProblem)\n .filter((diagnostic) => diagnostic.severity === 'error')\n .map((diagnostic) => (diagnostic.plugin ? `${diagnostic.plugin}: ${diagnostic.message}` : diagnostic.message))\n\n if (!reasons.length) return new Error('Generation failed')\n\n return new Error(`Generation failed: ${reasons.length} error${reasons.length === 1 ? '' : 's'}: ${reasons.join('; ')}`)\n}\n\n/**\n * Runs one generation and returns the files it produced. The formatter, the linter, and\n * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.\n */\nexport async function generate({\n config,\n hooks,\n signal,\n allowExec,\n}: {\n config: Config\n hooks?: Hookable<KubbHooks>\n signal?: AbortSignal\n allowExec: boolean\n}): Promise<SourceFiles> {\n const output = allowExec ? config.output : { ...config.output, format: false as const, lint: false as const, postGenerate: [] }\n const kubb = createKubb({ ...config, output }, { hooks, signal })\n const result = await kubb.generate()\n if (!result.success) throw generationFailure(result.diagnostics)\n\n // `kubb.config` carries the defaults, such as the fs storage a config loaded by the CLI leaves unset.\n const { storage, root } = kubb.config\n return {\n storage,\n root,\n paths: new Set(result.files.map((file) => relativeStoragePath({ root, filePath: file.path }))),\n }\n}\n\n/**\n * What the output directory holds on disk before a run. `undefined` when `outputPath` is not a real\n * subdirectory of `root` (listing the root would take in every source file) or holds more than `maxFiles`.\n */\nexport async function listDisk({ root, outputPath, maxFiles }: { root: string; outputPath: string; maxFiles: number }): Promise<SourceFiles | undefined> {\n const outputDir = resolve(root, outputPath)\n const fromRoot = relative(resolve(root), outputDir)\n if (!fromRoot || fromRoot.startsWith('..') || fromRoot.startsWith(sep)) return undefined\n\n const storage = fsStorage()\n const keys = await storage.readKeys(outputDir)\n if (keys.length > maxFiles) return undefined\n\n const paths = keys\n .filter((key) => !key.split('/').includes('node_modules'))\n .map((key) => relative(resolve(root), resolve(outputDir, key)).replaceAll('\\\\', '/'))\n return { storage, root, paths: new Set(paths) }\n}\n\n/**\n * Keeps recent generations by job id in `storage`, with an index next to them so a store on disk\n * survives a restart. A generation is only ever looked up by its job id, so on a pooled sandbox one\n * tenant never reaches another's output. The oldest go past `maxCount` or `maxMb`, but the newest\n * always stays.\n */\nexport function createGenerationStore({\n storage,\n maxCount,\n maxMb,\n ttlMs,\n now = Date.now,\n}: {\n storage: Storage\n maxCount: number\n maxMb: number\n /** How long a generation stays readable. Unset, it stays until count or size pushes it out. */\n ttlMs?: number\n now?: () => number\n}) {\n let index: Array<KeptGeneration> | undefined\n\n // An entry from before `keptAt` existed never expires, so upgrading drops nothing.\n const isLive = (generation: KeptGeneration) => ttlMs === undefined || generation.keptAt === undefined || now() - generation.keptAt < ttlMs\n\n // Hashed so a job id from the wire can never point outside the store.\n const dirOf = (jobId: string) => `studio/generations/${hashOf(jobId)}/`\n\n async function load(): Promise<Array<KeptGeneration>> {\n if (index) return index\n const stored = await storage.readItem(INDEX_KEY).catch(() => null)\n try {\n index = stored ? (JSON.parse(stored) as Array<KeptGeneration>) : []\n } catch {\n index = []\n }\n return index\n }\n\n /**\n * Copies `files` into the store as one set of `jobId`. Above `maxSetMb` only the hashes are kept.\n */\n async function keep({ jobId, source, files, maxSetMb }: { jobId: string; source: FileSource; files: SourceFiles; maxSetMb: number }): Promise<KeptSet> {\n const maxSetBytes = maxSetMb * MB\n const hashes: Record<string, string> = {}\n let bytes = 0\n await inParallel({\n items: [...files.paths],\n limit: READ_CONCURRENCY,\n run: async (path) => {\n // Output outside the root would land outside the store too.\n if (path.split('/').includes('..')) return\n const content = await files.storage.readItem(resolve(files.root, path))\n if (content === null) return\n hashes[path] = hashOf(content)\n bytes += Buffer.byteLength(content)\n if (bytes <= maxSetBytes) await storage.writeItem(`${dirOf(jobId)}${source}/${path}`, content)\n },\n })\n if (bytes > maxSetBytes) {\n await storage.empty(`${dirOf(jobId)}${source}/`)\n return { paths: [], hashes, bytes: 0 }\n }\n return { paths: Object.keys(hashes), hashes, bytes }\n }\n\n async function drop(jobId: string): Promise<void> {\n await storage.empty(dirOf(jobId))\n }\n\n return {\n keep,\n drop,\n get: async (jobId: string) => (await load()).find((generation) => generation.jobId === jobId && isLive(generation)),\n async add(generation: KeptGeneration): Promise<void> {\n const current = await load()\n for (const expired of current.filter((entry) => !isLive(entry))) await drop(expired.jobId)\n const entries = current.filter((entry) => entry.jobId !== generation.jobId && isLive(entry))\n entries.push({ ...generation, keptAt: now() })\n while (entries.length > 1 && (entries.length > maxCount || totalBytes(entries) > maxMb * MB)) {\n await drop(entries.shift()!.jobId)\n }\n index = entries\n await storage.writeItem(INDEX_KEY, JSON.stringify(entries))\n },\n /**\n * Reads the requested paths the set holds, skipping any it does not, one page of lines when `limit` is given.\n */\n async read({\n generation,\n source,\n paths,\n cursor = 0,\n limit,\n }: {\n generation: KeptGeneration\n source: FileSource\n paths: Array<string>\n cursor?: number\n limit?: number\n }): Promise<ReadFilesResult> {\n const kept = new Set(generation[source]?.paths)\n const files: Record<string, string> = {}\n const pages: Record<string, FilePage> = {}\n await inParallel({\n items: paths.filter((path) => kept.has(path)),\n limit: READ_CONCURRENCY,\n run: async (path) => {\n const content = await storage.readItem(`${dirOf(generation.jobId)}${source}/${path}`)\n if (content === null) return\n if (limit === undefined) {\n files[path] = content\n return\n }\n const lines = content.split(/\\r\\n|\\r|\\n/)\n const end = Math.min(cursor + limit, lines.length)\n files[path] = lines.slice(cursor, end).join('\\n')\n pages[path] = { nextCursor: end < lines.length ? end : null, totalLines: lines.length }\n },\n })\n return limit === undefined ? { files } : { files, pages }\n },\n }\n}\n\nexport type GenerationStore = ReturnType<typeof createGenerationStore>\n","import { stripVTControlCharacters } from 'node:util'\nimport { getElapsedMs } from '@internals/utils'\nimport { Diagnostics, type Hookable, type KubbHooks } from '@kubb/core'\nimport { type GenerationEvent, type GenerationEventPayloads, type GenerationEventType, generationEventTypes } from './protocol.ts'\nimport { relativeStoragePath } from './generations.ts'\n\n/** How each published hook's context becomes its wire payload; a hook without a projection fails to compile. */\ntype Projections = { [Type in GenerationEventType]: (...args: KubbHooks[Type]) => GenerationEventPayloads[Type] }\n\nconst MAX_QUEUED_EVENTS = 1_024\nconst RESERVED_EVENTS = 64\nconst isDiscardable = (event: GenerationEvent) => event.type === 'kubb:files:processing:update' || event.type === 'kubb:info' || event.type === 'kubb:success'\n\n/** Forwards selected Kubb lifecycle events to a native Cap'n Web stream. */\nexport function createGenerationStream(\n hooks: Hookable<KubbHooks>,\n jobId: string,\n): { stream: ReadableStream<GenerationEvent>; close: () => Promise<void>; dispose: () => void; fail: (error: unknown) => void } {\n const unhooks: Array<() => void> = []\n let root = ''\n let controller!: ReadableStreamDefaultController<GenerationEvent>\n let closed = false\n const stream = new ReadableStream<GenerationEvent>(\n {\n start: (value) => {\n controller = value\n },\n cancel: () => {\n closed = true\n detach()\n },\n },\n { highWaterMark: MAX_QUEUED_EVENTS },\n )\n\n /**\n * Registers a listener and keeps its remover, so one generation's listeners come off the session\n * emitter again when that generation ends.\n */\n function on<TName extends keyof KubbHooks & string>(name: TName, handler: (...args: KubbHooks[TName]) => unknown): void {\n unhooks.push(hooks.hook(name, handler))\n }\n\n function emitEvent<Type extends GenerationEventType>(type: Type, data: GenerationEventPayloads[Type]): void {\n if (closed) return\n const event = { jobId, type, data, version: 1 as const, timestamp: Date.now() } as unknown as GenerationEvent\n if (controller.desiredSize! <= RESERVED_EVENTS && isDiscardable(event)) return\n if (controller.desiredSize! <= 0) {\n fail(new Error(`Generation event stream exceeded ${MAX_QUEUED_EVENTS} queued events`))\n return\n }\n controller.enqueue(event)\n }\n\n const projections: Projections = {\n 'kubb:plugin:start': ({ plugin }) => [{ plugin: { name: plugin.name } }],\n 'kubb:plugin:end': ({ plugin, duration, success }) => [{ plugin: { name: plugin.name }, duration, success }],\n 'kubb:build:start': ({ config, adapter }) => [{ config: { name: config.name }, adapter: { name: adapter.name } }],\n 'kubb:build:end': ({ files, config, outputDir }) => [\n { files: files.map((file) => ({ path: relativeStoragePath({ root: config.root, filePath: file.path }), name: file.name })), outputDir },\n ],\n 'kubb:files:processing:start': ({ files }) => [{ total: files.length }],\n 'kubb:files:processing:update': ({ files }) => [\n {\n files: files.map(({ file, processed, total, percentage }) => ({\n file: relativeStoragePath({ root, filePath: file.path }),\n processed,\n total,\n percentage,\n })),\n },\n ],\n 'kubb:files:processing:end': ({ files }) => [{ total: files.length }],\n 'kubb:info': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:success': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:warn': ({ message, info }) => [{ message: stripVTControlCharacters(message), info }],\n 'kubb:error': ({ error }) => [{ message: error.message, stack: error.stack }],\n 'kubb:diagnostic': ({ diagnostic }) => [\n {\n code: diagnostic.code,\n message: diagnostic.message,\n severity: diagnostic.severity,\n location: 'location' in diagnostic ? diagnostic.location : undefined,\n help: 'help' in diagnostic ? diagnostic.help : undefined,\n plugin: 'plugin' in diagnostic ? diagnostic.plugin : undefined,\n stack: 'cause' in diagnostic ? diagnostic.cause?.stack : undefined,\n },\n ],\n 'kubb:generation:start': ({ config }) => [{ name: config.name, plugins: config.plugins.length }],\n 'kubb:generation:end': () => [],\n 'kubb:generation:summary': ({ duration, fileCount, failedPlugins, status }) => [{ duration, fileCount, failedPlugins, status }],\n 'kubb:lifecycle:start': () => [],\n 'kubb:lifecycle:end': () => [],\n 'kubb:format:start': () => [],\n 'kubb:format:end': () => [],\n 'kubb:lint:start': () => [],\n 'kubb:lint:end': () => [],\n 'kubb:hooks:start': () => [],\n 'kubb:hooks:end': () => [],\n 'kubb:hook:start': ({ id, command, args }) => [{ id, command, args: args ? [...args] : undefined }],\n 'kubb:hook:line': ({ id, line }) => [{ id, line }],\n 'kubb:hook:end': ({ id, command, args, success, error }) => [\n { id, command, args: args ? [...args] : undefined, success, error: error ? { message: error.message, stack: error.stack } : undefined },\n ],\n }\n\n function forward<Type extends GenerationEventType>(type: Type): void {\n on(type, (...args: KubbHooks[Type]) => emitEvent(type, projections[type](...args)))\n }\n\n // Paths in `kubb:files:processing:update` are made relative to the root the build announced.\n on('kubb:build:start', ({ config }) => {\n root = config.root\n })\n\n for (const type of generationEventTypes) forward(type)\n\n // Registered after the loop so the summary follows its `kubb:generation:end`; core never emits it.\n on('kubb:generation:end', ({ diagnostics = [], status, hrStart, filesCreated }) => {\n if (!hrStart) {\n return\n }\n\n const duration = Math.round(getElapsedMs(hrStart))\n\n emitEvent('kubb:generation:summary', [\n { duration, fileCount: filesCreated ?? 0, failedPlugins: Diagnostics.failedPlugins(diagnostics).length, status: status ?? 'success' },\n ])\n })\n\n /**\n * Takes this generation's listeners off the session emitter. Safe to call twice.\n */\n function detach(): void {\n for (const unhook of unhooks) unhook()\n unhooks.length = 0\n }\n\n async function close(): Promise<void> {\n if (closed) {\n return\n }\n closed = true\n detach()\n controller.close()\n }\n\n function fail(error?: unknown): void {\n detach()\n if (closed) {\n return\n }\n closed = true\n controller.error(error)\n }\n\n return { stream, close, dispose: () => fail(), fail }\n}\n","/**\n * Hosted Kubb Studio URL, used when a host passes none.\n */\nexport const defaultStudioUrl = 'https://kubb.studio'\n\n// `URL` keeps IPv6 brackets, so `::1` is `[::1]`.\nfunction isLoopbackHost(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]'\n}\n\n/**\n * Appends `path` to the Studio URL and refuses plaintext to anything but this machine, so a token\n * or API key never crosses the network unencrypted. `socket` switches the scheme to `ws:`/`wss:`.\n *\n * @example\n * ```ts\n * secureUrl({ studioUrl: 'https://kubb.studio', path: '/api/agent/socket', socket: true }).href // 'wss://kubb.studio/api/agent/socket'\n * ```\n */\nexport function secureUrl({ studioUrl, path, socket = false }: { studioUrl: string; path: string; socket?: boolean }): URL {\n const url = new URL(`${studioUrl.replace(/\\/+$/, '')}${path}`)\n\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) {\n throw new Error(`Refusing to reach Kubb Studio at ${url.origin}: use an https:// URL, or a loopback host for local development`)\n }\n if (socket) url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n\n return url\n}\n","import { randomUUID } from 'node:crypto'\nimport { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { getErrorMessage, read, toError } from '@internals/utils'\nimport { cacheStorage, type Config, fsStorage, Hookable, type KubbHooks, memoryStorage, resolveCacheDir } from '@kubb/core'\nimport { newWebSocketRpcSession, RpcTarget } from 'capnweb'\nimport { version as kubbVersion } from '../package.json'\nimport { readConfig, writeConfigEdits } from './configFile.ts'\nimport { createGenerationStream } from './generationEvents.ts'\nimport { createGenerationStore, generate, type GenerationStore, listDisk, resolveGenerationLimits } from './generations.ts'\nimport {\n AGENT_INSTANCE_HEADER,\n AGENT_SOCKET_PATH,\n type AgentApi,\n AgentCloseCode,\n type AgentConnectInfo,\n type AgentPermissions,\n type ConfigFileView,\n type ConnectMessagePayload,\n type GenerateInput,\n type GenerateResult,\n type GenerationEvent,\n type GenerationRun,\n GENERATION_GONE_MESSAGE,\n MAX_FILES_PER_REQUEST,\n MAX_PAGE_LINES,\n type ReadFilesInput,\n type ReadFilesResult,\n type SaveConfigInput,\n type SaveResult,\n type StudioApi,\n} from './protocol.ts'\nimport { mergeAdapter, mergePlugins, toPackageName } from './resolveConfig.ts'\nimport { defaultStudioUrl, secureUrl } from './url.ts'\n\nconst HEARTBEAT_INTERVAL_MS = 30_000\n// Studio marks an agent offline after its liveness window, so a slower cadence would look dead.\nconst MAX_HEARTBEAT_INTERVAL_MS = 60_000\nconst PING_TIMEOUT_MS = 10_000\nconst OPEN_TIMEOUT_MS = 5_000\nconst MAX_RETRY_DELAY_MS = 30_000\nconst DISK_SNAPSHOT_MAX_FILES = 10_000\n// A sandbox shares one in-memory store across tenants, so old generations expire.\nconst SANDBOX_GENERATION_TTL_MS = 15 * 60_000\n\n/**\n * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.\n */\nexport class InvalidAgentTokenError extends Error {\n constructor(studioUrl: string) {\n super(`Kubb Studio rejected this agent's token. It expired or was revoked, or the agent was deleted in ${studioUrl}.`)\n this.name = 'InvalidAgentTokenError'\n }\n}\n\n/**\n * Studio closed with {@link AgentCloseCode.INCOMPATIBLE}. Only an upgrade helps.\n */\nexport class IncompatibleAgentError extends Error {\n constructor({ studioUrl, detail }: { studioUrl: string; detail?: string }) {\n super(`Kubb Studio at ${studioUrl} requires a newer agent${detail ? `: ${detail}` : ''}. Upgrade kubb or the Kubb agent image.`)\n this.name = 'IncompatibleAgentError'\n }\n}\n\nexport type StudioConnectedContext = AgentConnectInfo & {\n url: string\n /**\n * The Studio, runtime, and host versions, so a host can show a mismatch.\n */\n versions: { studio: string; kubb: string; agent: string }\n}\n\ndeclare global {\n namespace Kubb {\n interface KubbHooksRegistry {\n /**\n * Fired after each handshake, including reconnects.\n */\n 'studio:connected': [ctx: StudioConnectedContext]\n 'studio:disconnected': [ctx: { code: number; reason: string }]\n 'studio:reconnecting': [ctx: { delayMs: number }]\n /**\n * A finished command and what it did, such as `applied 2/3 edits to kubb.config.ts`.\n */\n 'studio:command': [ctx: { command: 'generate' | 'saveConfig' | 'readFiles'; info: string }]\n /**\n * A refused or ignored request, with the missing permission so the host can add a remedy.\n */\n 'studio:warn': [ctx: { message: string; permission?: keyof AgentPermissions }]\n 'studio:error': [ctx: { error: Error }]\n }\n }\n}\n\nexport type ConnectAgentOptions = {\n /**\n * The agent's bearer token, from {@link pairAgent}.\n */\n token: string\n studioUrl?: string\n /**\n * The config path shown in Studio, relative to `root` unless absolute.\n */\n configPath: string\n /**\n * Called for every handshake and every generation, so edits on disk show up.\n */\n loadConfig: () => Promise<Config>\n /**\n * The host's own version, reported to Studio next to the runtime's.\n */\n version: string\n /**\n * The project root generation runs against.\n * @default process.cwd()\n */\n root?: string\n /**\n * What Studio may do in this project. Every permission is off unless granted.\n */\n permissions?: Partial<AgentPermissions>\n /**\n * Receives the `studio:*` hooks and the `kubb:*` hooks of every generation.\n */\n hooks?: Hookable<KubbHooks>\n signal?: AbortSignal\n /**\n * Longest wait between reconnect attempts, in milliseconds.\n * @default 30000\n */\n maxRetryDelay?: number\n /**\n * Milliseconds between keep-alive pings, at most 60000.\n * @default 30000\n */\n heartbeatInterval?: number\n}\n\ntype ResolvedOptions = Required<Omit<ConnectAgentOptions, 'signal'>> & {\n signal?: AbortSignal\n permissions: AgentPermissions\n configFile: string\n}\n\ntype Rpc = { studio: StudioApi; closed: Promise<{ code: number; reason: string }>; close: () => void }\n\n// Tests swap in an in-process pair.\nexport type OpenRpc = (input: { url: URL; token: string; instanceId: string; agent: AgentApi }) => Rpc\n\ntype Session = {\n info?: AgentConnectInfo\n connected: PromiseWithResolvers<AgentConnectInfo>\n closed: boolean\n active?: { jobId: string; abort: () => void; settled: Promise<void> }\n}\n\n// A throwing host listener must not break the connection.\nfunction emit<TName extends keyof KubbHooks & string>(hooks: Hookable<KubbHooks>, name: TName, ...args: KubbHooks[TName]): Promise<void> {\n return Promise.resolve(hooks.callHook(name, ...args)).catch(() => {})\n}\n\nfunction isValidPage({ cursor, limit }: Pick<ReadFilesInput, 'cursor' | 'limit'>): boolean {\n if (limit === undefined) return cursor === undefined\n if (cursor !== undefined && (!Number.isSafeInteger(cursor) || cursor < 0)) return false\n return Number.isSafeInteger(limit) && limit >= 1 && limit <= MAX_PAGE_LINES\n}\n\ntype RunHandle = { stream: ReadableStream<GenerationEvent>; result: Promise<GenerateResult>; stop: () => void }\n\nclass GenerationRunTarget extends RpcTarget implements GenerationRun {\n readonly #run: RunHandle\n\n constructor(run: RunHandle) {\n super()\n this.#run = run\n }\n\n async events() {\n return this.#run.stream\n }\n result() {\n return this.#run.result\n }\n async cancel() {\n this.#run.stop()\n }\n // Cap'n Web also calls this when the peer session is torn down, so a dropped socket stops the run.\n [Symbol.dispose]() {\n this.#run.stop()\n }\n}\n\n// Cap'n Web exposes only prototype methods, so the public methods are exactly `AgentApi`.\nclass Agent extends RpcTarget implements AgentApi {\n readonly #options: ResolvedOptions\n readonly #session: Session\n readonly #limits = resolveGenerationLimits()\n #store: GenerationStore | undefined\n\n constructor({ options, session }: { options: ResolvedOptions; session: Session }) {\n super()\n this.#options = options\n this.#session = session\n }\n\n get #sandbox(): boolean {\n return this.#session.info?.sandbox === true\n }\n\n // A sandbox has no project to write to or edit, and Studio may always read what it generated there.\n get #permissions(): AgentPermissions {\n const { permissions } = this.#options\n return this.#sandbox ? { ...permissions, allowWrite: false, allowConfigEdit: false, allowRead: true } : permissions\n }\n\n // Kept in the project's cache directory so it survives a restart. A sandbox keeps them in memory,\n // because its pool runs every tenant's jobs.\n get #generations(): GenerationStore {\n this.#store ??= createGenerationStore({\n storage: this.#sandbox ? memoryStorage() : cacheStorage({ root: this.#options.root }),\n maxCount: this.#limits.maxCount,\n maxMb: this.#limits.maxMb,\n ttlMs: this.#sandbox ? SANDBOX_GENERATION_TTL_MS : undefined,\n })\n return this.#store\n }\n\n #warn({ message, permission }: { message: string; permission?: keyof AgentPermissions }): Promise<void> {\n return emit(this.#options.hooks, 'studio:warn', { message, permission })\n }\n\n // Studio shows the thrown message, and the host logs the same text.\n async #refuse({ message, permission }: { message: string; permission?: keyof AgentPermissions }): Promise<never> {\n await this.#warn({ message, permission })\n throw new Error(message)\n }\n\n async #command<T>({ command, run }: { command: KubbHooks['studio:command'][0]['command']; run: () => Promise<{ value: T; info?: string }> }): Promise<T> {\n if (!this.#session.info) throw new Error('Studio must call connect() before any other command')\n const { value, info } = await run()\n if (info !== undefined) await emit(this.#options.hooks, 'studio:command', { command, info })\n return value\n }\n\n // Not cached: the user can edit the file between two Studio actions.\n async #readConfigFileView(source?: string): Promise<ConfigFileView | undefined> {\n if (!this.#permissions.allowConfigEdit) return undefined\n\n try {\n return readConfig(source ?? (await read(this.#options.configFile)))\n } catch (error) {\n await this.#warn({ message: `Could not read ${this.#options.configFile}: ${getErrorMessage(error)}` })\n return undefined\n }\n }\n\n async connect(info: AgentConnectInfo): Promise<ConnectMessagePayload> {\n this.#session.info = info\n const { configPath, root, version, loadConfig } = this.#options\n const [config, file] = await Promise.all([loadConfig(), this.#readConfigFileView()])\n this.#session.connected.resolve(info)\n\n return {\n versions: { kubb: kubbVersion, agent: version },\n root,\n config: { path: configPath, file, plugins: config.plugins.map((plugin) => ({ name: toPackageName(plugin.name), options: plugin.options ?? {} })) },\n permissions: this.#permissions,\n }\n }\n\n startGeneration(input: GenerateInput): GenerationRun {\n const stream = createGenerationStream(this.#options.hooks, input.jobId)\n const controller = new AbortController()\n const result = this.#runGeneration(input, controller).then(\n (value) => stream.close().then(() => value),\n (error: unknown) => {\n stream.fail(error)\n throw error\n },\n )\n // A disconnect can reject this after the remote caller disappeared.\n void result.catch(() => {})\n\n return new GenerationRunTarget({\n stream: stream.stream,\n result,\n stop: () => {\n controller.abort(new Error('Generation canceled'))\n stream.dispose()\n },\n })\n }\n\n async #runGeneration(input: GenerateInput, controller: AbortController): Promise<GenerateResult> {\n // Checked before the first `await`, so two calls in the same tick can't both pass.\n if (this.#session.closed) throw new Error('Connection is closed')\n if (this.#session.active) return this.#refuse({ message: 'A generation is already in progress, please wait for it to finish' })\n const settled = Promise.withResolvers<void>()\n this.#session.active = { jobId: input.jobId, abort: () => controller.abort(new Error('Generation canceled')), settled: settled.promise }\n let root = this.#options.root\n\n try {\n // Kubb keys its manifest cache by root, so sandbox tenants sharing one root would read each other's.\n if (this.#sandbox) root = await mkdtemp(path.join(tmpdir(), 'kubb-job-'))\n return await this.#command({ command: 'generate', run: () => this.#generate({ input, root, signal: controller.signal }) })\n } finally {\n if (root !== this.#options.root) {\n await Promise.all([rm(root, { recursive: true, force: true }), rm(resolveCacheDir(root), { recursive: true, force: true })]).catch(() => {})\n }\n this.#session.active = undefined\n settled.resolve()\n }\n }\n\n async #generate({ input, root, signal }: { input: GenerateInput; root: string; signal: AbortSignal }): Promise<{ value: GenerateResult; info: string }> {\n const { jobId, config: patch } = input\n const config = await this.#options.loadConfig()\n const plugins = (await mergePlugins(config.plugins, patch?.plugins)) ?? config.plugins\n const adapter = await mergeAdapter(config.adapter, patch?.adapter)\n // A sandbox has no spec on disk, so it always generates from Studio's, empty string included.\n const studioInput = this.#sandbox ? (patch?.input ?? '') : undefined\n\n if (patch?.input && !this.#sandbox) {\n await this.#warn({ message: 'Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox agent' })\n }\n\n const hasProjectOnDisk = !this.#sandbox && this.#permissions.allowRead\n const diskFiles = hasProjectOnDisk ? await listDisk({ root, outputPath: config.output.path, maxFiles: DISK_SNAPSHOT_MAX_FILES }) : undefined\n const disk = diskFiles ? await this.#generations.keep({ jobId, source: 'disk', files: diskFiles, maxSetMb: this.#limits.maxSnapshotMb }) : undefined\n\n const files = await generate({\n config: { ...config, root, input: studioInput ?? config.input, storage: this.#permissions.allowWrite ? fsStorage() : memoryStorage(), plugins, adapter },\n hooks: this.#options.hooks,\n signal,\n allowExec: this.#permissions.allowExec,\n }).catch(async (error: unknown) => {\n await this.#generations.drop(jobId)\n throw error\n })\n\n const output = await this.#generations.keep({ jobId, source: 'output', files, maxSetMb: this.#limits.maxMb })\n if (!output.paths.length && Object.keys(output.hashes).length) {\n await this.#warn({ message: 'Kept only the hashes of this generation: its output is too large to keep' })\n }\n await this.#generations.add({ jobId, output, disk })\n\n return {\n value: {\n status: 'success',\n files: [...files.paths],\n fileCount: files.paths.size,\n hashes: output.hashes,\n disk: disk ? { hashes: disk.hashes } : undefined,\n },\n info: `${plugins.length} plugin${plugins.length === 1 ? '' : 's'}, ${this.#permissions.allowWrite ? 'written to disk' : 'in memory'}${studioInput !== undefined ? ', from a Studio spec' : ''}`,\n }\n }\n\n saveConfig(input: SaveConfigInput): Promise<SaveResult> {\n return this.#command({ command: 'saveConfig', run: () => this.#saveConfig(input) })\n }\n\n async #saveConfig(input: SaveConfigInput): Promise<{ value: SaveResult; info?: string }> {\n const { configPath, configFile } = this.#options\n\n if (!Array.isArray(input.edits)) {\n await this.#warn({ message: 'Ignored save: the message carried no edits' })\n return { value: { outcomes: [], changed: false } }\n }\n\n const edits = input.edits\n const refuse = (reason: string): SaveResult => ({ outcomes: edits.map((edit) => ({ edit, applied: false, reason })), changed: false })\n\n if (!this.#permissions.allowConfigEdit) {\n await this.#warn({ message: 'Ignored save: editing kubb.config.ts was not granted' })\n return { value: refuse('the agent was not granted permission to edit kubb.config.ts') }\n }\n\n // A running generation reloads the config, so it would see half the change.\n if (this.#session.active) return { value: refuse('a generation is in progress') }\n\n try {\n const { source, outcomes, changed } = await writeConfigEdits({ filePath: configFile, edits })\n const applied = outcomes.filter((outcome) => outcome.applied).length\n\n return {\n value: { outcomes, changed, file: changed ? await this.#readConfigFileView(source) : undefined },\n info: `applied ${applied}/${outcomes.length} edits to ${configPath}`,\n }\n } catch (error) {\n // Refuse every edit so Studio hears back instead of waiting.\n await emit(this.#options.hooks, 'studio:error', { error: toError(error) })\n return { value: refuse(getErrorMessage(error)) }\n }\n }\n\n readFiles(input: ReadFilesInput): Promise<ReadFilesResult> {\n return this.#command({ command: 'readFiles', run: () => this.#readFiles(input) })\n }\n\n async #readFiles(input: ReadFilesInput): Promise<{ value: ReadFilesResult; info: string }> {\n if (!this.#permissions.allowRead) return this.#refuse({ message: 'The agent was not granted permission to read generated files', permission: 'allowRead' })\n if (!Array.isArray(input.paths) || typeof input.jobId !== 'string' || !input.jobId) {\n return this.#refuse({ message: 'The request must name a job and carry paths' })\n }\n const { paths } = input\n if (paths.length > MAX_FILES_PER_REQUEST) return this.#refuse({ message: `At most ${MAX_FILES_PER_REQUEST} paths may be requested at once` })\n\n const generation = await this.#generations.get(input.jobId)\n if (!generation) return this.#refuse({ message: GENERATION_GONE_MESSAGE })\n if (!isValidPage(input)) return this.#refuse({ message: `The cursor must be a whole line from 0 and come with a limit of 1 to ${MAX_PAGE_LINES} lines` })\n\n const source = input.source === 'disk' ? 'disk' : 'output'\n if (!generation[source]) return this.#refuse({ message: 'This agent kept no snapshot of the files on disk for that job' })\n\n // Only paths the set holds are read, never an arbitrary path.\n const result = await this.#generations.read({ generation, source, paths, cursor: input.cursor, limit: input.limit })\n\n return { value: result, info: `read ${Object.keys(result.files).length}/${paths.length} requested file${paths.length === 1 ? '' : 's'}` }\n }\n}\n\nconst openWebSocketRpc: OpenRpc = ({ url, token, instanceId, agent }) => {\n // Node's `WebSocket` takes undici's `headers` option, which the DOM typing leaves out.\n const NodeWebSocket = WebSocket as unknown as new (url: URL, init: { headers: Record<string, string> }) => WebSocket\n const socket = new NodeWebSocket(url, { headers: { Authorization: `Bearer ${token}`, [AGENT_INSTANCE_HEADER]: instanceId } })\n const timer = setTimeout(() => socket.close(3008, 'Connection timeout'), OPEN_TIMEOUT_MS)\n socket.addEventListener('open', () => clearTimeout(timer), { once: true })\n\n const closed = new Promise<Awaited<Rpc['closed']>>((resolve) => {\n socket.addEventListener('close', ({ code, reason }) => resolve({ code, reason }), { once: true })\n // Node fires only `error` when the handshake itself fails.\n socket.addEventListener('error', () => {\n if (socket.readyState !== WebSocket.OPEN) resolve({ code: 1006, reason: '' })\n })\n }).finally(() => clearTimeout(timer))\n\n const studio = newWebSocketRpcSession<StudioApi>(socket, agent)\n studio.onRpcBroken(() => socket.close())\n\n return {\n studio,\n closed,\n close: () => {\n studio[Symbol.dispose]()\n socket.close()\n },\n }\n}\n\nasync function runSession({ options, openRpc, url, instanceId }: { options: ResolvedOptions; openRpc: OpenRpc; url: URL; instanceId: string }) {\n const { hooks, signal, heartbeatInterval, token, studioUrl, version } = options\n const session: Session = { connected: Promise.withResolvers(), closed: false }\n const rpc = openRpc({ url, token, instanceId, agent: new Agent({ options, session }) })\n signal?.addEventListener('abort', rpc.close, { once: true })\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // Races each ping against a deadline, so a half-open socket can't hang it forever.\n const heartbeat = async (): Promise<void> => {\n let deadline: ReturnType<typeof setTimeout> | undefined\n const timedOut = new Promise<boolean>((resolve) => (deadline = setTimeout(resolve, PING_TIMEOUT_MS, true)))\n const failed = await Promise.race([\n Promise.resolve(rpc.studio.ping()).then(\n () => false,\n () => true,\n ),\n timedOut,\n ])\n clearTimeout(deadline)\n if (failed) return rpc.close()\n if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval)\n }\n\n void session.connected.promise.then(\n async (info) => {\n await emit(hooks, 'studio:connected', { ...info, url: studioUrl, versions: { studio: info.studioVersion, kubb: kubbVersion, agent: version } })\n if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval)\n },\n () => {},\n )\n\n const close = await rpc.closed\n session.closed = true\n clearTimeout(timer)\n signal?.removeEventListener('abort', rpc.close)\n session.connected.reject(new Error('The socket closed before Studio called connect()'))\n session.active?.abort()\n await session.active?.settled\n\n return { ...close, connected: session.info !== undefined }\n}\n\n/**\n * The connection loop with a swappable transport. {@link connectAgent} passes a real WebSocket.\n */\nexport async function runAgent({ options, openRpc }: { options: ConnectAgentOptions; openRpc: OpenRpc }): Promise<void> {\n const root = options.root ?? process.cwd()\n const resolved: ResolvedOptions = {\n ...options,\n studioUrl: options.studioUrl ?? defaultStudioUrl,\n root,\n configFile: path.resolve(root, options.configPath),\n permissions: { allowWrite: false, allowConfigEdit: false, allowExec: false, allowRead: false, ...options.permissions },\n hooks: options.hooks ?? new Hookable<KubbHooks>(),\n maxRetryDelay: options.maxRetryDelay ?? MAX_RETRY_DELAY_MS,\n heartbeatInterval: Math.min(options.heartbeatInterval ?? HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS),\n }\n const { studioUrl, hooks, signal, maxRetryDelay } = resolved\n const url = secureUrl({ studioUrl, path: AGENT_SOCKET_PATH, socket: true })\n // One per call, so a reconnect is the same process to Studio and a restart is a new one.\n const instanceId = randomUUID()\n let attempt = 0\n\n while (!signal?.aborted) {\n const { code, reason, connected } = await runSession({ options: resolved, openRpc, url, instanceId })\n if (signal?.aborted) return\n await emit(hooks, 'studio:disconnected', { code, reason })\n\n if (code === AgentCloseCode.UNAUTHORIZED) throw new InvalidAgentTokenError(studioUrl)\n if (code === AgentCloseCode.INCOMPATIBLE) throw new IncompatibleAgentError({ studioUrl, detail: reason })\n if (code === AgentCloseCode.SUPERSEDED) return\n\n // Reset only once Studio called connect(), so a socket that opens and closes again backs off.\n if (connected) attempt = 0\n const delayMs = Math.random() * Math.min(1_000 * 2 ** Math.min(attempt++, 16), maxRetryDelay)\n await emit(hooks, 'studio:reconnecting', { delayMs })\n await delay(delayMs, undefined, { signal }).catch(() => {})\n }\n}\n\n/**\n * Connects this project to Kubb Studio and serves its commands until `signal` aborts. Reconnects\n * with jittered backoff, and resolves when another process of the agent takes over. Rejects with\n * {@link InvalidAgentTokenError} so the host can pair again, or {@link IncompatibleAgentError}.\n *\n * @example\n * ```ts\n * const hooks = new Hookable<KubbHooks>()\n * hooks.hook('studio:connected', ({ agentSlug }) => console.log(`Connected as ${agentSlug}`))\n *\n * await connectAgent({ token, configPath: 'kubb.config.ts', loadConfig, version: '1.0.0', hooks, signal })\n * ```\n */\nexport function connectAgent(options: ConnectAgentOptions): Promise<void> {\n return runAgent({ options, openRpc: openWebSocketRpc })\n}\n","import { hash } from 'node:crypto'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { toError } from '@internals/utils'\nimport { ofetch } from 'ofetch'\nimport { defaultStudioUrl, secureUrl } from './url.ts'\n\n/**\n * RFC 8628 device-authorization response from Studio's `/api/auth/device/code` endpoint.\n * Field names match the RFC; the CLI polls with `device_code` and shows `user_code` to the user.\n */\nexport type PairingSession = {\n device_code: string\n user_code: string\n verification_uri: string\n verification_uri_complete: string\n expires_in: number\n interval: number\n}\n\ntype PairingResult = {\n /**\n * Bearer token for this machine. Write credentials with mode 0600 and never log the value.\n */\n token: string\n agent: {\n /**\n * Stable agent id in Studio.\n */\n id: string\n /**\n * Short slug used in logs and the UI (for example `brave-otter`).\n */\n slug: string\n /**\n * Display name chosen at pairing time.\n */\n name: string\n /**\n * This agent's organization slug, absent for a sandbox or global agent, which has none.\n */\n organizationSlug?: string\n }\n}\n\n/**\n * What this machine registers as. Any member may approve `cli` (`kubb studio`); only an admin may\n * approve `user` and `sandbox` (the Docker image). A `ci` agent never pairs.\n */\ntype PairingAgentType = 'cli' | 'user' | 'sandbox'\n\n/** Labels, not secrets: a person approving the code in the browser is what authorizes a pairing. */\nconst CLIENT_IDS = { cli: 'kubb-cli', agent: 'kubb-agent' } as const\n\n/**\n * Thrown when a caller aborts `startPairing` or `pollForPairingToken` through their `signal`, such\n * as a `kubb studio` shutdown mid-pairing. Distinct from a denial or an expired code, so a host can\n * exit quietly instead of reporting a pairing failure.\n */\nexport class PairingCanceledError extends Error {\n constructor() {\n super('Pairing was canceled')\n this.name = 'PairingCanceledError'\n }\n}\n\n/** Thrown when the code expired unapproved. A fresh code can still succeed. */\nexport class PairingExpiredError extends Error {\n constructor(message = 'The pairing code expired, pair again') {\n super(message)\n this.name = 'PairingExpiredError'\n }\n}\n\n/** Thrown when the pairing was denied in the browser, including by the organization's agent limit. */\nexport class PairingDeniedError extends Error {\n constructor(message = 'Pairing was denied in the browser') {\n super(message)\n this.name = 'PairingDeniedError'\n }\n}\n\ntype StartPairingOptions = {\n studioUrl?: string\n type: PairingAgentType\n /**\n * Display name for the agent, usually the project or machine name.\n */\n name: string\n hostname: string\n /**\n * A stable secret the host keeps for this machine. Studio stores its hash against the agent, so\n * the same machine pairing again rotates one agent's token instead of creating a second agent.\n */\n machineId: string\n /**\n * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.\n */\n signal?: AbortSignal\n}\n\n/**\n * Asks Studio for a pairing code, sending the hashed machine id with it.\n */\nexport async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }: StartPairingOptions): Promise<PairingSession> {\n try {\n const pairing = await ofetch<PairingSession>(secureUrl({ studioUrl, path: '/api/auth/device/code' }).href, {\n method: 'POST',\n body: {\n client_id: type === 'cli' ? CLIENT_IDS.cli : CLIENT_IDS.agent,\n name,\n hostname,\n machine_token: hash('sha256', machineId),\n agent_kind: type === 'cli' ? undefined : type,\n },\n signal,\n })\n if (typeof pairing?.device_code !== 'string') throw new Error('Kubb Studio returned no pairing code')\n\n return pairing\n } catch (error) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n throw error\n }\n}\n\ntype PollOptions = {\n studioUrl?: string\n session: PairingSession\n /**\n * Aborting this stops polling and rejects with {@link PairingCanceledError}, whether the abort\n * lands between polls or during the wait for the next one.\n */\n signal?: AbortSignal\n /** Called when a poll could not reach Studio. Polling carries on. */\n onRetry?: (error: Error) => void\n}\n\ntype PollError = 'authorization_pending' | 'slow_down' | 'expired_token' | 'access_denied' | 'invalid_grant'\n\ntype PollResponse =\n | PairingResult\n | {\n error: PollError | string\n /**\n * Why, when Studio has something more useful to say than the RFC code. An approval that hits\n * the organization's agent limit comes back as `access_denied` with the limit spelled out.\n */\n error_description?: string\n }\n\nfunction isPairingResult(response: PollResponse): response is PairingResult {\n return 'token' in response && typeof response.token === 'string'\n}\n\n/**\n * Polls until the user approves or denies, honoring the server's `slow_down` back-off.\n *\n * Studio's own endpoint is used rather than the auth layer's `/device/token`, because an approved\n * Kubb pairing is worth an agent bearer token, not a user session.\n *\n * @throws {PairingExpiredError} when the code expires before anyone approves it.\n * @throws {PairingDeniedError} when the pairing is denied in the browser.\n * @throws {PairingCanceledError} when `signal` aborts.\n */\nexport async function pollForPairingToken({ studioUrl = defaultStudioUrl, session, signal, onRetry }: PollOptions): Promise<PairingResult> {\n // Both fields cross the network, so neither is trusted as-is: a missing or zero `interval` would\n // spin the poll loop, and a missing or zero `expires_in` would expire the code before the first\n // poll. `> 0` is also false for `NaN` and for a missing field, so it doubles as the type guard.\n const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1000\n let intervalMs = (session.interval > 0 ? session.interval : 5) * 1000\n\n while (Date.now() < deadline) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n try {\n await delay(intervalMs, undefined, { signal })\n } catch {\n throw new PairingCanceledError()\n }\n\n let response: PollResponse\n try {\n // A denial, an expiry, and \"not yet\" all come back as 4xx with a body to switch on.\n const { status, _data } = await ofetch.raw<PollResponse>(secureUrl({ studioUrl, path: '/api/agent/token' }).href, {\n method: 'POST',\n body: { device_code: session.device_code },\n signal,\n ignoreResponseError: true,\n })\n if (status >= 500 || !_data || typeof _data !== 'object') throw new Error(`Kubb Studio answered with status ${status}`)\n response = _data\n } catch (error) {\n if (signal?.aborted) {\n throw new PairingCanceledError()\n }\n\n // Studio can be briefly unreachable (a deploy) while the code is still valid, so retry.\n onRetry?.(toError(error))\n continue\n }\n\n if (isPairingResult(response)) {\n return response\n }\n\n if (!('error' in response) || typeof response.error !== 'string') {\n throw new Error('Kubb Studio returned an empty pairing response, pair again')\n }\n\n if (response.error === 'authorization_pending') {\n continue\n }\n\n if (response.error === 'slow_down') {\n intervalMs += 5_000\n continue\n }\n\n if (response.error === 'access_denied') {\n throw new PairingDeniedError(response.error_description)\n }\n\n if (response.error === 'expired_token' || response.error === 'invalid_grant') {\n throw new PairingExpiredError(response.error_description)\n }\n\n throw new Error(response.error_description ?? `Pairing failed (${response.error})`)\n }\n\n throw new PairingExpiredError()\n}\n\ntype PairAgentOptions = StartPairingOptions & {\n /** Shows the code to whoever approves it. Called again for each fresh code. */\n onCode: (session: PairingSession, attempt: number) => void | Promise<void>\n /** Called when a poll could not reach Studio. Polling carries on. */\n onRetry?: (error: Error) => void\n /**\n * Codes to ask for in total when one expires unapproved. A denial or abort ends it at once.\n * @default 1\n */\n maxAttempts?: number\n}\n\n/**\n * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.\n */\nexport async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }: PairAgentOptions): Promise<PairingResult> {\n for (let attempt = 1; ; attempt++) {\n const session = await startPairing(options)\n await onCode(session, attempt)\n\n try {\n return await pollForPairingToken({ studioUrl: options.studioUrl, session, signal: options.signal, onRetry })\n } catch (error) {\n if (!(error instanceof PairingExpiredError) || attempt >= maxAttempts) {\n throw error\n }\n }\n }\n}\n","import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { promisify } from 'node:util'\nimport { gzip } from 'node:zlib'\nimport { type Config, fsStorage, type Hookable, type KubbHooks } from '@kubb/core'\nimport { ofetch } from 'ofetch'\nimport { generate, hashOf } from './generations.ts'\nimport { MAX_SNAPSHOT_BYTES, type PublishedSnapshot, type SnapshotUploadMetadata } from './protocol.ts'\nimport { resolvePeerDependencies } from './resolveConfig.ts'\nimport { defaultStudioUrl, secureUrl } from './url.ts'\n\nconst gzipAsync = promisify(gzip)\nconst UPLOAD_TIMEOUT_MS = 120_000\n\n// Plugins whose output a snapshot carries without depending on the plugin package.\nconst BUNDLED_DEPENDENCIES = ['@kubb/plugin-barrel']\n\ntype SnapshotFiles = Record<string, string>\ntype SnapshotPackage = { name: string; version: string; peerDependencies: Record<string, string> }\n\n/**\n * Maps a generated file to its path in the package, from its `src`/`dist` segment on, without `..` parts that could escape it.\n */\nfunction packagePath(filePath: string): string {\n const normalized = filePath.replaceAll('\\\\', '/')\n const relativePath = normalized.match(/\\/(?:src|dist)\\/.*$/)?.[0] ?? normalized\n return relativePath\n .split('/')\n .filter((part) => part && part !== '.' && part !== '..')\n .join('/')\n}\n\n/**\n * Splits a tar path into the 100-byte USTAR `name` and the 155-byte `prefix`, and throws for a path that fits neither.\n */\nfunction splitEntryPath(path: string): { name: string; prefix: string } {\n if (Buffer.byteLength(path) <= 100) return { name: path, prefix: '' }\n for (let i = path.lastIndexOf('/'); i > 0; i = path.lastIndexOf('/', i - 1)) {\n const prefix = path.slice(0, i)\n const name = path.slice(i + 1)\n if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) return { name, prefix }\n }\n throw new Error(`Snapshot path is too long for a tar entry: ${path}`)\n}\n\nfunction header(path: string, size: number): Buffer {\n const { name, prefix } = splitEntryPath(path)\n const value = Buffer.alloc(512)\n value.write(name)\n value.write('0000644\\0', 100)\n for (const offset of [108, 116, 265, 297]) value.write('0000000\\0', offset)\n value.write(`${size.toString(8).padStart(11, '0')}\\0`, 124)\n // npm's fixed mtime, so the same files always pack to the same integrity.\n value.write('03560116604\\0', 136)\n value.fill(32, 148, 156)\n value.write('0', 156)\n value.write('ustar\\0', 257)\n value.write('00', 263)\n value.write(prefix, 345)\n const checksum = value.reduce((sum, byte) => sum + byte, 0)\n value.write(`${checksum.toString(8).padStart(6, '0')}\\0 `, 148)\n return value\n}\n\n/**\n * Packs a generation's files into a gzipped, npm-installable tarball: a `package/` root with the\n * generated sources, a `tsdown`-built `dist/` (esm + cjs), and a `package.json` manifest.\n */\nexport async function createSnapshotPackage({ files, packageInfo }: { files: SnapshotFiles; packageInfo: SnapshotPackage }): Promise<Buffer> {\n const sources = new Map<string, { name: string; content: string }>()\n for (const [name, content] of Object.entries(files)) {\n const path = packagePath(name)\n const owner = sources.get(path)?.name\n if (owner) throw new Error(`Snapshot has two generated files that sanitize to the same path \"package/${path}\": \"${owner}\" and \"${name}\"`)\n sources.set(path, { name, content })\n }\n const root = await mkdtemp(join(tmpdir(), 'kubb-snapshot-'))\n const dist = join(root, 'dist')\n\n try {\n await mkdir(dist)\n await Promise.all(\n [...sources].map(async ([path, { content }]) => {\n await mkdir(dirname(join(root, path)), { recursive: true })\n await writeFile(join(root, path), content)\n }),\n )\n const entry = [...sources.keys()].filter((path) => /\\.(?:[cm]?[jt]sx?)$/.test(path)).map((path) => join(root, path))\n if (entry.length) {\n // Loaded on first use: tsdown is large, and most agent processes never pack a snapshot.\n const { build } = await import('tsdown')\n // `fixedExtension` emits the `.mjs`/`.cjs` the manifest names, whatever \"type\" the host's own package.json sets.\n await build({\n entry,\n outDir: dist,\n format: ['esm', 'cjs'],\n dts: false,\n sourcemap: false,\n unbundle: true,\n report: false,\n logLevel: 'silent',\n fixedExtension: true,\n })\n }\n const built = await fsStorage().readKeys(dist)\n // Only `@kubb/plugin-barrel` produces a `dist/index.*` for `main`, `module`, and `exports['.']` to name.\n const hasBarrel = built.includes('index.mjs') && built.includes('index.cjs')\n const manifest = {\n ...packageInfo,\n type: 'module',\n ...(hasBarrel ? { main: './dist/index.cjs', module: './dist/index.mjs' } : {}),\n // `exports` denies any subpath it does not list, so the wildcard keeps each generated file importable.\n exports: {\n ...(hasBarrel ? { '.': { import: './dist/index.mjs', require: './dist/index.cjs' } } : {}),\n './*': { import: './dist/*.mjs', require: './dist/*.cjs' },\n },\n }\n const entries = new Map<string, string>([\n ['package.json', JSON.stringify(manifest, null, 2)],\n ...[...sources].map(([path, { content }]) => [path, content] as const),\n ...(await Promise.all(built.map(async (key) => [`dist/${key}`, await readFile(join(dist, key), 'utf8')] as const))),\n ])\n const chunks = [...entries].flatMap(([path, content]) => {\n const bytes = Buffer.from(content)\n return [header(`package/${path}`, bytes.length), bytes, Buffer.alloc((512 - (bytes.length % 512)) % 512)]\n })\n return await gzipAsync(Buffer.concat([...chunks, Buffer.alloc(1024)]))\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n}\n\ntype CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDependencies'> & {\n studioUrl?: string\n /**\n * Organization CI API key, sent as `x-api-key`.\n */\n apiKey: string\n /**\n * The project's Kubb config, generated like `kubb generate`: formatter, linter, and `output.postGenerate` included.\n */\n config: Config\n hooks?: Hookable<KubbHooks>\n signal?: AbortSignal\n}\n\n/**\n * Generates the project, packs it as an npm tarball, and publishes it to Studio in one `POST /api/snapshots` request.\n *\n * @example\n * ```ts\n * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, config, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })\n * ```\n */\nexport async function createSnapshot({\n studioUrl = defaultStudioUrl,\n apiKey,\n config,\n hooks,\n signal,\n ...metadata\n}: CreateSnapshotOptions): Promise<PublishedSnapshot> {\n const url = secureUrl({ studioUrl, path: '/api/snapshots' })\n const generated = await generate({ config, hooks, signal, allowExec: true })\n const files = Object.fromEntries(\n await Promise.all(\n [...generated.paths].map(async (path) => {\n const content = await generated.storage.readItem(resolve(generated.root, path))\n if (content === null) throw new Error(`The generation listed ${path} but did not keep its content`)\n return [path, content] as const\n }),\n ),\n )\n const { peerDependencies, missingDependencies } = await resolvePeerDependencies(config.plugins.map(({ name }) => name))\n // The package would declare no version for a plugin that is not installed.\n const missing = missingDependencies.filter((dependency) => !BUNDLED_DEPENDENCIES.includes(dependency))\n if (missing.length) throw new Error(`Missing dependencies: ${missing.join(', ')}`)\n\n const bytes = await createSnapshotPackage({ files, packageInfo: { name: metadata.packageName, version: metadata.version, peerDependencies } })\n if (bytes.length > MAX_SNAPSHOT_BYTES) {\n throw new Error(`The snapshot is ${Math.ceil(bytes.length / 1024 / 1024)} MB, over the ${MAX_SNAPSHOT_BYTES / 1024 / 1024} MB limit`)\n }\n\n const hashes = Object.fromEntries(Object.entries(files).map(([path, content]) => [path, hashOf(content)]))\n const body = new FormData()\n body.set('metadata', JSON.stringify({ ...metadata, hashes, peerDependencies } satisfies SnapshotUploadMetadata))\n body.set('tarball', new Blob([new Uint8Array(bytes)], { type: 'application/gzip' }), 'snapshot.tgz')\n\n const timeout = AbortSignal.timeout(UPLOAD_TIMEOUT_MS)\n // A redirect would forward the CI key and tarball to wherever it points.\n const { ok, status, _data } = await ofetch.raw<{ snapshot?: PublishedSnapshot; message?: string; data?: { upgradeUrl?: string } }>(url.href, {\n method: 'POST',\n headers: { 'x-api-key': apiKey },\n body,\n redirect: 'error',\n signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n ignoreResponseError: true,\n })\n if (!ok) {\n const upgrade = _data?.data?.upgradeUrl ? ` Upgrade at ${_data.data.upgradeUrl}.` : ''\n throw new Error(`Kubb Studio refused the snapshot (status ${status})${_data?.message ? `: ${_data.message}` : ''}.${upgrade}`)\n }\n if (!_data?.snapshot) throw new Error(`Kubb Studio returned no snapshot (status ${status})`)\n return _data.snapshot\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,gBAAgB,MAAc,QAAyB;CAC9D,OAAO,KACJ,KAAK,CAAC,CACN,QAAQ,qBAAqB,OAAO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