@kubb/studio 5.6.0 → 5.6.1

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 CHANGED
@@ -1,19 +1,47 @@
1
1
  import "./rolldown-runtime-CRm0XQPb.js";
2
- import { a as resolvePeerDependencies, c as read, i as mergePlugins, r as mergeAdapter, s as toPackageName } from "./resolveConfig-DOUv_Tid.js";
3
- import { AGENT_INSTANCE_HEADER, AgentCloseCode, GENERATION_GONE_MESSAGE, MAX_PAGE_LINES, generationEventTypes } from "./protocol.js";
4
- import { t as isLoopbackHost } from "./url-DhFfJpxp.js";
5
- import { createHash, hash, randomBytes, randomUUID } from "node:crypto";
6
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
- import process$1 from "node:process";
8
- import path, { isAbsolute, relative, resolve, sep } from "node:path";
9
- import { mkdtemp, rm } from "node:fs/promises";
10
- import { FetchError, ofetch } from "ofetch";
11
- import { stripVTControlCharacters, styleText } from "node:util";
12
- import { createStorage } from "unstorage";
13
- import fsDriver from "unstorage/drivers/fs";
2
+ import { AGENT_INSTANCE_HEADER, AGENT_SOCKET_PATH, AgentCloseCode, GENERATION_GONE_MESSAGE, MAX_PAGE_LINES, MAX_SNAPSHOT_BYTES, generationEventTypes } from "./protocol.js";
3
+ import { createRequire } from "node:module";
4
+ import { createHash, hash, randomUUID } from "node:crypto";
5
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
14
6
  import { tmpdir } from "node:os";
7
+ import path, { isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import process$1 from "node:process";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ import { pathToFileURL } from "node:url";
11
+ import { existsSync } from "node:fs";
15
12
  import { Diagnostics, Hookable, cacheStorage, createKubb, fsStorage, memoryStorage, resolveCacheDir } from "@kubb/core";
16
13
  import { RpcTarget, newWebSocketRpcSession } from "capnweb";
14
+ import { builders, detectCodeFormat, generateCode, parseModule } from "magicast";
15
+ import { promisify, stripVTControlCharacters } from "node:util";
16
+ import { ofetch } from "ofetch";
17
+ import { gzip } from "node:zlib";
18
+ //#region ../../internals/utils/src/casing.ts
19
+ /**
20
+ * Shared implementation for camelCase and PascalCase conversion.
21
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
22
+ * and capitalizes each word according to `pascal`.
23
+ *
24
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
25
+ */
26
+ function toCamelOrPascal(text, pascal) {
27
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
28
+ if (word.length > 1 && word === word.toUpperCase()) return word;
29
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
30
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
31
+ }
32
+ /**
33
+ * Converts `text` to camelCase.
34
+ *
35
+ * @example Word boundaries
36
+ * `camelCase('hello-world') // 'helloWorld'`
37
+ *
38
+ * @example With a prefix
39
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
40
+ */
41
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
42
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
43
+ }
44
+ //#endregion
17
45
  //#region ../../internals/utils/src/errors.ts
18
46
  /**
19
47
  * Coerces an unknown thrown value to an `Error` instance.
@@ -42,6 +70,91 @@ function getErrorMessage(value) {
42
70
  return value instanceof Error ? value.message : String(value);
43
71
  }
44
72
  //#endregion
73
+ //#region ../../internals/utils/src/runtime.ts
74
+ /**
75
+ * Detects the JavaScript runtime executing the current process and exposes its name and version.
76
+ *
77
+ * Prefer the shared {@link runtime} instance over constructing your own.
78
+ */
79
+ var Runtime = class {
80
+ /**
81
+ * `true` when the current process is running under Bun.
82
+ *
83
+ * Detection keys off the global `Bun` object rather than `process.versions`,
84
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
85
+ * otherwise look like Node.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * if (runtime.isBun) {
90
+ * await Bun.write(path, data)
91
+ * }
92
+ * ```
93
+ */
94
+ get isBun() {
95
+ return typeof Bun !== "undefined";
96
+ }
97
+ /**
98
+ * `true` when the current process is running under Deno.
99
+ */
100
+ get isDeno() {
101
+ return typeof globalThis.Deno !== "undefined";
102
+ }
103
+ /**
104
+ * `true` when the current process is running under Node.
105
+ *
106
+ * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
107
+ */
108
+ get isNode() {
109
+ return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
110
+ }
111
+ /**
112
+ * Name of the runtime executing the current process.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
117
+ * ```
118
+ */
119
+ get name() {
120
+ if (this.isBun) return "bun";
121
+ if (this.isDeno) return "deno";
122
+ return "node";
123
+ }
124
+ /**
125
+ * Version of the active runtime, or an empty string when it cannot be read.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
130
+ * ```
131
+ */
132
+ get version() {
133
+ if (this.isBun) return process.versions.bun ?? "";
134
+ if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
135
+ return process.versions?.node ?? "";
136
+ }
137
+ };
138
+ /**
139
+ * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
140
+ */
141
+ const runtime = new Runtime();
142
+ //#endregion
143
+ //#region ../../internals/utils/src/fs.ts
144
+ /**
145
+ * Reads the file at `path` as a UTF-8 string.
146
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * const source = await read('./src/Pet.ts')
151
+ * ```
152
+ */
153
+ async function read(path) {
154
+ if (runtime.isBun) return Bun.file(path).text();
155
+ return readFile(path, { encoding: "utf8" });
156
+ }
157
+ //#endregion
45
158
  //#region ../../internals/utils/src/promise.ts
46
159
  /**
47
160
  * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
@@ -78,360 +191,800 @@ function getElapsedMs(hrStart) {
78
191
  return Math.round(ms * 100) / 100;
79
192
  }
80
193
  //#endregion
81
- //#region src/operations/machine.ts
194
+ //#region package.json
195
+ var version = "5.6.1";
196
+ //#endregion
197
+ //#region src/resolveConfig.ts
82
198
  /**
83
- * Key-value storage the runtime uses for its machine secret and the last Studio config.
199
+ * Imports a package, falling back to how the user's project would resolve it.
84
200
  *
85
- * One storage per process, since one process serves one config file. Hosts install their own
86
- * driver on startup: Nitro passes its `kubb` mount, the CLI an fs driver under `~/.kubb/cache`.
87
- * The in-memory default keeps the runtime usable without a host, at the cost of a machine
88
- * identity that changes on every restart.
201
+ * `import()` resolves from this file, so a linked or globally installed Studio (`pnpm link`,
202
+ * `npm i -g`) only sees its own `node_modules` and misses the plugins installed next to the user's
203
+ * config. The retry resolves from `process.cwd()` instead.
89
204
  */
90
- let storage = createStorage();
91
- let hasInstalledStorage = false;
205
+ async function importFromProject(packageName) {
206
+ try {
207
+ return await import(packageName);
208
+ } catch {
209
+ const resolved = createRequire(pathToFileURL(`${process.cwd()}/`)).resolve(packageName);
210
+ const esm = resolved.replace(/\.cjs$/, ".js");
211
+ return await import(pathToFileURL(esm !== resolved && existsSync(esm) ? esm : resolved).href);
212
+ }
213
+ }
92
214
  /**
93
- * Installs the storage driver the runtime persists to. Call once, before connecting.
215
+ * Strips the `@kubb/` scope from a plugin package name, matching the `name` convention Kubb
216
+ * plugin factories use internally.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * toPluginName('@kubb/plugin-ts') // 'plugin-ts'
221
+ * ```
94
222
  */
95
- function setStorage(next) {
96
- storage = next;
97
- hasInstalledStorage = true;
223
+ function toPluginName(packageName) {
224
+ return packageName.split("/").pop() ?? packageName;
98
225
  }
99
226
  /**
100
- * A storage backed by files under `base`, so the machine secret and the last Studio config
101
- * survive a restart. Repeated pairings of one machine depend on that secret staying put.
227
+ * Adds the `@kubb/` scope a plugin's package carries but its `name` does not, the inverse of
228
+ * {@link toPluginName}. A name outside the `plugin-` convention is left alone, so a third-party
229
+ * plugin is not reported as one of Kubb's.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * toPackageName('plugin-ts') // '@kubb/plugin-ts'
234
+ * toPackageName('@acme/my-plugin') // '@acme/my-plugin'
235
+ * ```
102
236
  */
103
- function createFileStorage(base) {
104
- return createStorage({ driver: fsDriver({ base }) });
237
+ function toPackageName(name) {
238
+ return name.startsWith("plugin-") ? `@kubb/${name}` : name;
105
239
  }
106
- let fallbackSecretPromise = null;
107
240
  /**
108
- * Loads the fallback machine secret from the runtime storage.
109
- * On first use it generates a secret and persists it, so the machine identity stays
110
- * stable across restarts. An identity that changes on every boot breaks session
111
- * creation with Studio whenever the startup registration call fails.
241
+ * Derives the conventional named export for a `@kubb/*` plugin package from its package name.
242
+ *
243
+ * @example
244
+ * ```ts
245
+ * toExportName('@kubb/plugin-react-query') // 'pluginReactQuery'
246
+ * toExportName('@kubb/plugin-ts') // 'pluginTs'
247
+ * ```
112
248
  */
113
- async function loadOrCreateFallbackSecret() {
114
- if (!hasInstalledStorage) console.warn(styleText("yellow", "Deriving the machine token before a storage driver was installed"), "call setStorage() first, or set KUBB_AGENT_SECRET, to keep a stable machine identity across restarts");
115
- const stored = await storage.getItem("machine-secret").catch(() => null);
116
- if (typeof stored === "string" && stored) return stored;
117
- const secret = randomBytes(32).toString("hex");
118
- await storage.setItem("machine-secret", secret).catch(() => {
119
- console.warn(styleText("yellow", "Could not persist the generated machine secret"), "set KUBB_AGENT_SECRET to keep a stable machine identity across restarts");
120
- });
121
- return secret;
249
+ function toExportName(packageName) {
250
+ return camelCase(toPluginName(packageName));
122
251
  }
123
252
  /**
124
- * Hashes a stable secret into the machine token Studio expects, so a host can derive one from its
125
- * own identity without duplicating `getMachineToken`'s SHA-256 step.
253
+ * A `@kubb/plugin-*` package specifier. Nothing else may reach `import()`: only Kubb's own
254
+ * plugins are supported, so a payload naming anything else, a third-party package or a path, is
255
+ * refused before it can execute.
126
256
  */
127
- function machineTokenFrom(secret) {
128
- return hash("sha256", secret);
129
- }
257
+ const KUBB_PLUGIN_SPECIFIER = /^@kubb\/plugin-[\w.-]+$/;
130
258
  /**
131
- * Returns the machine token derived from the `KUBB_AGENT_SECRET` environment variable.
132
- * Falls back to a generated secret persisted in the runtime storage if the env var is not set.
133
- * The token is hashed with SHA-256.
259
+ * Whether `name` is a `@kubb/plugin-*` specifier. Exported so `configFile.ts` can refuse the same
260
+ * shape before printing a Studio-supplied plugin name into the config file's source text.
134
261
  */
135
- async function getMachineToken() {
136
- if (process$1.env.KUBB_AGENT_SECRET) return machineTokenFrom(process$1.env.KUBB_AGENT_SECRET);
137
- fallbackSecretPromise ??= loadOrCreateFallbackSecret();
138
- return machineTokenFrom(await fallbackSecretPromise);
262
+ function isKubbPluginSpecifier(name) {
263
+ return KUBB_PLUGIN_SPECIFIER.test(name);
139
264
  }
140
- //#endregion
141
- //#region src/operations/api.ts
142
265
  /**
143
- * Reads a human-readable message from a Studio JSON error body, when it has one. `FetchError`'s own
144
- * message stops at the status line, so the detail Studio sends with a failure (an agent limit, a
145
- * revoked token) would otherwise never reach the user.
266
+ * Dynamically imports a `@kubb/plugin-*` package and returns its factory function.
267
+ *
268
+ * Packages must be pre-installed in the Docker image at build time via the `KUBB_PACKAGES`
269
+ * build ARG, no runtime installation is possible in the distroless container.
270
+ *
271
+ * Resolution order: the camelCase named export the package name implies (e.g. `pluginTs`), then
272
+ * the default export.
273
+ *
274
+ * @throws if the package cannot be imported or exports no callable factory.
146
275
  */
147
- function responseMessage(data) {
148
- if (!data || typeof data !== "object") return;
149
- const body = data;
150
- for (const value of [
151
- body.error_description,
152
- body.message,
153
- body.error
154
- ]) if (typeof value === "string" && value) return value;
276
+ async function loadPluginFactory(packageName) {
277
+ if (!isKubbPluginSpecifier(packageName)) throw new Error(`Plugin "${packageName}" is not a @kubb/plugin-* package. Kubb Studio only supports Kubb's own plugins.`);
278
+ let mod;
279
+ try {
280
+ mod = await importFromProject(packageName);
281
+ } catch (cause) {
282
+ throw new Error(`Plugin "${packageName}" could not be loaded. Make sure it is installed: \`npm install ${packageName}\``, { cause });
283
+ }
284
+ const exportName = toExportName(packageName);
285
+ if (typeof mod[exportName] === "function") return mod[exportName];
286
+ if (typeof mod["default"] === "function") return mod["default"];
287
+ throw new Error(`Plugin "${packageName}" does not export a callable factory. Tried the named export "${exportName}" and "default".`);
155
288
  }
156
289
  /**
157
- * Thrown when Studio rejects the agent token itself (401). Retrying cannot help: the token was
158
- * revoked, or the agent it belonged to was deleted in the Studio UI. Hosts catch this to forget
159
- * the stored credential and pair again.
290
+ * Resolves each plugin entry by dynamically importing the `@kubb/plugin-*` package and
291
+ * calling its factory with the provided options.
292
+ *
293
+ * Packages must be pre-installed in the Docker image at build time, use the `KUBB_PACKAGES`
294
+ * build ARG to control which ones are available at runtime.
295
+ *
296
+ * @example
297
+ * ```ts
298
+ * { name: '@kubb/plugin-react-query', options: { output: { path: './hooks' } } }
299
+ * { name: '@kubb/plugin-ts', options: { output: { path: './types' } } }
300
+ * ```
160
301
  */
161
- var InvalidAgentTokenError = class extends Error {
162
- constructor(studioUrl, options) {
163
- super(`Kubb Studio rejected this agent's token. It was revoked or the agent was deleted in ${studioUrl}.`, options);
164
- this.name = "InvalidAgentTokenError";
302
+ async function resolvePlugins(plugins) {
303
+ return Promise.all(plugins.map(async ({ name, options }) => {
304
+ return (await loadPluginFactory(name))(options ?? {});
305
+ }));
306
+ }
307
+ /** The installed version of each plugin's package, plus the names that could not be resolved. */
308
+ async function resolvePeerDependencies(names) {
309
+ const require = createRequire(import.meta.url);
310
+ const uniqueNames = [...new Set(names.map(toPackageName))];
311
+ const peerDependencies = {};
312
+ const missingDependencies = [];
313
+ const versions = await Promise.all(uniqueNames.map(async (name) => {
314
+ try {
315
+ const path = require.resolve(`${name}/package.json`);
316
+ return JSON.parse(await readFile(path, "utf8")).version;
317
+ } catch {
318
+ return;
319
+ }
320
+ }));
321
+ for (const [index, name] of uniqueNames.entries()) {
322
+ const version = versions[index];
323
+ if (version) {
324
+ peerDependencies[name] = version;
325
+ continue;
326
+ }
327
+ missingDependencies.push(name);
165
328
  }
166
- };
329
+ return {
330
+ peerDependencies,
331
+ missingDependencies
332
+ };
333
+ }
167
334
  /**
168
- * Thrown when Studio refuses this agent's protocol version (426). Retrying cannot help until the
169
- * agent is upgraded, so hosts stop instead of reconnecting.
335
+ * Whether `value` is an object literal or a null-prototype object, not an array or class instance.
170
336
  */
171
- var IncompatibleAgentError = class extends Error {
172
- constructor(studioUrl, detail, options) {
173
- super(`Kubb Studio at ${studioUrl} requires a newer agent${detail ? `: ${detail}` : ""}. Upgrade @kubb/studio or the Kubb agent image.`, options);
174
- this.name = "IncompatibleAgentError";
337
+ function isPlainObject(value) {
338
+ if (typeof value !== "object" || value === null) return false;
339
+ const prototype = Object.getPrototypeOf(value);
340
+ return prototype === null || prototype === Object.prototype;
341
+ }
342
+ /**
343
+ * Whether `value` survives a JSON round trip, so it can be printed into a config file as a literal.
344
+ * A function, `undefined`, a non-finite number or a class instance comes back from Studio as a
345
+ * lossy copy, so an edit carrying one is refused rather than written into the user's source.
346
+ */
347
+ function isOptionValue(value) {
348
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
349
+ if (typeof value === "number") return Number.isFinite(value);
350
+ if (Array.isArray(value)) return value.every(isOptionValue);
351
+ if (isPlainObject(value)) return Object.values(value).every(isOptionValue);
352
+ return false;
353
+ }
354
+ /**
355
+ * Deep-merges Studio's options over the disk options, with Studio taking priority, except where the
356
+ * disk value cannot survive JSON. Studio only ever saw a lossy copy of such a value, so the disk
357
+ * value is kept rather than replaced by what Studio echoes back. Plain objects merge key by key, so
358
+ * Studio can still change a literal that sits next to a function (e.g. `group.type` beside `group.name`).
359
+ *
360
+ * @example
361
+ * ```ts
362
+ * mergeOptions({ macros: [camelCaseMacro], syntaxType: 'type' }, { macros: [{ name: 'camelCase' }], syntaxType: 'interface' })
363
+ * // { macros: [camelCaseMacro], syntaxType: 'interface' }
364
+ * ```
365
+ */
366
+ function mergeOptions(disk, studio) {
367
+ const merged = { ...disk };
368
+ for (const [key, value] of Object.entries(studio)) {
369
+ const current = disk[key];
370
+ if (isPlainObject(current) && isPlainObject(value)) {
371
+ merged[key] = mergeOptions(current, value);
372
+ continue;
373
+ }
374
+ if (current !== void 0 && !isOptionValue(current)) continue;
375
+ merged[key] = value;
175
376
  }
176
- };
377
+ return merged;
378
+ }
177
379
  /**
178
- * Whether a thrown value carries `statusCode`. Not narrowed to `FetchError`: a host wrapper can
179
- * throw its own error shape with the same field.
380
+ * Merges studio plugin options with disk config plugins.
381
+ * Studio takes priority: options from studio win over disk (except values only the disk config
382
+ * can express, see {@link mergeOptions}), and a plugin Studio explicitly
383
+ * disabled is dropped even when the disk config still lists it. Disk plugins without a studio
384
+ * counterpart are kept as-is. Studio plugins not present on disk are appended.
385
+ *
386
+ * For plugins present in both configs, the plugin is re-instantiated with merged options
387
+ * so that all internal closures correctly reference the merged values.
180
388
  */
181
- function rejectedWith(error, statusCode) {
182
- return error?.statusCode === statusCode;
389
+ async function mergePlugins(diskPlugins, studioPlugins) {
390
+ const disabledNames = new Set((studioPlugins ?? []).filter((entry) => entry.disabled).map((entry) => toPluginName(entry.name)));
391
+ const activeDiskPlugins = disabledNames.size ? diskPlugins?.filter((plugin) => !disabledNames.has(plugin.name)) : diskPlugins;
392
+ const activeStudioPlugins = studioPlugins?.filter((entry) => !entry.disabled);
393
+ if (!activeDiskPlugins && !activeStudioPlugins?.length) return void 0;
394
+ if (!activeStudioPlugins?.length) return activeDiskPlugins;
395
+ if (!activeDiskPlugins) return resolvePlugins(activeStudioPlugins);
396
+ const studioEntryByName = new Map(activeStudioPlugins.map((entry) => [toPluginName(entry.name), entry]));
397
+ const diskNames = new Set(activeDiskPlugins.map((plugin) => plugin.name));
398
+ const merged = await Promise.all(activeDiskPlugins.map(async (diskPlugin) => {
399
+ const studioEntry = studioEntryByName.get(diskPlugin.name);
400
+ if (!studioEntry) return diskPlugin;
401
+ const options = mergeOptions(diskPlugin.options ?? {}, studioEntry.options ?? {});
402
+ const [resolved] = await resolvePlugins([{
403
+ name: studioEntry.name,
404
+ options
405
+ }]);
406
+ return resolved ?? diskPlugin;
407
+ }));
408
+ const studioOnly = activeStudioPlugins.filter((entry) => !diskNames.has(toPluginName(entry.name)));
409
+ return [...merged, ...await resolvePlugins(studioOnly)];
183
410
  }
184
- function registrationError(cause) {
185
- const detail = (cause instanceof FetchError ? responseMessage(cause.data) : void 0) ?? getErrorMessage(cause);
186
- return new Error(detail ? `Failed to register with Kubb Studio: ${detail}` : "Failed to register with Kubb Studio", { cause });
411
+ /**
412
+ * Merges Studio-provided adapter option overrides into the disk config's adapter.
413
+ *
414
+ * Adapter instances carry live functions (`parse`, `getImports`, ...) that can't survive
415
+ * JSON serialization over the WebSocket, so `studioOptions` is treated as an options patch
416
+ * rather than a replacement adapter. Re-invokes the same `@kubb/adapter-<name>` factory the
417
+ * disk config used, with the merged options, so the resulting instance has fresh closures
418
+ * over the merged values instead of a plain object missing `parse`.
419
+ */
420
+ async function mergeAdapter(diskAdapter, studioOptions) {
421
+ if (!studioOptions || !diskAdapter) return diskAdapter;
422
+ const packageName = `@kubb/adapter-${diskAdapter.name}`;
423
+ const factory = (await importFromProject(packageName))[toExportName(packageName)];
424
+ if (typeof factory !== "function") return diskAdapter;
425
+ return factory(mergeOptions(diskAdapter.options ?? {}, studioOptions));
187
426
  }
427
+ //#endregion
428
+ //#region src/configFile.ts
188
429
  /**
189
- * Registers this agent process with Kubb Studio (`POST /api/agent/connect`): binds the machine
190
- * identity to the token, reports what the process can take on, and gets back the URL of the one
191
- * socket it keeps open.
430
+ * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
431
+ * never as source that breaks out of the import statement.
432
+ */
433
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
434
+ /**
435
+ * `key: value` as an object literal property, in the file's quote and key style.
192
436
  *
193
- * Makes one bounded attempt; `runConnection` owns retries. A rejected token (401) throws
194
- * {@link InvalidAgentTokenError} and an unsupported agent version (426) throws
195
- * {@link IncompatibleAgentError}, since retrying either cannot help.
437
+ * Uses magicast's literal builder for the key/value nodes, then wraps them as a Babel
438
+ * `ObjectProperty`, the type the rest of this file reads.
196
439
  */
197
- async function registerAgent({ token, studioUrl, instanceId, capacity, signal }) {
198
- const body = {
199
- machineToken: await getMachineToken(),
200
- instanceId,
201
- capacity
440
+ function literalProperty({ key, value }) {
441
+ const built = builders.literal({ [key]: value }).properties[0];
442
+ return {
443
+ type: "ObjectProperty",
444
+ key: built.key,
445
+ value: built.value,
446
+ computed: false,
447
+ shorthand: false
202
448
  };
203
- try {
204
- return await ofetch(`${studioUrl}/api/agent/connect`, {
205
- method: "POST",
206
- headers: { Authorization: `Bearer ${token}` },
207
- body,
208
- retry: 0,
209
- timeout: 1e4,
210
- signal
211
- });
212
- } catch (error) {
213
- if (rejectedWith(error, 401)) throw new InvalidAgentTokenError(studioUrl, { cause: error });
214
- if (rejectedWith(error, 426)) throw new IncompatibleAgentError(studioUrl, error instanceof FetchError ? responseMessage(error.data) : void 0, { cause: error });
215
- throw registrationError(error);
216
- }
217
449
  }
218
450
  /**
219
- * First wait before `createJob` retries a busy or queue-full response, absent a `Retry-After` hint.
451
+ * Marks the comment block a `disable-plugin` leaves behind, so `enable-plugin` can find its way
452
+ * back to the exact lines it commented out. Carries the block's line count, so `enable-plugin`
453
+ * restores exactly those lines instead of scanning forward through whatever comments follow.
454
+ */
455
+ const DISABLED_MARKER = "kubb:disabled";
456
+ /**
457
+ * The plugin and comment-block length a marker line names, when `line` is one.
458
+ */
459
+ function parseMarker(line) {
460
+ const trimmed = line.trim();
461
+ if (!trimmed.startsWith(`// ${DISABLED_MARKER} `)) return;
462
+ const match = trimmed.slice(`// ${DISABLED_MARKER} `.length).match(/^(.+)\s+(\d+)$/);
463
+ return match ? {
464
+ plugin: match[1],
465
+ lineCount: Number(match[2])
466
+ } : void 0;
467
+ }
468
+ /**
469
+ * Steps through a config's wrappers to the object literal underneath: a `satisfies`/`as`
470
+ * assertion, a `() => ...` factory, or a factory whose block body returns the config.
220
471
  */
221
- const CREATE_JOB_INITIAL_DELAY_MS = 1e3;
472
+ function unwrap(node) {
473
+ if (!node) return;
474
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") return unwrap(node.expression);
475
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression") return node;
476
+ if (node.body.type !== "BlockStatement") return unwrap(node.body);
477
+ return unwrap(node.body.body.find((statement) => statement.type === "ReturnStatement")?.argument);
478
+ }
222
479
  /**
223
- * Slowest `createJob` backs off to between retries.
480
+ * Every config object in `export default defineConfig(...)`, or why the file is unmanaged.
481
+ *
482
+ * An array export gets one entry per element, matching {@link ConfigRef}'s numeric index.
483
+ *
484
+ * Walks the parsed AST rather than magicast's proxies, which throw on node types they cannot
485
+ * cast, most of what an unmanaged config file is made of.
224
486
  */
225
- const CREATE_JOB_MAX_INTERVAL_MS = 1e4;
487
+ function findConfigs(mod) {
488
+ const exported = unwrap((mod.$ast.type === "Program" ? mod.$ast.body : []).find((node) => node.type === "ExportDefaultDeclaration")?.declaration);
489
+ if (!exported) return { reason: "no default export found" };
490
+ if (exported.type !== "CallExpression" || exported.callee.type !== "Identifier" || exported.callee.name !== "defineConfig") return { reason: "default export is not a defineConfig(...) call" };
491
+ const argument = unwrap(exported.arguments[0]);
492
+ if (!argument) return { reason: "defineConfig(...) was called without a config" };
493
+ if (argument.type === "ArrayExpression") {
494
+ const configs = [];
495
+ for (const element of argument.elements) {
496
+ const entry = unwrap(element);
497
+ if (entry?.type !== "ObjectExpression") return { reason: "config is not an object literal" };
498
+ configs.push(entry);
499
+ }
500
+ return { configs };
501
+ }
502
+ if (argument.type !== "ObjectExpression") return { reason: "config is not an object literal" };
503
+ return { configs: [argument] };
504
+ }
226
505
  /**
227
- * Statuses worth retrying: the agent has no free connection yet (409, a stale conflict a moment
228
- * later resolves), its queue is momentarily full (429), or it has no live connection at all yet
229
- * (503, an agent process that is mid-reconnect). Anything else (404 agent not found, 401/403 auth)
230
- * is thrown straight away, since retrying cannot change the outcome.
506
+ * The config entry an edit names, defaulting to the first when it names none.
231
507
  */
232
- const CREATE_JOB_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
233
- 409,
234
- 429,
235
- 503
236
- ]);
508
+ function selectConfig(configs, ref) {
509
+ if (ref === void 0) return configs[0];
510
+ if (typeof ref === "number") return configs[ref];
511
+ return configs.find((config) => configName(config) === ref);
512
+ }
513
+ function configName(config) {
514
+ const name = property(config, "name");
515
+ return name?.type === "StringLiteral" ? name.value : void 0;
516
+ }
517
+ /**
518
+ * The name of an object literal property, for the two key shapes a config uses: `key: value` and
519
+ * `'key': value`. `undefined` for a computed key, which the patcher never touches.
520
+ */
521
+ function propertyKey(entry) {
522
+ if (entry.key.type === "Identifier") return entry.key.name;
523
+ if (entry.key.type === "StringLiteral") return entry.key.value;
524
+ }
237
525
  /**
238
- * Reads Studio's `Retry-After` header (seconds) off a thrown `ofetch` error, when present.
526
+ * The index of an object literal's own property named `key`, `-1` when it has none.
239
527
  */
240
- function retryAfterMs(error) {
241
- const seconds = Number(error.response?.headers.get("retry-after"));
242
- return Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : void 0;
528
+ function entryIndex({ node, key }) {
529
+ return node.properties.findIndex((entry) => entry.type === "ObjectProperty" && propertyKey(entry) === key);
243
530
  }
244
531
  /**
245
- * Adds up to 30% jitter, so every CI run queued behind the same busy agent does not retry in
246
- * lockstep.
532
+ * The value node of an object literal's own property.
247
533
  */
248
- function withJitter(ms) {
249
- return ms + Math.random() * ms * .3;
534
+ function property(node, key) {
535
+ const index = entryIndex({
536
+ node,
537
+ key
538
+ });
539
+ return index === -1 ? void 0 : node.properties[index].value;
250
540
  }
251
541
  /**
252
- * Queues a generation or snapshot job on Studio (`POST /api/jobs`).
542
+ * Writes `key: value` on an object literal, replacing the value when the property is already there.
253
543
  *
254
- * Returns as soon as Studio accepts the job (`202`). Poll with {@link waitForJob} until it finishes.
255
- * Authenticates with the organization CI API key via `x-api-key`.
544
+ * An existing property has its value swapped in place rather than being replaced whole, so recast
545
+ * reprints only that value and leaves the object's own layout alone.
546
+ */
547
+ function setProperty({ node, key, value }) {
548
+ const entry = literalProperty({
549
+ key,
550
+ value
551
+ });
552
+ const index = entryIndex({
553
+ node,
554
+ key
555
+ });
556
+ if (index === -1) {
557
+ node.properties.push(entry);
558
+ return;
559
+ }
560
+ node.properties[index].value = entry.value;
561
+ }
562
+ /**
563
+ * Drops `key` from an object literal.
564
+ */
565
+ function removeProperty({ node, key }) {
566
+ const index = entryIndex({
567
+ node,
568
+ key
569
+ });
570
+ if (index !== -1) node.properties.splice(index, 1);
571
+ }
572
+ /**
573
+ * Reads a literal node's value: a primitive, or an object/array built only from primitives.
574
+ * `undefined` for anything else, so a caller can use this both to read a value and to check
575
+ * whether a node is a literal at all.
576
+ */
577
+ function readLiteral(node) {
578
+ if (!node) return;
579
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return node.value;
580
+ if (node.type === "NullLiteral") return null;
581
+ if (node.type === "TemplateLiteral") return node.expressions.length === 0 ? node.quasis[0]?.value.cooked ?? "" : void 0;
582
+ if (node.type === "UnaryExpression") {
583
+ const value = readLiteral(node.argument);
584
+ if (typeof value !== "number") return;
585
+ if (node.operator === "-") return -value;
586
+ if (node.operator === "+") return value;
587
+ return;
588
+ }
589
+ if (node.type === "ArrayExpression") {
590
+ const values = node.elements.map((element) => element ? readLiteral(element) : void 0);
591
+ return values.every((value) => value !== void 0) ? values : void 0;
592
+ }
593
+ if (node.type === "ObjectExpression") {
594
+ const entries = {};
595
+ for (const entry of node.properties) {
596
+ if (entry.type !== "ObjectProperty") return;
597
+ const key = propertyKey(entry);
598
+ const value = readLiteral(entry.value);
599
+ if (key === void 0 || value === void 0) return;
600
+ entries[key] = value;
601
+ }
602
+ return entries;
603
+ }
604
+ }
605
+ /**
606
+ * Maps a factory identifier in the file back to the module it was imported from.
607
+ */
608
+ function importedFrom(mod) {
609
+ return new Map(mod.imports.$items.map((item) => [item.local, item.from]));
610
+ }
611
+ /**
612
+ * Every `pluginX(...)` element of a config's plugins array that resolves to an import.
613
+ */
614
+ function pluginCalls(mod, config) {
615
+ const plugins = property(config, "plugins");
616
+ if (plugins?.type !== "ArrayExpression") return [];
617
+ const imports = importedFrom(mod);
618
+ return plugins.elements.flatMap((element) => {
619
+ if (element?.type !== "CallExpression" || element.callee.type !== "Identifier") return [];
620
+ const packageName = imports.get(element.callee.name);
621
+ return packageName ? [{
622
+ importName: element.callee.name,
623
+ packageName,
624
+ call: element
625
+ }] : [];
626
+ });
627
+ }
628
+ /**
629
+ * Plugins a previous `disable-plugin` commented out of this config, keyed by package name.
256
630
  *
257
- * A busy agent, a full queue, or a momentary lack of a live connection (409, 429, 503) retries with
258
- * exponential backoff and jitter, honoring Studio's `Retry-After` header when it sends one, up to
259
- * `timeoutMs`. Every other failure, including a missing agent (404), throws immediately.
631
+ * Read from the marker lines rather than the AST, since a commented-out call is no longer a node.
632
+ */
633
+ function disabledMarkers(source) {
634
+ return source.split("\n").flatMap((line, index) => {
635
+ const marker = parseMarker(line);
636
+ return marker ? [{
637
+ packageName: marker.plugin,
638
+ line: index + 1
639
+ }] : [];
640
+ });
641
+ }
642
+ /**
643
+ * Reads which plugins the file declares and which of their options Studio may write.
260
644
  *
261
- * @example Snapshot job
645
+ * @example
262
646
  * ```ts
263
- * const job = await createJob({
264
- * studioUrl: 'https://kubb.studio',
265
- * token: process.env.KUBB_TOKEN!,
266
- * type: 'snapshot',
267
- * agentId: agent.id,
268
- * name: '@kubb/demo',
269
- * version: '1.0.0',
270
- * })
271
- * const finished = await waitForJob({ studioUrl, token, id: job.id })
647
+ * const view = readConfig(await readFile('kubb.config.ts', 'utf8'))
648
+ * if (view.managed) {
649
+ * view.configs.forEach((config) => console.log(config.name, config.plugins.length))
650
+ * }
272
651
  * ```
273
652
  */
274
- async function createJob({ studioUrl, token, type, agentId, name, version, commit, baseId, config, instanceId, timeoutMs = 6e4, signal }) {
275
- const deadline = Date.now() + timeoutMs;
276
- let interval = CREATE_JOB_INITIAL_DELAY_MS;
277
- for (;;) {
278
- signal?.throwIfAborted();
279
- try {
280
- const { job } = await ofetch(`${studioUrl}/api/jobs`, {
281
- method: "POST",
282
- headers: { "x-api-key": token },
283
- body: {
284
- type,
285
- agentId,
286
- name,
287
- version,
288
- commit,
289
- baseId,
290
- config,
291
- instanceId
292
- },
293
- retry: false,
294
- timeout: Math.max(deadline - Date.now(), 1),
295
- signal
653
+ function readConfig(source) {
654
+ const parsed = parseConfigs(source);
655
+ if ("reason" in parsed) return {
656
+ managed: false,
657
+ reason: parsed.reason
658
+ };
659
+ const { mod, configs } = parsed;
660
+ const importNames = new Map([...importedFrom(mod)].map(([local, from]) => [from, local]));
661
+ const disabled = disabledMarkers(source);
662
+ return {
663
+ managed: true,
664
+ configs: configs.map((config) => {
665
+ const plugins = pluginCalls(mod, config).map(({ importName, packageName, call }) => {
666
+ const entries = {};
667
+ const options = call.arguments[0];
668
+ if (options?.type === "ObjectExpression") for (const entry of options.properties) {
669
+ if (entry.type !== "ObjectProperty") continue;
670
+ const key = propertyKey(entry);
671
+ if (key === void 0) continue;
672
+ const value = readLiteral(entry.value);
673
+ entries[key] = value === void 0 ? { literal: false } : {
674
+ literal: true,
675
+ value
676
+ };
677
+ }
678
+ return {
679
+ importName,
680
+ packageName,
681
+ options: entries
682
+ };
296
683
  });
297
- return job;
298
- } catch (error) {
299
- signal?.throwIfAborted();
300
- const status = error.response?.status;
301
- if (!status || !CREATE_JOB_RETRYABLE_STATUSES.has(status) || Date.now() >= deadline) throw error;
302
- const wait = Math.min(retryAfterMs(error) ?? withJitter(interval), Math.max(deadline - Date.now(), 0));
303
- if (signal) await setTimeout$1(wait, void 0, { signal });
304
- else await new Promise((resolve) => setTimeout(resolve, wait));
305
- if (Date.now() >= deadline) throw error;
306
- interval = Math.min(interval * 2, CREATE_JOB_MAX_INTERVAL_MS);
307
- }
308
- }
684
+ const start = config.loc?.start.line ?? 0;
685
+ const end = config.loc?.end.line ?? Number.POSITIVE_INFINITY;
686
+ for (const { packageName } of disabled.filter((entry) => entry.line >= start && entry.line <= end)) plugins.push({
687
+ importName: importNames.get(packageName) ?? toExportName(packageName),
688
+ packageName,
689
+ options: {},
690
+ disabled: true
691
+ });
692
+ return {
693
+ name: configName(config),
694
+ plugins
695
+ };
696
+ })
697
+ };
309
698
  }
310
699
  /**
311
- * A job runs a generation and packs a tarball, so it is never done the instant it is queued.
700
+ * The options object of a plugin call, when it was called with one.
312
701
  */
313
- const INITIAL_POLL_DELAY_MS = 2e3;
702
+ function getOptions(call) {
703
+ const options = call.arguments[0];
704
+ return options?.type === "ObjectExpression" ? options : void 0;
705
+ }
314
706
  /**
315
- * Slowest the poll backs off to. Requests per run are roughly `timeoutMs` divided by this, and
316
- * every concurrent run on the same organization key draws on one budget.
707
+ * The options object of a plugin call, creating an empty one when the plugin was called bare.
317
708
  */
318
- const MAX_POLL_INTERVAL_MS = 3e4;
709
+ function ensureOptions(call) {
710
+ if (call.arguments.length === 0) call.arguments.push({
711
+ type: "ObjectExpression",
712
+ properties: []
713
+ });
714
+ return getOptions(call);
715
+ }
319
716
  /**
320
- * Polls `GET /api/jobs/{id}` until the job reaches a terminal status, waiting
321
- * {@link INITIAL_POLL_DELAY_MS} first and doubling up to {@link MAX_POLL_INTERVAL_MS} so a long
322
- * job stays inside the API key's rate limit.
323
- *
324
- * A `failed` job resolves normally. Check `job.status` and `job.error`. Throws only when the
325
- * deadline passes before Studio finishes.
326
- */
327
- async function waitForJob({ studioUrl, token, id, timeoutMs = 6e4, signal }) {
328
- const deadline = Date.now() + timeoutMs;
329
- let interval = INITIAL_POLL_DELAY_MS;
330
- for (;;) {
331
- signal?.throwIfAborted();
332
- const wait = Math.max(Math.min(interval, deadline - Date.now()), 0);
333
- if (signal) await setTimeout$1(wait, void 0, { signal });
334
- else await new Promise((resolve) => setTimeout(resolve, wait));
335
- if (Date.now() >= deadline) throw new Error("Timed out waiting for the Studio job");
336
- interval = Math.min(interval * 2, MAX_POLL_INTERVAL_MS);
337
- try {
338
- const { job } = await ofetch(`${studioUrl}/api/jobs/${id}`, {
339
- headers: { "x-api-key": token },
340
- retry: false,
341
- timeout: Math.max(deadline - Date.now(), 1),
342
- signal
343
- });
344
- if (job.status === "success" || job.status === "failed" || job.status === "canceled") return job;
345
- } catch (error) {
346
- signal?.throwIfAborted();
347
- const response = error.response;
348
- if (response?.status !== 429) throw error;
349
- const retryAfter = response._data?.data?.tryAgainIn;
350
- interval = Math.max(interval, typeof retryAfter === "number" && Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : MAX_POLL_INTERVAL_MS);
351
- }
717
+ * Walks `path` down to the object holding its last key, descending only through object literals.
718
+ */
719
+ function optionParent(options, path) {
720
+ let object = options;
721
+ for (const [index, key] of path.entries()) {
722
+ if (index === path.length - 1) return {
723
+ object,
724
+ key
725
+ };
726
+ if (property(object, key) === void 0) setProperty({
727
+ node: object,
728
+ key,
729
+ value: {}
730
+ });
731
+ const next = property(object, key);
732
+ if (next?.type !== "ObjectExpression") return { reason: `${key} is not an object, so ${path.join(".")} cannot be reached` };
733
+ object = next;
352
734
  }
735
+ return { reason: "no option path given" };
353
736
  }
354
737
  /**
355
- * Creates or reuses a CI agent (`POST /api/agents`), keyed by `(organization, machineToken)`.
356
- * Authenticates via `x-api-key`. Reusing the same `machineToken` reuses the same agent instead of
357
- * consuming a new one from the organization's agent limit.
738
+ * Writes `value` at `path` inside a plugin call's options, creating the options object and any
739
+ * intermediate object along the path as needed. Refuses when the current value at `path` is
740
+ * something other than a literal, so an option customized in code is never overwritten.
358
741
  */
359
- async function createAgent({ studioUrl, token, name, machineToken }) {
360
- try {
361
- return await ofetch(`${studioUrl}/api/agents`, {
362
- method: "POST",
363
- headers: { "x-api-key": token },
364
- body: {
365
- name,
366
- machineToken
367
- }
368
- });
369
- } catch (error) {
370
- if (error instanceof FetchError) {
371
- const upgradeUrl = error.data?.data?.upgradeUrl;
372
- const detail = responseMessage(error.data) ?? getErrorMessage(error);
373
- const hint = upgradeUrl ? ` Agent limit reached; upgrade at ${upgradeUrl}.` : "";
374
- throw new Error(`Failed to create a Kubb Studio agent: ${detail}${hint}`, { cause: error });
375
- }
376
- throw error;
742
+ function applySet(call, path, value) {
743
+ if (!isOptionValue(value)) return "the value is not a literal that can be written to a config file";
744
+ const options = ensureOptions(call);
745
+ if (!options) return "the plugin was not called with an object literal";
746
+ const target = optionParent(options, path);
747
+ if ("reason" in target) return target.reason;
748
+ const current = property(target.object, target.key);
749
+ if (current !== void 0 && readLiteral(current) === void 0) return `${path.join(".")} is customized in code`;
750
+ setProperty({
751
+ node: target.object,
752
+ key: target.key,
753
+ value
754
+ });
755
+ }
756
+ /**
757
+ * Deletes the property at `path` inside a plugin call's options, falling the plugin back to its
758
+ * default for that option. Refuses when the value at `path` is not a literal, for the same reason
759
+ * `applySet` does.
760
+ */
761
+ function applyRemove(call, path) {
762
+ const options = getOptions(call);
763
+ if (!options) return "the plugin has no options to remove";
764
+ const target = optionParent(options, path);
765
+ if ("reason" in target) return target.reason;
766
+ const current = property(target.object, target.key);
767
+ if (current === void 0) return `${path.join(".")} is not set`;
768
+ if (readLiteral(current) === void 0) return `${path.join(".")} is customized in code`;
769
+ removeProperty({
770
+ node: target.object,
771
+ key: target.key
772
+ });
773
+ }
774
+ /**
775
+ * Adds a `pluginX(...)` call to a config's plugins array. Replaying the same add is a no-op, while
776
+ * an import name collision with an unrelated package remains an error.
777
+ */
778
+ function applyAddPlugin(mod, config, edit) {
779
+ if (!isKubbPluginSpecifier(edit.plugin)) return { reason: `"${edit.plugin}" is not a @kubb/plugin-* package` };
780
+ const importName = edit.importName ?? toExportName(edit.plugin);
781
+ if (!IDENTIFIER.test(importName)) return { reason: `"${importName}" is not a valid import name` };
782
+ if (pluginCalls(mod, config).some((plugin) => plugin.packageName === edit.plugin)) return { noop: true };
783
+ const taken = importedFrom(mod).get(importName);
784
+ if (taken && taken !== edit.plugin) return { reason: `${importName} is already imported from ${taken}` };
785
+ const options = edit.options ?? {};
786
+ if (!isOptionValue(options)) return { reason: "the options are not literals that can be written to a config file" };
787
+ const plugins = property(config, "plugins");
788
+ if (plugins?.type !== "ArrayExpression") return { reason: "plugins is not an array literal" };
789
+ const call = Object.keys(options).length ? builders.functionCall(importName, options) : builders.functionCall(importName);
790
+ plugins.elements.push(call.$ast);
791
+ return taken ? {} : { addImport: {
792
+ importName,
793
+ moduleSpecifier: edit.plugin
794
+ } };
795
+ }
796
+ /**
797
+ * Comments out a plugin call in place, keeping its options on disk so `enable-plugin` can restore
798
+ * them exactly. Operates on `source` text rather than the AST: a commented-out call is no longer a
799
+ * node magicast can address, and the surrounding array must not reflow when its element count
800
+ * never actually changes.
801
+ */
802
+ function disablePlugin(source, mod, config, plugin) {
803
+ const target = pluginCalls(mod, config).find((entry) => entry.packageName === plugin);
804
+ if (!target) return { reason: `${plugin} is not in the plugins array` };
805
+ const loc = target.call.loc;
806
+ if (!loc?.start || !loc.end) return { reason: `${plugin} has no source location to comment out` };
807
+ const lines = source.split("\n");
808
+ const from = loc.start.line - 1;
809
+ const to = loc.end.line - 1;
810
+ const firstLine = lines[from] ?? "";
811
+ const lastLine = lines[to] ?? "";
812
+ if (firstLine.slice(0, loc.start.column).trim() !== "" || !/^,?\s*$/.test(lastLine.slice(loc.end.column))) return { reason: `${plugin} shares a line with other code, so it cannot be commented out safely` };
813
+ const indent = firstLine.match(/^\s*/)?.[0] ?? "";
814
+ const commented = lines.slice(from, to + 1).map((line) => line.trim() ? `${indent}// ${line.slice(indent.length)}` : indent ? `${indent}//` : "//");
815
+ lines.splice(from, to - from + 1, `${indent}// ${DISABLED_MARKER} ${plugin} ${commented.length}`, ...commented);
816
+ return { source: lines.join("\n") };
817
+ }
818
+ /**
819
+ * Uncomments the block a previous `disable-plugin` left behind for `plugin`.
820
+ */
821
+ function enablePlugin(source, plugin) {
822
+ const lines = source.split("\n");
823
+ for (const [index, line] of lines.entries()) {
824
+ const marker = parseMarker(line);
825
+ if (marker?.plugin !== plugin) continue;
826
+ const end = index + 1 + marker.lineCount;
827
+ const restored = lines.slice(index + 1, end).map((commented) => commented.replace(/^(\s*)\/\/ ?/, "$1"));
828
+ lines.splice(index, end - index, ...restored);
829
+ return { source: lines.join("\n") };
377
830
  }
831
+ return { reason: `${plugin} is not disabled` };
378
832
  }
379
- //#endregion
380
- //#region src/operations/constants.ts
381
833
  /**
382
- * Hosted Kubb Studio URL. Exported so credential stores can bind tokens to the resolved instance,
383
- * not whatever default the client would pick on its own.
834
+ * Parses `source` and finds the config entries it exports.
384
835
  */
385
- const defaultStudioUrl = "https://kubb.studio";
836
+ function parseConfigs(source) {
837
+ let mod;
838
+ try {
839
+ mod = parseModule(source);
840
+ } catch {
841
+ return { reason: "the config file could not be parsed" };
842
+ }
843
+ const found = findConfigs(mod);
844
+ return "reason" in found ? found : {
845
+ mod,
846
+ configs: found.configs
847
+ };
848
+ }
386
849
  /**
387
- * Defaults the Studio client uses when a host passes nothing.
388
- * Config path is left out on purpose: each host discovers that itself.
850
+ * Re-parses `source` and resolves the config entry an edit targets. Every edit re-parses rather
851
+ * than sharing one module across the batch, since the disable/enable edits rewrite `source` as
852
+ * text and would otherwise leave the others working from a stale tree.
389
853
  */
390
- const agentDefaults = {
391
- studioUrl: defaultStudioUrl,
392
- retryIntervalMs: 3e4,
393
- heartbeatIntervalMs: 3e4,
394
- /**
395
- * Slowest heartbeat a host may ask for. Studio drops an agent from the active list once its
396
- * stored ping is older than its liveness window, and it persists a ping at most once an hour,
397
- * so a slower cadence would make a healthy agent look dead after a single missed ping.
398
- */
399
- maxHeartbeatIntervalMs: 6e4,
400
- /** How long a heartbeat ping may take before the session is treated as dead. */
401
- heartbeatTimeoutMs: 1e4,
402
- maxConcurrent: 1,
403
- maxGenerations: 8,
404
- maxGenerationsMb: 100,
405
- maxSnapshotMb: 50
406
- };
407
- function positiveNumber(value) {
408
- const parsed = Number(value);
409
- return value && Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
854
+ function parseTarget(source, ref) {
855
+ const parsed = parseConfigs(source);
856
+ if ("reason" in parsed) return parsed;
857
+ const config = selectConfig(parsed.configs, ref);
858
+ if (!config) return { reason: `no config entry found for ${JSON.stringify(ref)}` };
859
+ return {
860
+ mod: parsed.mod,
861
+ config
862
+ };
410
863
  }
411
864
  /**
412
- * How many generations an agent keeps and how large they may get, read from
413
- * `KUBB_AGENT_MAX_GENERATIONS`, `KUBB_AGENT_MAX_GENERATIONS_MB` and `KUBB_AGENT_MAX_SNAPSHOT_MB`.
414
- * An unset or invalid value keeps the default.
865
+ * Applies edits to a `kubb.config.ts` in place. Every node the edits do not touch keeps its
866
+ * original text, so comments, formatting, and hand-written code around the config survive.
867
+ *
868
+ * Edits are independent: one that cannot be applied is reported in `outcomes` and the rest still run.
869
+ *
870
+ * @example
871
+ * ```ts
872
+ * const { source, outcomes } = applyConfigEdits(current, [
873
+ * { operation: 'set', plugin: '@kubb/plugin-ts', path: ['enum', 'type'], value: 'enum' },
874
+ * ])
875
+ * ```
876
+ *
877
+ * @note recast always reprints a semicolon on a reprinted statement, so editing a block-body
878
+ * `defineConfig` in a semicolon-free file adds one to the `return` line. This is a known gap.
879
+ * Strip it when `detectCodeFormat` reports `useSemi: false`, if it turns out to matter in practice.
415
880
  */
416
- function resolveGenerationLimits(env = process.env) {
881
+ function applyConfigEdits(source, edits) {
882
+ let current = source;
883
+ const format = detectCodeFormat(source);
884
+ const endsWithNewline = source.endsWith("\n");
885
+ const outcomes = edits.map((edit) => {
886
+ const target = parseTarget(current, edit.config);
887
+ if ("reason" in target) return {
888
+ edit,
889
+ applied: false,
890
+ reason: target.reason
891
+ };
892
+ const { mod, config } = target;
893
+ if (edit.operation === "disable-plugin" || edit.operation === "enable-plugin") {
894
+ const result = edit.operation === "disable-plugin" ? disablePlugin(current, mod, config, edit.plugin) : enablePlugin(current, edit.plugin);
895
+ if ("reason" in result) return {
896
+ edit,
897
+ applied: false,
898
+ reason: result.reason
899
+ };
900
+ current = result.source;
901
+ return {
902
+ edit,
903
+ applied: true
904
+ };
905
+ }
906
+ if (edit.operation === "add-plugin") {
907
+ const result = applyAddPlugin(mod, config, edit);
908
+ if ("reason" in result) return {
909
+ edit,
910
+ applied: false,
911
+ reason: result.reason
912
+ };
913
+ if ("noop" in result) return {
914
+ edit,
915
+ applied: true
916
+ };
917
+ const afterLine = lastImportEndLine(mod);
918
+ let next = generateCode(mod, { format }).code;
919
+ if (result.addImport) next = insertImportLine({
920
+ source: next,
921
+ afterLine,
922
+ ...result.addImport
923
+ });
924
+ current = withTrailingNewline(next, endsWithNewline);
925
+ return {
926
+ edit,
927
+ applied: true
928
+ };
929
+ }
930
+ const pluginCall = pluginCalls(mod, config).find((plugin) => plugin.packageName === edit.plugin);
931
+ if (!pluginCall) return {
932
+ edit,
933
+ applied: false,
934
+ reason: `${edit.plugin} is not in the plugins array`
935
+ };
936
+ const reason = edit.operation === "set" ? applySet(pluginCall.call, edit.path, edit.value) : applyRemove(pluginCall.call, edit.path);
937
+ if (!reason) current = withTrailingNewline(generateCode(mod, { format }).code, endsWithNewline);
938
+ return {
939
+ edit,
940
+ applied: !reason,
941
+ reason
942
+ };
943
+ });
417
944
  return {
418
- maxCount: Math.max(1, Math.floor(positiveNumber(env.KUBB_AGENT_MAX_GENERATIONS) ?? agentDefaults.maxGenerations)),
419
- maxMb: positiveNumber(env.KUBB_AGENT_MAX_GENERATIONS_MB) ?? agentDefaults.maxGenerationsMb,
420
- maxSnapshotMb: positiveNumber(env.KUBB_AGENT_MAX_SNAPSHOT_MB) ?? agentDefaults.maxSnapshotMb
945
+ source: current,
946
+ outcomes,
947
+ changed: current !== source
421
948
  };
422
949
  }
950
+ async function writeConfigEdits({ filePath, edits }) {
951
+ const result = applyConfigEdits(await read(filePath), edits);
952
+ if (result.changed) await writeFile(filePath, result.source, "utf-8");
953
+ return result;
954
+ }
423
955
  /**
424
- * An agent's capacity read from `KUBB_AGENT_MAX_CONCURRENT`. An unset or invalid value keeps the
425
- * default: one job at a time.
956
+ * The 1-based line where the file's last import declaration ends, or `0` when it has none. Read
957
+ * off the parsed module, so a multi-line `import {\n x,\n} from '...'` reports its closing line
958
+ * rather than the `import` keyword.
426
959
  */
427
- function resolveAgentCapacity(env = process.env) {
428
- return { maxConcurrent: Math.max(1, Math.floor(positiveNumber(env.KUBB_AGENT_MAX_CONCURRENT) ?? agentDefaults.maxConcurrent)) };
960
+ function lastImportEndLine(mod) {
961
+ return (mod.$ast.type === "Program" ? mod.$ast.body : []).filter((node) => node.type === "ImportDeclaration").at(-1)?.loc?.end.line ?? 0;
962
+ }
963
+ /**
964
+ * Writes an import after the last one already in the file, matching its quote style and whether it
965
+ * ends in a semicolon. `afterLine` is where that last import ends, `0` for a file with none.
966
+ *
967
+ * Written as plain text rather than through magicast's import builder, which prints a brand-new
968
+ * import declaration with its own default spacing and a semicolon regardless of `format`, since
969
+ * that formatting only governs nodes recast can diff against the original source.
970
+ */
971
+ function insertImportLine({ source, importName, moduleSpecifier, afterLine }) {
972
+ const lines = source.split("\n");
973
+ const lastImportLine = afterLine > 0 ? lines[afterLine - 1] : void 0;
974
+ const quote = lastImportLine?.includes(`"`) ? `"` : `'`;
975
+ const line = `import { ${importName} } from ${quote}${moduleSpecifier}${quote}${lastImportLine?.trimEnd().endsWith(";") ? ";" : ""}`;
976
+ lines.splice(afterLine, 0, ...afterLine > 0 ? [line] : [line, ""]);
977
+ return lines.join("\n");
978
+ }
979
+ /**
980
+ * `generateCode` always drops the file's trailing newline. Restore it when the input had one.
981
+ */
982
+ function withTrailingNewline(code, hadTrailingNewline) {
983
+ if (!hadTrailingNewline || code.endsWith("\n")) return code;
984
+ return `${code}\n`;
429
985
  }
430
986
  //#endregion
431
- //#region package.json
432
- var version = "5.6.0";
433
- //#endregion
434
- //#region src/operations/generations.ts
987
+ //#region src/generations.ts
435
988
  const READ_CONCURRENCY = 50;
436
989
  const MB = 1048576;
437
990
  const INDEX_KEY = "studio/generations.json";
@@ -441,8 +994,63 @@ const INDEX_KEY = "studio/generations.json";
441
994
  function relativeStoragePath({ root, filePath }) {
442
995
  return (isAbsolute(filePath) ? relative(resolve(root), filePath) : filePath).replaceAll("\\", "/");
443
996
  }
997
+ /**
998
+ * The content fingerprint Studio compares snapshots by. Agent runs and CI uploads must agree on it.
999
+ */
444
1000
  const hashOf = (content) => createHash("sha1").update(content).digest("hex").slice(0, 16);
445
1001
  const totalBytes = (entries) => entries.reduce((sum, { output, disk }) => sum + output.bytes + (disk?.bytes ?? 0), 0);
1002
+ function positiveNumber(value) {
1003
+ const parsed = Number(value);
1004
+ return value && Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
1005
+ }
1006
+ /**
1007
+ * How many generations an agent keeps and how large they may get, read from
1008
+ * `KUBB_AGENT_MAX_GENERATIONS`, `KUBB_AGENT_MAX_GENERATIONS_MB` and `KUBB_AGENT_MAX_SNAPSHOT_MB`.
1009
+ * An unset or invalid value keeps the default.
1010
+ */
1011
+ function resolveGenerationLimits() {
1012
+ return {
1013
+ maxCount: Math.max(1, Math.floor(positiveNumber(process$1.env.KUBB_AGENT_MAX_GENERATIONS) ?? 8)),
1014
+ maxMb: positiveNumber(process$1.env.KUBB_AGENT_MAX_GENERATIONS_MB) ?? 100,
1015
+ maxSnapshotMb: positiveNumber(process$1.env.KUBB_AGENT_MAX_SNAPSHOT_MB) ?? 50
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Folds error-severity diagnostics into one thrown error so logs name the failing plugin or pass.
1020
+ */
1021
+ function generationFailure(diagnostics) {
1022
+ const reasons = diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.plugin ? `${diagnostic.plugin}: ${diagnostic.message}` : diagnostic.message);
1023
+ if (!reasons.length) return /* @__PURE__ */ new Error("Generation failed");
1024
+ return /* @__PURE__ */ new Error(`Generation failed: ${reasons.length} error${reasons.length === 1 ? "" : "s"}: ${reasons.join("; ")}`);
1025
+ }
1026
+ /**
1027
+ * Runs one generation and returns the files it produced. The formatter, the linter, and
1028
+ * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
1029
+ */
1030
+ async function generate({ config, hooks, signal, allowExec }) {
1031
+ const output = allowExec ? config.output : {
1032
+ ...config.output,
1033
+ format: false,
1034
+ lint: false,
1035
+ postGenerate: []
1036
+ };
1037
+ const result = await createKubb({
1038
+ ...config,
1039
+ output
1040
+ }, {
1041
+ hooks,
1042
+ signal
1043
+ }).generate();
1044
+ if (!result.success) throw generationFailure(result.diagnostics);
1045
+ return {
1046
+ storage: config.storage,
1047
+ root: config.root,
1048
+ paths: new Set(result.files.map((file) => relativeStoragePath({
1049
+ root: config.root,
1050
+ filePath: file.path
1051
+ })))
1052
+ };
1053
+ }
446
1054
  /**
447
1055
  * What the output directory holds on disk before a run. `undefined` when `outputPath` is not a real
448
1056
  * subdirectory of `root` (listing the root would take in every source file) or holds more than `maxFiles`.
@@ -521,9 +1129,6 @@ function createGenerationStore({ storage, maxCount, maxMb, ttlMs, now = Date.now
521
1129
  keep,
522
1130
  drop,
523
1131
  get: async (jobId) => (await load()).find((generation) => generation.jobId === jobId && isLive(generation)),
524
- latest: async () => (await load()).filter(isLive).at(-1),
525
- /** Total bytes of every set the store holds, expired ones too until the next add drops them. */
526
- bytes: async () => totalBytes(await load()),
527
1132
  async add(generation) {
528
1133
  const current = await load();
529
1134
  for (const expired of current.filter((entry) => !isLive(entry))) await drop(expired.jobId);
@@ -570,7 +1175,7 @@ function createGenerationStore({ storage, maxCount, maxMb, ttlMs, now = Date.now
570
1175
  };
571
1176
  }
572
1177
  //#endregion
573
- //#region src/operations/generationEvents.ts
1178
+ //#region src/generationEvents.ts
574
1179
  const MAX_QUEUED_EVENTS = 1024;
575
1180
  const RESERVED_EVENTS = 64;
576
1181
  const isDiscardable = (event) => event.type === "kubb:files:processing:update" || event.type === "kubb:info" || event.type === "kubb:success";
@@ -751,423 +1356,151 @@ function createGenerationStream(hooks, jobId) {
751
1356
  };
752
1357
  }
753
1358
  //#endregion
754
- //#region src/operations/rpc.ts
755
- const CONNECT_TIMEOUT_MS = 5e3;
756
- /**
757
- * The only methods Studio may call on an agent. A `StudioSession` carries far more than
758
- * {@link AgentApi}, so it is wrapped rather than exposed: what Cap'n Web can reach is exactly what
759
- * this class re-declares.
760
- */
761
- var AgentRpcTarget = class extends RpcTarget {
762
- api;
763
- constructor(api) {
764
- super();
765
- this.api = api;
766
- }
767
- connect() {
768
- return this.api.connect();
769
- }
770
- startGeneration(input) {
771
- return this.api.startGeneration(input);
772
- }
773
- saveConfig(input) {
774
- return this.api.saveConfig(input);
775
- }
776
- publishSnapshot(input) {
777
- return this.api.publishSnapshot(input);
778
- }
779
- readFiles(input) {
780
- return this.api.readFiles(input);
781
- }
782
- cancel(jobId) {
783
- return this.api.cancel(jobId);
784
- }
785
- };
1359
+ //#region src/url.ts
786
1360
  /**
787
- * Opens a Studio WebSocket, closing it when the handshake exceeds {@link CONNECT_TIMEOUT_MS}. Node
788
- * fires no `close` event when the handshake itself fails, only `error`, so `closed` settles as 1006 there.
1361
+ * Hosted Kubb Studio URL, used when a host passes none.
789
1362
  */
790
- function openSocket({ url, headers }) {
791
- const socket = new WebSocket(url, { headers });
792
- return {
793
- socket,
794
- closed: new Promise((resolve) => {
795
- let opened = false;
796
- const timer = setTimeout(() => {
797
- if (socket.readyState === WebSocket.CONNECTING) socket.close(3008, "Connection timeout");
798
- }, CONNECT_TIMEOUT_MS);
799
- socket.addEventListener("open", () => {
800
- opened = true;
801
- clearTimeout(timer);
802
- }, { once: true });
803
- socket.addEventListener("close", (event) => {
804
- clearTimeout(timer);
805
- resolve({
806
- code: event.code,
807
- reason: event.reason
808
- });
809
- }, { once: true });
810
- socket.addEventListener("error", () => {
811
- if (opened) return;
812
- clearTimeout(timer);
813
- resolve({
814
- code: 1006,
815
- reason: ""
816
- });
817
- });
818
- })
819
- };
1363
+ const defaultStudioUrl = "https://kubb.studio";
1364
+ function isLoopbackHost(hostname) {
1365
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
820
1366
  }
821
1367
  /**
822
- * Opens an authenticated Cap'n Web session to Studio over a WebSocket. Rejects an unencrypted URL
823
- * before opening the socket, so a bearer token never reaches a plaintext host.
1368
+ * Appends `path` to the Studio URL and refuses plaintext to anything but this machine, so a token
1369
+ * or API key never crosses the network unencrypted. `socket` switches the scheme to `ws:`/`wss:`.
824
1370
  *
825
1371
  * @example
826
1372
  * ```ts
827
- * const rpc = await connectWebSocketRpc({ url: 'wss://studio.kubb.dev/s/1', token, local: session })
828
- * await rpc.studio.ping()
1373
+ * secureUrl({ studioUrl: 'https://kubb.studio', path: '/api/agent/socket', socket: true }).href // 'wss://kubb.studio/api/agent/socket'
829
1374
  * ```
830
1375
  */
831
- const connectWebSocketRpc = async ({ url, token, instanceId, local }) => {
832
- const { protocol, hostname, host } = new URL(url);
833
- if (protocol !== "wss:" && !(protocol === "ws:" && isLoopbackHost(hostname))) throw new Error(`Refusing unencrypted WebSocket to ${host}`);
834
- const { socket, closed } = openSocket({
835
- url,
836
- headers: {
837
- Authorization: `Bearer ${token}`,
838
- [AGENT_INSTANCE_HEADER]: instanceId
839
- }
840
- });
841
- const studio = newWebSocketRpcSession(socket, new AgentRpcTarget(local));
842
- studio.onRpcBroken(() => socket.close());
843
- return {
844
- studio,
845
- closed,
846
- close: () => studio[Symbol.dispose]()
847
- };
848
- };
1376
+ function secureUrl({ studioUrl, path, socket = false }) {
1377
+ const url = new URL(`${studioUrl.replace(/\/+$/, "")}${path}`);
1378
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) throw new Error(`Refusing to reach Kubb Studio at ${url.origin}: use an https:// URL, or a loopback host for local development`);
1379
+ if (socket) url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
1380
+ return url;
1381
+ }
849
1382
  //#endregion
850
- //#region src/runtime/StudioSession.ts
1383
+ //#region src/connect.ts
1384
+ const HEARTBEAT_INTERVAL_MS = 3e4;
1385
+ const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
1386
+ const PING_TIMEOUT_MS = 1e4;
1387
+ const OPEN_TIMEOUT_MS = 5e3;
1388
+ const MAX_RETRY_DELAY_MS = 3e4;
851
1389
  const DISK_SNAPSHOT_MAX_FILES = 1e4;
1390
+ const SANDBOX_GENERATION_TTL_MS = 9e5;
852
1391
  /**
853
- * Folds error-severity diagnostics into one thrown error so logs name the failing plugin or pass.
1392
+ * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
854
1393
  */
855
- function generationFailure(diagnostics) {
856
- const reasons = diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.plugin ? `${diagnostic.plugin}: ${diagnostic.message}` : diagnostic.message);
857
- if (!reasons.length) return /* @__PURE__ */ new Error("Generation failed");
858
- return /* @__PURE__ */ new Error(`Generation failed: ${reasons.length} error${reasons.length === 1 ? "" : "s"}: ${reasons.join("; ")}`);
859
- }
860
- /** A sandbox shares one in-memory generation store across tenants, so old generations expire. */
861
- const SANDBOX_GENERATION_TTL_MS = 9e5;
1394
+ var InvalidAgentTokenError = class extends Error {
1395
+ constructor(studioUrl) {
1396
+ super(`Kubb Studio rejected this agent's token. It expired or was revoked, or the agent was deleted in ${studioUrl}.`);
1397
+ this.name = "InvalidAgentTokenError";
1398
+ }
1399
+ };
862
1400
  /**
863
- * A fresh root for one sandbox job. Kubb keys its output manifest cache by root, so tenants that
864
- * shared the agent's own root would read each other's manifest.
1401
+ * Studio closed with {@link AgentCloseCode.INCOMPATIBLE}. Only an upgrade helps.
865
1402
  */
866
- function createJobRoot() {
867
- return mkdtemp(path.join(tmpdir(), "kubb-job-"));
1403
+ var IncompatibleAgentError = class extends Error {
1404
+ constructor({ studioUrl, detail }) {
1405
+ super(`Kubb Studio at ${studioUrl} requires a newer agent${detail ? `: ${detail}` : ""}. Upgrade kubb or the Kubb agent image.`);
1406
+ this.name = "IncompatibleAgentError";
1407
+ }
1408
+ };
1409
+ function emit(hooks, name, ...args) {
1410
+ return Promise.resolve(hooks.callHook(name, ...args)).catch(() => {});
868
1411
  }
869
- /**
870
- * Removes a job root and the manifest cache Kubb derived from it. Best effort: a leftover temp
871
- * directory must not fail a job that already finished.
872
- */
873
- async function removeJobRoot(jobRoot) {
874
- await Promise.all([rm(jobRoot, {
875
- recursive: true,
876
- force: true
877
- }), rm(resolveCacheDir(jobRoot), {
878
- recursive: true,
879
- force: true
880
- })]).catch(() => {});
1412
+ function isValidPage({ cursor, limit }) {
1413
+ if (limit === void 0) return cursor === void 0;
1414
+ if (cursor !== void 0 && (!Number.isSafeInteger(cursor) || cursor < 0)) return false;
1415
+ return Number.isSafeInteger(limit) && limit >= 1 && limit <= 2e3;
881
1416
  }
882
1417
  var GenerationRunTarget = class extends RpcTarget {
883
- generationStream;
884
- generationResult;
885
- cancelGeneration;
886
- stopGeneration;
887
- constructor(generationStream, generationResult, cancelGeneration, stopGeneration) {
1418
+ #run;
1419
+ constructor(run) {
888
1420
  super();
889
- this.generationStream = generationStream;
890
- this.generationResult = generationResult;
891
- this.cancelGeneration = cancelGeneration;
892
- this.stopGeneration = stopGeneration;
1421
+ this.#run = run;
893
1422
  }
894
1423
  async events() {
895
- return this.generationStream;
1424
+ return this.#run.stream;
896
1425
  }
897
1426
  result() {
898
- return this.generationResult;
1427
+ return this.#run.result;
899
1428
  }
900
- cancel() {
901
- return this.cancelGeneration();
1429
+ async cancel() {
1430
+ this.#run.stop();
902
1431
  }
903
1432
  [Symbol.dispose]() {
904
- this.stopGeneration();
1433
+ this.#run.stop();
905
1434
  }
906
1435
  };
907
- /**
908
- * Fills in a host's options: the hosted Studio URL, the current working directory, and every
909
- * permission off unless granted. Idempotent, so a reconnect can pass an already-resolved bag
910
- * back in.
911
- */
912
- function applyStudioDefaults(options) {
913
- const root = options.root ?? process$1.cwd();
914
- return {
915
- ...options,
916
- studioUrl: options.studioUrl ?? agentDefaults.studioUrl,
917
- root,
918
- configFile: path.resolve(root, options.configPath),
919
- permissions: {
920
- allowWrite: false,
921
- allowConfigEdit: false,
922
- allowExec: false,
923
- allowRead: false,
924
- ...options.permissions
925
- },
926
- heartbeatInterval: Math.min(options.heartbeatInterval ?? agentDefaults.heartbeatIntervalMs, agentDefaults.maxHeartbeatIntervalMs),
927
- capacity: {
928
- ...resolveAgentCapacity(),
929
- ...options.capacity
930
- },
931
- instanceId: options.instanceId ?? randomUUID()
932
- };
933
- }
934
- /**
935
- * Jobs one agent process can run at once today. Two runs would share this session's hook emitter,
936
- * and with it each other's events, so the connection keeps this limit.
937
- */
938
- const RUNTIME_MAX_CONCURRENT = 1;
939
- /**
940
- * Reads what Studio meant by closing the connection. A code Studio did not send on purpose is an
941
- * ordinary drop, and the agent reconnects as it always has.
942
- */
943
- function planEnd(close) {
944
- const code = close?.code;
945
- if (code === AgentCloseCode.REAUTHENTICATE) return {
946
- reason: "Kubb Studio asked the agent to register again",
947
- retry: true
948
- };
949
- if (code === AgentCloseCode.SUPERSEDED) return {
950
- reason: "another instance of this agent took over",
951
- retry: false
952
- };
953
- if (code === AgentCloseCode.INCOMPATIBLE) return {
954
- reason: "this agent is too old for Kubb Studio, or was deleted",
955
- retry: false,
956
- error: /* @__PURE__ */ new Error("Kubb Studio closed the connection: this agent is too old for it, or was deleted. Upgrade the agent, or pair it again.")
957
- };
958
- return {
959
- reason: "connection closed",
960
- retry: true
961
- };
962
- }
963
- function isValidPage({ cursor, limit }) {
964
- if (limit === void 0) return cursor === void 0;
965
- if (cursor !== void 0 && (!Number.isSafeInteger(cursor) || cursor < 0)) return false;
966
- return Number.isSafeInteger(limit) && limit >= 1 && limit <= 2e3;
967
- }
968
- /**
969
- * One agent-to-Studio RPC transport: opening it, keeping it alive, and serving remote methods.
970
- * `runConnection` owns the lifetime and retry of each attempt.
971
- */
972
- var StudioSession = class {
1436
+ var Agent = class extends RpcTarget {
973
1437
  #options;
974
- #hooks = new Hookable();
975
- /**
976
- * Removers for every listener this session added (socket, shutdown signal, hooks) so `dispose`
977
- * detaches them in one pass. Listeners a host attached itself through `installLogger` survive.
978
- */
979
- #unhooks = [];
980
- /**
981
- * What registration handed back, and the marker for whether the agent registered at all.
982
- * Before it resolves there is no sandbox flag to read.
983
- */
984
- #registration;
985
- #rpc;
986
- #disposed = false;
987
- #isGenerating = false;
988
- #activeJob;
989
- #heartbeatTimer;
990
- #store;
1438
+ #session;
991
1439
  #limits = resolveGenerationLimits();
992
- /**
993
- * Resolves when Studio calls {@link StudioSession.connect}. `studio:ready` waits on this so the
994
- * host does not queue jobs before the agent session is registered.
995
- */
996
- #connectAck = Promise.withResolvers();
997
- #ended = Promise.withResolvers();
998
- closed = this.#ended.promise;
999
- #generationResult;
1000
- constructor(options) {
1001
- this.#options = applyStudioDefaults(options);
1002
- this.#connectAck.promise.catch(() => {});
1440
+ #store;
1441
+ constructor({ options, session }) {
1442
+ super();
1443
+ this.#options = options;
1444
+ this.#session = session;
1003
1445
  }
1004
- /**
1005
- * A sandbox agent runs on Studio's own infrastructure, so it has no user project to touch.
1006
- */
1007
- get #isSandbox() {
1008
- return this.#registration?.isSandbox === true;
1446
+ get #sandbox() {
1447
+ return this.#session.info?.sandbox === true;
1448
+ }
1449
+ get #permissions() {
1450
+ const { permissions } = this.#options;
1451
+ return this.#sandbox ? {
1452
+ ...permissions,
1453
+ allowWrite: false,
1454
+ allowConfigEdit: false,
1455
+ allowRead: true
1456
+ } : permissions;
1009
1457
  }
1010
- /**
1011
- * Kept in the project's cache directory, so it survives a restart, except on a sandbox: its pool
1012
- * sessions run every tenant's jobs, so it keeps them in memory. Looked up by job id only.
1013
- */
1014
1458
  get #generations() {
1015
1459
  this.#store ??= createGenerationStore({
1016
- storage: this.#isSandbox ? memoryStorage() : cacheStorage({ root: this.#options.root }),
1460
+ storage: this.#sandbox ? memoryStorage() : cacheStorage({ root: this.#options.root }),
1017
1461
  maxCount: this.#limits.maxCount,
1018
1462
  maxMb: this.#limits.maxMb,
1019
- ttlMs: this.#isSandbox ? SANDBOX_GENERATION_TTL_MS : void 0
1463
+ ttlMs: this.#sandbox ? SANDBOX_GENERATION_TTL_MS : void 0
1020
1464
  });
1021
1465
  return this.#store;
1022
1466
  }
1023
- get #canWrite() {
1024
- return !this.#isSandbox && this.#options.permissions.allowWrite;
1025
- }
1026
- get #canEditConfig() {
1027
- return !this.#isSandbox && this.#options.permissions.allowConfigEdit;
1028
- }
1029
- /**
1030
- * A sandbox agent always allows reading its output back; a local agent only when opted in.
1031
- */
1032
- get #canRead() {
1033
- return this.#isSandbox || this.#options.permissions.allowRead;
1034
- }
1035
- async start() {
1036
- const { token, studioUrl, signal, heartbeatInterval, installLogger, instanceId, capacity } = this.#options;
1037
- await installLogger?.(this.#hooks);
1038
- signal?.addEventListener("abort", this.#onAbort, { once: true });
1039
- this.#unhooks.push(() => signal?.removeEventListener("abort", this.#onAbort));
1040
- try {
1041
- signal?.throwIfAborted();
1042
- await this.#hooks.callHook("studio:connecting", { url: studioUrl });
1043
- if (capacity.maxConcurrent > RUNTIME_MAX_CONCURRENT) await this.#warn(`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`);
1044
- const registration = await registerAgent({
1045
- signal,
1046
- token,
1047
- studioUrl,
1048
- instanceId,
1049
- capacity: {
1050
- ...capacity,
1051
- maxConcurrent: Math.min(capacity.maxConcurrent, RUNTIME_MAX_CONCURRENT)
1052
- }
1053
- });
1054
- signal?.throwIfAborted();
1055
- this.#registration = registration;
1056
- const rpc = await (this.#options.connector ?? connectWebSocketRpc)({
1057
- url: registration.socketUrl,
1058
- token,
1059
- instanceId,
1060
- local: this
1061
- });
1062
- this.#rpc = rpc;
1063
- rpc.closed.then(this.#onClose);
1064
- if (signal?.aborted || this.#disposed) {
1065
- rpc.close();
1066
- throw new Error("Connection stopped during startup");
1067
- }
1068
- this.#scheduleHeartbeat(heartbeatInterval);
1069
- await this.#hooks.callHook("studio:connected", {
1070
- url: studioUrl,
1071
- versions: {
1072
- studio: registration.version,
1073
- kubb: version,
1074
- agent: this.#options.version
1075
- },
1076
- agentSlug: registration.agentSlug,
1077
- organizationSlug: registration.organizationSlug
1078
- });
1079
- await this.#connectAck.promise;
1080
- await this.#hooks.callHook("studio:ready", {});
1081
- } catch (error) {
1082
- await this.dispose();
1083
- if (!signal?.aborted) await this.#hooks.callHook("studio:error", { error: toError(error) });
1084
- throw error;
1085
- }
1086
- }
1087
- reportRetry(delayMs) {
1088
- return this.#hooks.callHook("studio:reconnecting", { delayMs });
1089
- }
1090
- #warn(message, permission) {
1091
- return this.#hooks.callHook("studio:warn", {
1467
+ #warn({ message, permission }) {
1468
+ return emit(this.#options.hooks, "studio:warn", {
1092
1469
  message,
1093
1470
  permission
1094
1471
  });
1095
1472
  }
1096
- /**
1097
- * Declines a request: logs why locally, then tells Studio. The two wordings differ on purpose,
1098
- * since the log names the request that was ignored and the error names what the caller can do.
1099
- */
1100
- async #refuse(reason, message, permission) {
1101
- await this.#warn(reason, permission);
1473
+ async #refuse({ message, permission }) {
1474
+ await this.#warn({
1475
+ message,
1476
+ permission
1477
+ });
1102
1478
  throw new Error(message);
1103
1479
  }
1104
- /**
1105
- * Brackets one Studio command with `studio:command:start` and `studio:command:end`. A command
1106
- * that declined its request reports no `info`, and only the start is heard.
1107
- */
1108
1480
  async #command({ command, run }) {
1109
- await this.#hooks.callHook("studio:command:start", { command });
1481
+ if (!this.#session.info) throw new Error("Studio must call connect() before any other command");
1110
1482
  const { value, info } = await run();
1111
- if (info !== void 0) await this.#hooks.callHook("studio:command:end", {
1483
+ if (info !== void 0) await emit(this.#options.hooks, "studio:command", {
1112
1484
  command,
1113
1485
  info
1114
1486
  });
1115
1487
  return value;
1116
1488
  }
1117
- #scheduleHeartbeat(interval) {
1118
- const rpc = this.#rpc;
1119
- if (!rpc) return;
1120
- this.#heartbeatTimer = setTimeout(async () => {
1121
- try {
1122
- await this.#ping(rpc);
1123
- } catch {
1124
- if (this.#rpc === rpc) rpc.close();
1125
- return;
1126
- }
1127
- if (this.#rpc === rpc) this.#scheduleHeartbeat(interval);
1128
- }, interval);
1129
- }
1130
- /**
1131
- * Races `studio.ping()` against a deadline, so a half-open socket can't hang it forever.
1132
- * */
1133
- async #ping(rpc) {
1134
- const { promise: timedOut, reject: onTimeout } = Promise.withResolvers();
1135
- const timer = setTimeout(() => onTimeout(/* @__PURE__ */ new Error("Heartbeat ping timed out")), agentDefaults.heartbeatTimeoutMs);
1136
- try {
1137
- const load = await Promise.race([this.#load().catch(() => void 0), timedOut]);
1138
- await Promise.race([rpc.studio.ping(load), timedOut]);
1139
- } finally {
1140
- clearTimeout(timer);
1141
- }
1142
- }
1143
- async #load() {
1144
- return {
1145
- running: this.#isGenerating ? 1 : 0,
1146
- rssMb: Math.round(process$1.memoryUsage().rss / 1048576),
1147
- storeBytes: await this.#generations.bytes(),
1148
- accepting: true
1149
- };
1150
- }
1151
- /**
1152
- * Reads `kubb.config.ts` and reports which plugin options Studio may edit.
1153
- *
1154
- * Skipped when the host did not grant `allowConfigEdit`. Not cached: the user can edit the file
1155
- * between two Studio actions.
1156
- */
1157
1489
  async #readConfigFileView(source) {
1158
- if (!this.#canEditConfig) return;
1490
+ if (!this.#permissions.allowConfigEdit) return void 0;
1159
1491
  try {
1160
- const { readConfig } = await import("./configFile-zhp5DQIe.js");
1161
1492
  return readConfig(source ?? await read(this.#options.configFile));
1162
1493
  } catch (error) {
1163
- await this.#warn(`Could not read ${this.#options.configFile}: ${getErrorMessage(error)}`);
1494
+ await this.#warn({ message: `Could not read ${this.#options.configFile}: ${getErrorMessage(error)}` });
1164
1495
  return;
1165
1496
  }
1166
1497
  }
1167
- async connect() {
1168
- const { configPath, root, version: version$1, loadConfig, permissions } = this.#options;
1498
+ async connect(info) {
1499
+ this.#session.info = info;
1500
+ const { configPath, root, version: version$1, loadConfig } = this.#options;
1169
1501
  const [config, file] = await Promise.all([loadConfig(), this.#readConfigFileView()]);
1170
- const payload = {
1502
+ this.#session.connected.resolve(info);
1503
+ return {
1171
1504
  versions: {
1172
1505
  kubb: version,
1173
1506
  agent: version$1
@@ -1181,197 +1514,131 @@ var StudioSession = class {
1181
1514
  options: plugin.options ?? {}
1182
1515
  }))
1183
1516
  },
1184
- permissions: {
1185
- ...permissions,
1186
- allowWrite: this.#canWrite,
1187
- allowConfigEdit: this.#canEditConfig,
1188
- allowRead: this.#canRead
1189
- }
1517
+ permissions: this.#permissions
1190
1518
  };
1191
- this.#connectAck.resolve();
1192
- return payload;
1193
- }
1194
- #onAbort = () => void this.#end({
1195
- reason: "shutdown",
1196
- retry: false
1197
- }).catch(() => {});
1198
- #onClose = (close) => void this.#end(planEnd(close)).catch(() => {});
1199
- /** Closes this attempt and waits for its generation to stop before another can start. */
1200
- dispose() {
1201
- return this.#end({
1202
- reason: "shutdown",
1203
- retry: false
1204
- });
1205
- }
1206
- async #end(plan) {
1207
- if (this.#disposed) {
1208
- await this.closed;
1209
- return;
1210
- }
1211
- this.#disposed = true;
1212
- clearTimeout(this.#heartbeatTimer);
1213
- this.#rpc?.close();
1214
- this.#rpc = void 0;
1215
- this.#connectAck.reject(/* @__PURE__ */ new Error("Session ended before Studio called connect()"));
1216
- for (const unhook of this.#unhooks) unhook();
1217
- this.#unhooks.length = 0;
1218
- try {
1219
- await this.#activeJob?.cancel();
1220
- await this.#generationResult?.catch(() => {});
1221
- await this.#hooks.callHook("studio:disconnected", { reason: plan.reason });
1222
- if (plan.error) await this.#hooks.callHook("studio:error", { error: plan.error });
1223
- } finally {
1224
- this.#ended.resolve(plan);
1225
- }
1226
1519
  }
1227
- startGeneration(data) {
1228
- const generationStream = createGenerationStream(this.#hooks, data.jobId);
1520
+ startGeneration(input) {
1521
+ const stream = createGenerationStream(this.#options.hooks, input.jobId);
1229
1522
  const controller = new AbortController();
1230
- const cancelRun = async () => {
1231
- controller.abort(/* @__PURE__ */ new Error("Generation canceled"));
1232
- };
1233
- const result = this.#runGeneration(data, controller, cancelRun).then(async (value) => {
1234
- await generationStream.close();
1235
- return value;
1236
- }).catch((error) => {
1237
- generationStream.fail(error);
1523
+ const result = this.#runGeneration(input, controller).then((value) => stream.close().then(() => value), (error) => {
1524
+ stream.fail(error);
1238
1525
  throw error;
1239
- }).finally(() => {
1240
- if (this.#activeJob?.cancel === cancelRun) this.#activeJob = void 0;
1241
1526
  });
1242
- if (this.#activeJob?.cancel === cancelRun) this.#generationResult = result;
1243
1527
  result.catch(() => {});
1244
- return new GenerationRunTarget(generationStream.stream, result, cancelRun, () => {
1245
- controller.abort(/* @__PURE__ */ new Error("Generation canceled"));
1246
- generationStream.dispose();
1528
+ return new GenerationRunTarget({
1529
+ stream: stream.stream,
1530
+ result,
1531
+ stop: () => {
1532
+ controller.abort(/* @__PURE__ */ new Error("Generation canceled"));
1533
+ stream.dispose();
1534
+ }
1247
1535
  });
1248
1536
  }
1249
- /**
1250
- * Cancels the currently running job when its id matches `jobId`.
1251
- */
1252
- async cancel(jobId) {
1253
- if (this.#activeJob?.jobId === jobId) await this.#activeJob.cancel();
1254
- }
1255
- async #runGeneration(data, controller, cancelRun) {
1256
- if (this.#disposed) throw new Error("Connection is closed");
1257
- if (this.#isGenerating) return this.#refuse("Ignored generate: a generation is already in progress", "A generation is already in progress, please wait for it to finish");
1258
- this.#isGenerating = true;
1259
- this.#activeJob = {
1260
- jobId: data.jobId,
1261
- cancel: cancelRun
1537
+ async #runGeneration(input, controller) {
1538
+ if (this.#session.closed) throw new Error("Connection is closed");
1539
+ if (this.#session.active) return this.#refuse({ message: "A generation is already in progress, please wait for it to finish" });
1540
+ const settled = Promise.withResolvers();
1541
+ this.#session.active = {
1542
+ jobId: input.jobId,
1543
+ abort: () => controller.abort(/* @__PURE__ */ new Error("Generation canceled")),
1544
+ settled: settled.promise
1262
1545
  };
1263
1546
  let root = this.#options.root;
1264
1547
  try {
1265
- if (this.#isSandbox) root = await createJobRoot();
1548
+ if (this.#sandbox) root = await mkdtemp(path.join(tmpdir(), "kubb-job-"));
1266
1549
  return await this.#command({
1267
1550
  command: "generate",
1268
1551
  run: () => this.#generate({
1269
- data,
1552
+ input,
1270
1553
  root,
1271
1554
  signal: controller.signal
1272
1555
  })
1273
1556
  });
1274
1557
  } finally {
1275
- if (root !== this.#options.root) await removeJobRoot(root);
1276
- this.#isGenerating = false;
1558
+ if (root !== this.#options.root) await Promise.all([rm(root, {
1559
+ recursive: true,
1560
+ force: true
1561
+ }), rm(resolveCacheDir(root), {
1562
+ recursive: true,
1563
+ force: true
1564
+ })]).catch(() => {});
1565
+ this.#session.active = void 0;
1566
+ settled.resolve();
1277
1567
  }
1278
1568
  }
1279
- async #generate({ data, root, signal }) {
1280
- const { loadConfig, permissions } = this.#options;
1281
- const config = await loadConfig();
1282
- const patch = data.config;
1283
- const plugins = await mergePlugins(config.plugins, patch?.plugins);
1569
+ async #generate({ input, root, signal }) {
1570
+ const { jobId, config: patch } = input;
1571
+ const config = await this.#options.loadConfig();
1572
+ const plugins = await mergePlugins(config.plugins, patch?.plugins) ?? config.plugins;
1284
1573
  const adapter = await mergeAdapter(config.adapter, patch?.adapter);
1285
- const inputOverride = this.#isSandbox ? patch?.input ?? "" : void 0;
1286
- if (permissions.allowWrite && this.#isSandbox) await this.#warn("Running in a sandbox, so writing files is disabled");
1287
- if (patch?.input && !this.#isSandbox) await this.#warn("Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox agent");
1288
- const resolvedPlugins = plugins ?? config.plugins;
1289
- const storage = this.#canWrite ? fsStorage() : memoryStorage();
1290
- const diskFiles = this.#hasProjectOnDisk ? await listDisk({
1574
+ const studioInput = this.#sandbox ? patch?.input ?? "" : void 0;
1575
+ if (patch?.input && !this.#sandbox) await this.#warn({ message: "Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox agent" });
1576
+ const diskFiles = !this.#sandbox && this.#permissions.allowRead ? await listDisk({
1291
1577
  root,
1292
1578
  outputPath: config.output.path,
1293
1579
  maxFiles: DISK_SNAPSHOT_MAX_FILES
1294
1580
  }) : void 0;
1295
1581
  const disk = diskFiles ? await this.#generations.keep({
1296
- jobId: data.jobId,
1582
+ jobId,
1297
1583
  source: "disk",
1298
1584
  files: diskFiles,
1299
1585
  maxSetMb: this.#limits.maxSnapshotMb
1300
1586
  }) : void 0;
1301
- const result = await createKubb({
1302
- ...config,
1303
- root,
1304
- input: inputOverride ?? config.input,
1305
- storage,
1306
- output: permissions.allowExec ? { ...config.output } : {
1307
- ...config.output,
1308
- format: false,
1309
- lint: false,
1310
- postGenerate: []
1587
+ const files = await generate({
1588
+ config: {
1589
+ ...config,
1590
+ root,
1591
+ input: studioInput ?? config.input,
1592
+ storage: this.#permissions.allowWrite ? fsStorage() : memoryStorage(),
1593
+ plugins,
1594
+ adapter
1311
1595
  },
1312
- plugins: resolvedPlugins,
1313
- adapter
1314
- }, {
1315
- hooks: this.#hooks,
1316
- signal
1317
- }).generate().catch(async (error) => {
1318
- await this.#generations.drop(data.jobId);
1596
+ hooks: this.#options.hooks,
1597
+ signal,
1598
+ allowExec: this.#permissions.allowExec
1599
+ }).catch(async (error) => {
1600
+ await this.#generations.drop(jobId);
1319
1601
  throw error;
1320
1602
  });
1321
- if (!result.success) {
1322
- await this.#generations.drop(data.jobId);
1323
- throw generationFailure(result.diagnostics);
1324
- }
1325
- const paths = new Set(result.files.map((file) => relativeStoragePath({
1326
- root,
1327
- filePath: file.path
1328
- })));
1329
1603
  const output = await this.#generations.keep({
1330
- jobId: data.jobId,
1604
+ jobId,
1331
1605
  source: "output",
1332
- files: {
1333
- storage,
1334
- root,
1335
- paths
1336
- },
1606
+ files,
1337
1607
  maxSetMb: this.#limits.maxMb
1338
1608
  });
1339
- if (!output.paths.length && Object.keys(output.hashes).length) await this.#warn("Kept only the hashes of this generation: its output is too large to keep");
1340
- const { peerDependencies, missingDependencies } = await resolvePeerDependencies(resolvedPlugins.map(({ name }) => name));
1609
+ if (!output.paths.length && Object.keys(output.hashes).length) await this.#warn({ message: "Kept only the hashes of this generation: its output is too large to keep" });
1341
1610
  await this.#generations.add({
1342
- jobId: data.jobId,
1611
+ jobId,
1343
1612
  output,
1344
- disk,
1345
- peerDependencies,
1346
- missingDependencies
1613
+ disk
1347
1614
  });
1348
1615
  return {
1349
1616
  value: {
1350
1617
  status: "success",
1351
- files: [...paths],
1352
- fileCount: paths.size,
1618
+ files: [...files.paths],
1619
+ fileCount: files.paths.size,
1353
1620
  hashes: output.hashes,
1354
1621
  disk: disk ? { hashes: disk.hashes } : void 0
1355
1622
  },
1356
- info: `${resolvedPlugins.length} plugin${resolvedPlugins.length === 1 ? "" : "s"}, ${this.#canWrite ? "written to disk" : "in memory"}${inputOverride !== void 0 ? ", from a Studio spec" : ""}`
1623
+ info: `${plugins.length} plugin${plugins.length === 1 ? "" : "s"}, ${this.#permissions.allowWrite ? "written to disk" : "in memory"}${studioInput !== void 0 ? ", from a Studio spec" : ""}`
1357
1624
  };
1358
1625
  }
1359
- saveConfig(data) {
1626
+ saveConfig(input) {
1360
1627
  return this.#command({
1361
1628
  command: "saveConfig",
1362
- run: () => this.#saveConfig(data)
1629
+ run: () => this.#saveConfig(input)
1363
1630
  });
1364
1631
  }
1365
- async #saveConfig(data) {
1632
+ async #saveConfig(input) {
1366
1633
  const { configPath, configFile } = this.#options;
1367
- if (!Array.isArray(data.edits)) {
1368
- await this.#warn("Ignored save: the message carried no edits");
1634
+ if (!Array.isArray(input.edits)) {
1635
+ await this.#warn({ message: "Ignored save: the message carried no edits" });
1369
1636
  return { value: {
1370
1637
  outcomes: [],
1371
1638
  changed: false
1372
1639
  } };
1373
1640
  }
1374
- const edits = data.edits;
1641
+ const edits = input.edits;
1375
1642
  const refuse = (reason) => ({
1376
1643
  outcomes: edits.map((edit) => ({
1377
1644
  edit,
@@ -1380,14 +1647,13 @@ var StudioSession = class {
1380
1647
  })),
1381
1648
  changed: false
1382
1649
  });
1383
- if (!this.#canEditConfig) {
1384
- await this.#warn("Ignored save: editing kubb.config.ts was not granted");
1650
+ if (!this.#permissions.allowConfigEdit) {
1651
+ await this.#warn({ message: "Ignored save: editing kubb.config.ts was not granted" });
1385
1652
  return { value: refuse("the agent was not granted permission to edit kubb.config.ts") };
1386
1653
  }
1387
- if (this.#isGenerating) return { value: refuse("a generation is in progress") };
1654
+ if (this.#session.active) return { value: refuse("a generation is in progress") };
1388
1655
  try {
1389
- const { writeConfigEdits } = await import("./configFile-zhp5DQIe.js");
1390
- const { source: patched, outcomes, changed } = await writeConfigEdits({
1656
+ const { source, outcomes, changed } = await writeConfigEdits({
1391
1657
  filePath: configFile,
1392
1658
  edits
1393
1659
  });
@@ -1396,89 +1662,40 @@ var StudioSession = class {
1396
1662
  value: {
1397
1663
  outcomes,
1398
1664
  changed,
1399
- file: changed ? await this.#readConfigFileView(patched) : void 0
1665
+ file: changed ? await this.#readConfigFileView(source) : void 0
1400
1666
  },
1401
1667
  info: `applied ${applied}/${outcomes.length} edits to ${configPath}`
1402
1668
  };
1403
1669
  } catch (error) {
1404
- await this.#hooks.callHook("studio:error", { error: toError(error) });
1670
+ await emit(this.#options.hooks, "studio:error", { error: toError(error) });
1405
1671
  return { value: refuse(getErrorMessage(error)) };
1406
1672
  }
1407
1673
  }
1408
- publishSnapshot(data) {
1409
- return this.#command({
1410
- command: "snapshot",
1411
- run: () => this.#publishSnapshot(data)
1412
- });
1413
- }
1414
- async #publishSnapshot(data) {
1415
- if (this.#isSandbox) 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");
1416
- const { name, version, bundledDependencies, uploadPath } = data;
1417
- if (!name || !version || !uploadPath) return this.#refuse("Ignored snapshot: the message was missing required fields", "The request was missing required fields");
1418
- const generation = await this.#generations.latest();
1419
- if (!generation) return this.#refuse("Ignored snapshot: no prior generation to pack", "No prior generation exists to pack, run a generation first");
1420
- const bundled = new Set(bundledDependencies ?? []);
1421
- const missing = generation.missingDependencies.filter((dependency) => !bundled.has(dependency));
1422
- if (missing.length) return this.#refuse(`Ignored snapshot: missing dependencies: ${missing.join(", ")}`, `Missing dependencies: ${missing.join(", ")}`);
1423
- try {
1424
- const { createSnapshotPackage, uploadSnapshot } = await import("./snapshotPackage-BwZ8IJX-.js");
1425
- const { files } = await this.#generations.read({
1426
- generation,
1427
- source: "output",
1428
- paths: generation.output.paths
1429
- });
1430
- const { bytes, integrity } = await createSnapshotPackage(files, {
1431
- name,
1432
- version,
1433
- peerDependencies: generation.peerDependencies
1434
- });
1435
- const { token, studioUrl, signal } = this.#options;
1436
- await uploadSnapshot({
1437
- bytes,
1438
- uploadPath,
1439
- studioUrl,
1440
- token,
1441
- shutdown: signal
1442
- });
1443
- return {
1444
- value: {
1445
- integrity,
1446
- peerDependencies: generation.peerDependencies
1447
- },
1448
- info: `packed ${Object.keys(files).length} file${Object.keys(files).length === 1 ? "" : "s"}`
1449
- };
1450
- } catch (error) {
1451
- await this.#hooks.callHook("studio:error", { error: toError(error) });
1452
- throw error;
1453
- }
1454
- }
1455
- /** A sandbox has no project directory to snapshot. */
1456
- get #hasProjectOnDisk() {
1457
- return !this.#isSandbox && this.#canRead;
1458
- }
1459
- readFiles(data) {
1674
+ readFiles(input) {
1460
1675
  return this.#command({
1461
1676
  command: "readFiles",
1462
- run: () => this.#readFiles(data)
1677
+ run: () => this.#readFiles(input)
1463
1678
  });
1464
1679
  }
1465
- async #readFiles(data) {
1466
- if (!this.#canRead) return this.#refuse("Ignored files: reading generated files was not granted", "The agent was not granted permission to read generated files", "allowRead");
1467
- if (!Array.isArray(data.paths)) return this.#refuse("Ignored files: the message carried no paths", "The request carried no paths");
1468
- const { paths } = data;
1469
- if (paths.length > 50) return this.#refuse(`Ignored files: requested ${paths.length} paths, more than the 50 allowed per request`, `At most 50 paths may be requested at once`);
1470
- if (typeof data.jobId !== "string" || !data.jobId) return this.#refuse("Ignored files: the message named no job", "The request named no generation job");
1471
- const generation = await this.#generations.get(data.jobId);
1472
- if (!generation) return this.#refuse(`Ignored files: job ${data.jobId} is not kept on this agent`, GENERATION_GONE_MESSAGE);
1473
- if (!isValidPage(data)) return this.#refuse("Ignored files: the message carried an invalid page", `The cursor must be a whole line from 0 and come with a limit of 1 to ${MAX_PAGE_LINES} lines`);
1474
- const source = data.source === "disk" ? "disk" : "output";
1475
- if (!generation[source]) 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");
1680
+ async #readFiles(input) {
1681
+ if (!this.#permissions.allowRead) return this.#refuse({
1682
+ message: "The agent was not granted permission to read generated files",
1683
+ permission: "allowRead"
1684
+ });
1685
+ if (!Array.isArray(input.paths) || typeof input.jobId !== "string" || !input.jobId) return this.#refuse({ message: "The request must name a job and carry paths" });
1686
+ const { paths } = input;
1687
+ if (paths.length > 50) return this.#refuse({ message: `At most 50 paths may be requested at once` });
1688
+ const generation = await this.#generations.get(input.jobId);
1689
+ if (!generation) return this.#refuse({ message: GENERATION_GONE_MESSAGE });
1690
+ 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` });
1691
+ const source = input.source === "disk" ? "disk" : "output";
1692
+ if (!generation[source]) return this.#refuse({ message: "This agent kept no snapshot of the files on disk for that job" });
1476
1693
  const result = await this.#generations.read({
1477
1694
  generation,
1478
1695
  source,
1479
1696
  paths,
1480
- cursor: data.cursor,
1481
- limit: data.limit
1697
+ cursor: input.cursor,
1698
+ limit: input.limit
1482
1699
  });
1483
1700
  return {
1484
1701
  value: result,
@@ -1486,96 +1703,159 @@ var StudioSession = class {
1486
1703
  };
1487
1704
  }
1488
1705
  };
1489
- //#endregion
1490
- //#region src/runtime/runConnection.ts
1491
- /** Runs the process's one connection loop, including retries and credential replacement. */
1492
- async function runConnection({ credentials, clientOptions, onTokenRejected, signal, onStarted }) {
1493
- let current = credentials;
1494
- const initialOptions = clientOptions(current);
1495
- const instanceId = initialOptions.instanceId ?? randomUUID();
1496
- let options = initialOptions;
1497
- let attempt = 0;
1498
- let live = false;
1499
- while (!signal?.aborted) {
1500
- const session = new StudioSession({
1501
- ...options,
1502
- instanceId,
1503
- token: current.token,
1504
- signal
1706
+ const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
1707
+ const socket = new WebSocket(url, { headers: {
1708
+ Authorization: `Bearer ${token}`,
1709
+ [AGENT_INSTANCE_HEADER]: instanceId
1710
+ } });
1711
+ const timer = setTimeout(() => socket.close(3008, "Connection timeout"), OPEN_TIMEOUT_MS);
1712
+ socket.addEventListener("open", () => clearTimeout(timer), { once: true });
1713
+ const closed = new Promise((resolve) => {
1714
+ socket.addEventListener("close", ({ code, reason }) => resolve({
1715
+ code,
1716
+ reason
1717
+ }), { once: true });
1718
+ socket.addEventListener("error", () => {
1719
+ if (socket.readyState !== WebSocket.OPEN) resolve({
1720
+ code: 1006,
1721
+ reason: ""
1722
+ });
1505
1723
  });
1506
- try {
1507
- await session.start();
1508
- live = true;
1509
- attempt = 0;
1510
- onStarted?.();
1511
- if (!(await session.closed).retry) return signal?.aborted ? "shutdown" : "stopped";
1512
- } catch (error) {
1513
- if (signal?.aborted) return "shutdown";
1514
- if (error instanceof IncompatibleAgentError) throw error;
1515
- await session.dispose();
1516
- const end = await session.closed;
1517
- if (!end.retry && end.reason !== "shutdown") return "stopped";
1518
- if (error instanceof InvalidAgentTokenError) {
1519
- const next = await onTokenRejected({
1520
- error,
1521
- credentials: current,
1522
- live
1523
- });
1524
- if (!next) return "stopped";
1525
- current = next;
1526
- options = clientOptions(current);
1527
- live = false;
1528
- attempt = 0;
1529
- continue;
1530
- }
1531
- } finally {
1532
- await session.dispose();
1533
- }
1534
- onStarted?.();
1535
- const cap = Math.min(1e3 * 2 ** Math.min(attempt++, 16), options.retryInterval ?? agentDefaults.retryIntervalMs);
1536
- const delayMs = Math.random() * cap;
1537
- await session.reportRetry(delayMs);
1538
- try {
1539
- await setTimeout$1(delayMs, void 0, { signal });
1540
- } catch (error) {
1541
- if (!signal?.aborted) throw error;
1724
+ }).finally(() => clearTimeout(timer));
1725
+ const studio = newWebSocketRpcSession(socket, agent);
1726
+ studio.onRpcBroken(() => socket.close());
1727
+ return {
1728
+ studio,
1729
+ closed,
1730
+ close: () => {
1731
+ studio[Symbol.dispose]();
1732
+ socket.close();
1542
1733
  }
1543
- }
1544
- return "shutdown";
1545
- }
1546
- //#endregion
1547
- //#region src/runtime/client.ts
1548
- /** Compatibility facade over the shared connection loop. */
1549
- function createClient({ onAuthRequired, ...options }) {
1550
- const shutdown = new AbortController();
1551
- const started = Promise.withResolvers();
1552
- let resolved = false;
1553
- let running;
1734
+ };
1735
+ };
1736
+ async function runSession({ options, openRpc, url, instanceId }) {
1737
+ const { hooks, signal, heartbeatInterval, token, studioUrl, version: version$2 } = options;
1738
+ const session = {
1739
+ connected: Promise.withResolvers(),
1740
+ closed: false
1741
+ };
1742
+ const rpc = openRpc({
1743
+ url,
1744
+ token,
1745
+ instanceId,
1746
+ agent: new Agent({
1747
+ options,
1748
+ session
1749
+ })
1750
+ });
1751
+ signal?.addEventListener("abort", rpc.close, { once: true });
1752
+ let timer;
1753
+ const heartbeat = async () => {
1754
+ let deadline;
1755
+ const timedOut = new Promise((resolve) => deadline = setTimeout(resolve, PING_TIMEOUT_MS, true));
1756
+ const failed = await Promise.race([Promise.resolve(rpc.studio.ping()).then(() => false, () => true), timedOut]);
1757
+ clearTimeout(deadline);
1758
+ if (failed) return rpc.close();
1759
+ if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval);
1760
+ };
1761
+ session.connected.promise.then(async (info) => {
1762
+ await emit(hooks, "studio:connected", {
1763
+ ...info,
1764
+ url: studioUrl,
1765
+ versions: {
1766
+ studio: info.studioVersion,
1767
+ kubb: version,
1768
+ agent: version$2
1769
+ }
1770
+ });
1771
+ if (!session.closed) timer = setTimeout(heartbeat, heartbeatInterval);
1772
+ }, () => {});
1773
+ const close = await rpc.closed;
1774
+ session.closed = true;
1775
+ clearTimeout(timer);
1776
+ signal?.removeEventListener("abort", rpc.close);
1777
+ session.connected.reject(/* @__PURE__ */ new Error("The socket closed before Studio called connect()"));
1778
+ session.active?.abort();
1779
+ await session.active?.settled;
1554
1780
  return {
1555
- connect() {
1556
- running ??= runConnection({
1557
- credentials: { token: options.token },
1558
- clientOptions: () => options,
1559
- signal: shutdown.signal,
1560
- onStarted: () => {
1561
- resolved = true;
1562
- started.resolve();
1563
- },
1564
- onTokenRejected: async ({ error }) => {
1565
- if (!resolved) throw error;
1566
- onAuthRequired?.(error);
1567
- return null;
1568
- }
1569
- }).then(() => started.resolve(), (error) => started.reject(error));
1570
- return started.promise;
1781
+ ...close,
1782
+ connected: session.info !== void 0
1783
+ };
1784
+ }
1785
+ /**
1786
+ * The connection loop with a swappable transport. {@link connectAgent} passes a real WebSocket.
1787
+ */
1788
+ async function runAgent({ options, openRpc }) {
1789
+ const root = options.root ?? process$1.cwd();
1790
+ const resolved = {
1791
+ ...options,
1792
+ studioUrl: options.studioUrl ?? "https://kubb.studio",
1793
+ root,
1794
+ configFile: path.resolve(root, options.configPath),
1795
+ permissions: {
1796
+ allowWrite: false,
1797
+ allowConfigEdit: false,
1798
+ allowExec: false,
1799
+ allowRead: false,
1800
+ ...options.permissions
1571
1801
  },
1572
- disconnect() {
1573
- shutdown.abort();
1574
- }
1802
+ hooks: options.hooks ?? new Hookable(),
1803
+ maxRetryDelay: options.maxRetryDelay ?? MAX_RETRY_DELAY_MS,
1804
+ heartbeatInterval: Math.min(options.heartbeatInterval ?? HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS)
1575
1805
  };
1806
+ const { studioUrl, hooks, signal, maxRetryDelay } = resolved;
1807
+ const url = secureUrl({
1808
+ studioUrl,
1809
+ path: AGENT_SOCKET_PATH,
1810
+ socket: true
1811
+ });
1812
+ const instanceId = randomUUID();
1813
+ let attempt = 0;
1814
+ while (!signal?.aborted) {
1815
+ const { code, reason, connected } = await runSession({
1816
+ options: resolved,
1817
+ openRpc,
1818
+ url,
1819
+ instanceId
1820
+ });
1821
+ if (signal?.aborted) return;
1822
+ await emit(hooks, "studio:disconnected", {
1823
+ code,
1824
+ reason
1825
+ });
1826
+ if (code === AgentCloseCode.UNAUTHORIZED) throw new InvalidAgentTokenError(studioUrl);
1827
+ if (code === AgentCloseCode.INCOMPATIBLE) throw new IncompatibleAgentError({
1828
+ studioUrl,
1829
+ detail: reason
1830
+ });
1831
+ if (code === AgentCloseCode.SUPERSEDED) return;
1832
+ if (connected) attempt = 0;
1833
+ const delayMs = Math.random() * Math.min(1e3 * 2 ** Math.min(attempt++, 16), maxRetryDelay);
1834
+ await emit(hooks, "studio:reconnecting", { delayMs });
1835
+ await setTimeout$1(delayMs, void 0, { signal }).catch(() => {});
1836
+ }
1837
+ }
1838
+ /**
1839
+ * Connects this project to Kubb Studio and serves its commands until `signal` aborts. Reconnects
1840
+ * with jittered backoff, and resolves when another process of the agent takes over. Rejects with
1841
+ * {@link InvalidAgentTokenError} so the host can pair again, or {@link IncompatibleAgentError}.
1842
+ *
1843
+ * @example
1844
+ * ```ts
1845
+ * const hooks = new Hookable<KubbHooks>()
1846
+ * hooks.hook('studio:connected', ({ agentSlug }) => console.log(`Connected as ${agentSlug}`))
1847
+ *
1848
+ * await connectAgent({ token, configPath: 'kubb.config.ts', loadConfig, version: '1.0.0', hooks, signal })
1849
+ * ```
1850
+ */
1851
+ function connectAgent(options) {
1852
+ return runAgent({
1853
+ options,
1854
+ openRpc: openWebSocketRpc
1855
+ });
1576
1856
  }
1577
1857
  //#endregion
1578
- //#region src/operations/pair.ts
1858
+ //#region src/pair.ts
1579
1859
  /** Labels, not secrets: a person approving the code in the browser is what authorizes a pairing. */
1580
1860
  const CLIENT_IDS = {
1581
1861
  cli: "kubb-cli",
@@ -1607,30 +1887,33 @@ var PairingDeniedError = class extends Error {
1607
1887
  }
1608
1888
  };
1609
1889
  /**
1610
- * Asks Studio for a pairing code. The machine token travels with the request and is stored against
1611
- * the code, so approval knows which machine it is pairing: the same machine pairing twice rotates
1612
- * one agent's token instead of creating a second agent.
1890
+ * Asks Studio for a pairing code, sending the hashed machine id with it.
1613
1891
  */
1614
- async function startPairing({ studioUrl = agentDefaults.studioUrl, type, name, hostname, signal }) {
1892
+ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
1615
1893
  try {
1616
- return await ofetch(`${studioUrl}/api/auth/device/code`, {
1894
+ const pairing = await ofetch(secureUrl({
1895
+ studioUrl,
1896
+ path: "/api/auth/device/code"
1897
+ }).href, {
1617
1898
  method: "POST",
1618
1899
  body: {
1619
1900
  client_id: type === "cli" ? CLIENT_IDS.cli : CLIENT_IDS.agent,
1620
1901
  name,
1621
1902
  hostname,
1622
- machine_token: await getMachineToken(),
1903
+ machine_token: hash("sha256", machineId),
1623
1904
  agent_kind: type === "cli" ? void 0 : type
1624
1905
  },
1625
1906
  signal
1626
1907
  });
1908
+ if (typeof pairing?.device_code !== "string") throw new Error("Kubb Studio returned no pairing code");
1909
+ return pairing;
1627
1910
  } catch (error) {
1628
1911
  if (signal?.aborted) throw new PairingCanceledError();
1629
1912
  throw error;
1630
1913
  }
1631
1914
  }
1632
1915
  function isPairingResult(response) {
1633
- return !!response && typeof response === "object" && "token" in response && typeof response.token === "string";
1916
+ return "token" in response && typeof response.token === "string";
1634
1917
  }
1635
1918
  /**
1636
1919
  * Polls until the user approves or denies, honoring the server's `slow_down` back-off.
@@ -1642,7 +1925,7 @@ function isPairingResult(response) {
1642
1925
  * @throws {PairingDeniedError} when the pairing is denied in the browser.
1643
1926
  * @throws {PairingCanceledError} when `signal` aborts.
1644
1927
  */
1645
- async function pollForPairingToken({ studioUrl = agentDefaults.studioUrl, session, signal, onRetry }) {
1928
+ async function pollForPairingToken({ studioUrl = defaultStudioUrl, session, signal, onRetry }) {
1646
1929
  const deadline = Date.now() + (session.expires_in > 0 ? session.expires_in : 600) * 1e3;
1647
1930
  let intervalMs = (session.interval > 0 ? session.interval : 5) * 1e3;
1648
1931
  while (Date.now() < deadline) {
@@ -1654,19 +1937,24 @@ async function pollForPairingToken({ studioUrl = agentDefaults.studioUrl, sessio
1654
1937
  }
1655
1938
  let response;
1656
1939
  try {
1657
- response = await ofetch(`${studioUrl}/api/agent/token`, {
1940
+ const { status, _data } = await ofetch.raw(secureUrl({
1941
+ studioUrl,
1942
+ path: "/api/agent/token"
1943
+ }).href, {
1658
1944
  method: "POST",
1659
1945
  body: { device_code: session.device_code },
1660
- ignoreResponseError: true,
1661
- signal
1946
+ signal,
1947
+ ignoreResponseError: true
1662
1948
  });
1949
+ if (status >= 500 || !_data || typeof _data !== "object") throw new Error(`Kubb Studio answered with status ${status}`);
1950
+ response = _data;
1663
1951
  } catch (error) {
1664
1952
  if (signal?.aborted) throw new PairingCanceledError();
1665
1953
  onRetry?.(toError(error));
1666
1954
  continue;
1667
1955
  }
1668
1956
  if (isPairingResult(response)) return response;
1669
- if (!response || typeof response !== "object" || !("error" in response) || typeof response.error !== "string") throw new Error("Kubb Studio returned an empty pairing response, pair again");
1957
+ if (!("error" in response) || typeof response.error !== "string") throw new Error("Kubb Studio returned an empty pairing response, pair again");
1670
1958
  if (response.error === "authorization_pending") continue;
1671
1959
  if (response.error === "slow_down") {
1672
1960
  intervalMs += 5e3;
@@ -1698,6 +1986,212 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
1698
1986
  }
1699
1987
  }
1700
1988
  //#endregion
1701
- export { AGENT_INSTANCE_HEADER, AgentCloseCode, IncompatibleAgentError, InvalidAgentTokenError, PairingCanceledError, PairingDeniedError, PairingExpiredError, connectWebSocketRpc, createAgent, createClient, createFileStorage, createJob, defaultStudioUrl, generationEventTypes, machineTokenFrom, pairAgent, pollForPairingToken, runConnection, setStorage, startPairing, waitForJob };
1989
+ //#region src/snapshot.ts
1990
+ const gzipAsync = promisify(gzip);
1991
+ const UPLOAD_TIMEOUT_MS = 12e4;
1992
+ const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
1993
+ /**
1994
+ * Maps a generated file's path to its place inside the tarball, stripping everything before a
1995
+ * `src`/`dist` segment and any `..`/empty path segment so a crafted file name cannot escape the
1996
+ * `package/` root.
1997
+ */
1998
+ function packagePath(filePath) {
1999
+ const normalized = filePath.replaceAll("\\", "/");
2000
+ return `package/${(normalized.match(/\/(?:src|dist)\/.*$/)?.[0].slice(1) ?? normalized.replace(/^\/+/, "")).split("/").filter((part) => part && part !== "." && part !== "..").join("/")}`;
2001
+ }
2002
+ /**
2003
+ * Splits a tarball entry path into the legacy 100-byte `name` field and, when the path does not
2004
+ * fit, the 155-byte USTAR `prefix` field that extends it. Throws rather than silently truncating
2005
+ * a path the format cannot address (max 256 bytes: 100 name + 1 separator + 155 prefix).
2006
+ */
2007
+ function splitEntryPath(path) {
2008
+ if (Buffer.byteLength(path, "utf8") <= 100) return {
2009
+ name: path,
2010
+ prefix: ""
2011
+ };
2012
+ for (let i = path.length - 1; i >= 0; i--) {
2013
+ if (path[i] !== "/") continue;
2014
+ const prefix = path.slice(0, i);
2015
+ const name = path.slice(i + 1);
2016
+ if (Buffer.byteLength(prefix, "utf8") <= 155 && Buffer.byteLength(name, "utf8") <= 100) return {
2017
+ name,
2018
+ prefix
2019
+ };
2020
+ }
2021
+ throw new Error(`Snapshot path is too long for a tar entry: ${path}`);
2022
+ }
2023
+ function header(path, size) {
2024
+ const { name, prefix } = splitEntryPath(path);
2025
+ const value = Buffer.alloc(512);
2026
+ value.write(name, 0, "utf8");
2027
+ value.write("0000644\0", 100, "ascii");
2028
+ value.write("0000000\0", 108, "ascii");
2029
+ value.write("0000000\0", 116, "ascii");
2030
+ value.write(`${size.toString(8).padStart(11, "0")}\0`, 124, "ascii");
2031
+ value.write("03560116604\0", 136, "ascii");
2032
+ value.fill(32, 148, 156);
2033
+ value.write("0", 156, "ascii");
2034
+ value.write("ustar\0", 257, "ascii");
2035
+ value.write("00", 263, "ascii");
2036
+ value.write("0000000\0", 265, "ascii");
2037
+ value.write("0000000\0", 297, "ascii");
2038
+ value.write(prefix, 345, "utf8");
2039
+ const checksum = [...value].reduce((sum, byte) => sum + byte, 0);
2040
+ value.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, "ascii");
2041
+ return value;
2042
+ }
2043
+ /**
2044
+ * Packs a generation's files into a gzipped, npm-installable tarball: a `package/` root with the
2045
+ * generated sources, a `tsdown`-built `dist/` (esm + cjs), and a `package.json` manifest.
2046
+ */
2047
+ async function createSnapshotPackage({ files, packageInfo }) {
2048
+ const root = await mkdtemp(join(tmpdir(), "kubb-snapshot-"));
2049
+ const dist = join(root, "dist");
2050
+ const resolvedPaths = Object.entries(files).map(([name, content]) => ({
2051
+ name,
2052
+ content,
2053
+ target: packagePath(name)
2054
+ }));
2055
+ const targetOwners = /* @__PURE__ */ new Map();
2056
+ for (const { name, target } of resolvedPaths) {
2057
+ const owner = targetOwners.get(target);
2058
+ if (owner) throw new Error(`Snapshot has two generated files that sanitize to the same path "${target}": "${owner}" and "${name}"`);
2059
+ targetOwners.set(target, name);
2060
+ }
2061
+ try {
2062
+ await mkdir(dist);
2063
+ await Promise.all(resolvedPaths.map(async ({ content, target }) => {
2064
+ const path = join(root, target.slice(8));
2065
+ await mkdir(join(path, ".."), { recursive: true });
2066
+ await writeFile(path, content);
2067
+ }));
2068
+ const sourceEntries = resolvedPaths.filter(({ name }) => /\.(?:[cm]?[jt]sx?)$/.test(name)).map(({ target }) => join(root, target.slice(8)));
2069
+ if (sourceEntries.length) {
2070
+ const { build } = await import("tsdown");
2071
+ await build({
2072
+ entry: sourceEntries,
2073
+ outDir: dist,
2074
+ format: ["esm", "cjs"],
2075
+ dts: false,
2076
+ sourcemap: false,
2077
+ unbundle: true,
2078
+ report: false,
2079
+ logLevel: "silent",
2080
+ fixedExtension: true
2081
+ });
2082
+ }
2083
+ const builtEntries = await Promise.all((await fsStorage().readKeys(dist)).map(async (key) => [`package/dist/${key}`, await readFile(join(dist, key), "utf8")]));
2084
+ const builtPaths = new Set(builtEntries.map(([path]) => path));
2085
+ const hasBarrel = builtPaths.has("package/dist/index.mjs") && builtPaths.has("package/dist/index.cjs");
2086
+ const barrelFields = hasBarrel ? {
2087
+ main: "./dist/index.cjs",
2088
+ module: "./dist/index.mjs"
2089
+ } : {};
2090
+ const barrelExport = hasBarrel ? { ".": {
2091
+ import: "./dist/index.mjs",
2092
+ require: "./dist/index.cjs"
2093
+ } } : {};
2094
+ const entries = {
2095
+ "package/package.json": JSON.stringify({
2096
+ ...packageInfo,
2097
+ type: "module",
2098
+ ...barrelFields,
2099
+ exports: {
2100
+ ...barrelExport,
2101
+ "./*": {
2102
+ import: "./dist/*.mjs",
2103
+ require: "./dist/*.cjs"
2104
+ }
2105
+ }
2106
+ }, null, 2),
2107
+ ...Object.fromEntries(resolvedPaths.map(({ content, target }) => [target, content])),
2108
+ ...Object.fromEntries(builtEntries)
2109
+ };
2110
+ const chunks = [];
2111
+ for (const [name, content] of Object.entries(entries)) {
2112
+ const bytes = Buffer.from(content);
2113
+ chunks.push(header(name, bytes.length), bytes, Buffer.alloc((512 - bytes.length % 512) % 512));
2114
+ }
2115
+ return await gzipAsync(Buffer.concat([...chunks, Buffer.alloc(1024)]));
2116
+ } finally {
2117
+ await rm(root, {
2118
+ recursive: true,
2119
+ force: true
2120
+ });
2121
+ }
2122
+ }
2123
+ function failureMessage({ status, _data }) {
2124
+ const upgrade = _data?.data?.upgradeUrl ? ` Upgrade at ${_data.data.upgradeUrl}.` : "";
2125
+ return `Kubb Studio refused the snapshot (status ${status})${_data?.message ? `: ${_data.message}` : ""}.${upgrade}`;
2126
+ }
2127
+ /**
2128
+ * Generates the project, packs it as an npm tarball, and publishes it to Studio in one
2129
+ * `POST /api/snapshots` request.
2130
+ *
2131
+ * @example
2132
+ * ```ts
2133
+ * const snapshot = await createSnapshot({
2134
+ * apiKey: process.env.KUBB_TOKEN!,
2135
+ * config,
2136
+ * id: 'gh:123:pr-4',
2137
+ * name: 'acme/api#4',
2138
+ * packageName: '@acme/api',
2139
+ * version: '1.0.0',
2140
+ * })
2141
+ * console.log(snapshot.url, snapshot.changes)
2142
+ * ```
2143
+ */
2144
+ async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, config, hooks, signal, ...metadata }) {
2145
+ const url = secureUrl({
2146
+ studioUrl,
2147
+ path: "/api/snapshots"
2148
+ });
2149
+ const generated = await generate({
2150
+ config,
2151
+ hooks,
2152
+ signal,
2153
+ allowExec: true
2154
+ });
2155
+ const files = Object.fromEntries(await Promise.all([...generated.paths].map(async (path) => {
2156
+ const content = await generated.storage.readItem(resolve(generated.root, path));
2157
+ if (content === null) throw new Error(`The generation listed ${path} but did not keep its content`);
2158
+ return [path, content];
2159
+ })));
2160
+ const { peerDependencies, missingDependencies } = await resolvePeerDependencies(config.plugins.map(({ name }) => name));
2161
+ const missing = missingDependencies.filter((dependency) => !BUNDLED_DEPENDENCIES.includes(dependency));
2162
+ if (missing.length) throw new Error(`Missing dependencies: ${missing.join(", ")}`);
2163
+ const bytes = await createSnapshotPackage({
2164
+ files,
2165
+ packageInfo: {
2166
+ name: metadata.packageName,
2167
+ version: metadata.version,
2168
+ peerDependencies
2169
+ }
2170
+ });
2171
+ if (bytes.length > 52428800) throw new Error(`The snapshot is ${Math.ceil(bytes.length / 1024 / 1024)} MB, over the ${MAX_SNAPSHOT_BYTES / 1024 / 1024} MB limit`);
2172
+ const hashes = Object.fromEntries(Object.entries(files).map(([path, content]) => [path, hashOf(content)]));
2173
+ const body = new FormData();
2174
+ body.set("metadata", JSON.stringify({
2175
+ ...metadata,
2176
+ hashes,
2177
+ peerDependencies
2178
+ }));
2179
+ body.set("tarball", new Blob([new Uint8Array(bytes)], { type: "application/gzip" }), "snapshot.tgz");
2180
+ const timeout = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
2181
+ const response = await ofetch.raw(url.href, {
2182
+ method: "POST",
2183
+ headers: { "x-api-key": apiKey },
2184
+ body,
2185
+ redirect: "error",
2186
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
2187
+ ignoreResponseError: true
2188
+ });
2189
+ if (!response.ok) throw new Error(failureMessage(response));
2190
+ const snapshot = response._data?.snapshot;
2191
+ if (!snapshot) throw new Error(`Kubb Studio returned no snapshot (status ${response.status})`);
2192
+ return snapshot;
2193
+ }
2194
+ //#endregion
2195
+ export { IncompatibleAgentError, InvalidAgentTokenError, PairingCanceledError, PairingDeniedError, PairingExpiredError, connectAgent, createSnapshot, defaultStudioUrl, pairAgent };
1702
2196
 
1703
2197
  //# sourceMappingURL=index.js.map