@kubb/studio 5.18.6 → 5.18.8

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.d.cts CHANGED
@@ -225,9 +225,10 @@ type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDepend
225
225
  */
226
226
  apiKey: string;
227
227
  /**
228
- * The project's Kubb config, generated like `kubb generate`: formatter, linter, and `output.postGenerate` included.
228
+ * Every entry of the project's Kubb config, generated like `kubb generate`: formatter, linter, and `output.postGenerate` included.
229
+ * One package holds the output of them all.
229
230
  */
230
- config: Config;
231
+ configs: Array<Config>;
231
232
  hooks?: Hookable<KubbHooks>;
232
233
  signal?: AbortSignal;
233
234
  };
@@ -236,13 +237,12 @@ type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDepend
236
237
  *
237
238
  * @example
238
239
  * ```ts
239
- * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, config, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
240
+ * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, configs, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
240
241
  * ```
241
242
  */
242
- export declare function createSnapshot({ studioUrl, apiKey, config, hooks, signal, ...metadata }: CreateSnapshotOptions): Promise<PublishedSnapshot>;
243
+ export declare function createSnapshot({ studioUrl, apiKey, configs, hooks, signal, ...metadata }: CreateSnapshotOptions): Promise<PublishedSnapshot>;
243
244
  /**
244
245
  * Hosted Kubb Studio URL, used when a host passes none.
245
246
  */
246
247
  export declare const defaultStudioUrl = "https://kubb.studio";
247
- export { type ConnectAgentOptions, type StudioConnectedContext, editConfig, editConfigFile };
248
- //# sourceMappingURL=index.d.cts.map
248
+ export { type ConnectAgentOptions, type StudioConnectedContext, editConfig, editConfigFile };
package/dist/index.d.ts CHANGED
@@ -225,9 +225,10 @@ type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDepend
225
225
  */
226
226
  apiKey: string;
227
227
  /**
228
- * The project's Kubb config, generated like `kubb generate`: formatter, linter, and `output.postGenerate` included.
228
+ * Every entry of the project's Kubb config, generated like `kubb generate`: formatter, linter, and `output.postGenerate` included.
229
+ * One package holds the output of them all.
229
230
  */
230
- config: Config;
231
+ configs: Array<Config>;
231
232
  hooks?: Hookable<KubbHooks>;
232
233
  signal?: AbortSignal;
233
234
  };
@@ -236,13 +237,12 @@ type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDepend
236
237
  *
237
238
  * @example
238
239
  * ```ts
239
- * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, config, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
240
+ * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, configs, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
240
241
  * ```
241
242
  */
242
- export declare function createSnapshot({ studioUrl, apiKey, config, hooks, signal, ...metadata }: CreateSnapshotOptions): Promise<PublishedSnapshot>;
243
+ export declare function createSnapshot({ studioUrl, apiKey, configs, hooks, signal, ...metadata }: CreateSnapshotOptions): Promise<PublishedSnapshot>;
243
244
  /**
244
245
  * Hosted Kubb Studio URL, used when a host passes none.
245
246
  */
246
247
  export declare const defaultStudioUrl = "https://kubb.studio";
247
- export { type ConnectAgentOptions, type StudioConnectedContext, editConfig, editConfigFile };
248
- //# sourceMappingURL=index.d.ts.map
248
+ export { type ConnectAgentOptions, type StudioConnectedContext, editConfig, editConfigFile };
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { a as AgentPermission, c as MAX_SNAPSHOT_BYTES, d as extensionKinds, i as AgentMessage, l as generationEventTypes, n as AGENT_SOCKET_PATH, r as AgentCloseCode, t as AGENT_INSTANCE_HEADER, u as ConfigEditOperation } from "./protocol-B6oWLc7W.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, hash, randomUUID } from "node:crypto";
4
- import { existsSync } from "node:fs";
5
- import { mkdir, mkdir as mkdir$1, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { existsSync, readFile, writeFile } from "node:fs";
5
+ import { mkdir, mkdir as mkdir$1, mkdtemp, rm, writeFile as writeFile$1 } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
7
7
  import path, { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
8
  import process$1 from "node:process";
9
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { x } from "tinyexec";
11
- import { Diagnostics, Hookable, cacheStorage, checkoutGitInput, createKubb, fsStorage, getInputKind, isPackageName, isPublicAddress, readInstalledPackages, resolveCacheDir, resolveMeta } from "@kubb/core";
11
+ import { Diagnostics, Hookable, Kubb, cacheStorage, checkoutGitInput, createKubb, fsStorage, getInputKind, isPackageName, isPublicAddress, readInstalledPackages, resolveCacheDir, resolveMeta } from "@kubb/core";
12
12
  import { RpcTarget, newWebSocketRpcSession } from "capnweb";
13
13
  import { pathToFileURL } from "node:url";
14
14
  import { stripVTControlCharacters } from "node:util";
@@ -127,7 +127,7 @@ function detect() {
127
127
  */
128
128
  async function read(path) {
129
129
  if (runtime.isBun) return Bun.file(path).text();
130
- return readFile(path, { encoding: "utf8" });
130
+ return new Promise((resolvePromise, reject) => readFile(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
131
131
  }
132
132
  /**
133
133
  * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.
@@ -143,11 +143,11 @@ async function writeRaw(path, content) {
143
143
  return;
144
144
  }
145
145
  try {
146
- await writeFile(resolved, content, { encoding: "utf-8" });
146
+ await new Promise((resolvePromise, reject) => writeFile(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
147
147
  } catch (error) {
148
148
  if (error.code !== "ENOENT") throw error;
149
- await mkdir(dirname(resolved), { recursive: true });
150
- await writeFile(resolved, content, { encoding: "utf-8" });
149
+ await mkdir$1(dirname(resolved), { recursive: true });
150
+ await new Promise((resolvePromise, reject) => writeFile(resolved, content, { encoding: "utf-8" }, (error) => error ? reject(error) : resolvePromise()));
151
151
  }
152
152
  }
153
153
  /**
@@ -173,6 +173,41 @@ function isPathInside(path, parent) {
173
173
  }
174
174
  // ../../internals/utils/src/promise.ts
175
175
  /**
176
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
177
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
178
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
179
+ *
180
+ * @example
181
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
182
+ */
183
+ function memo(store, key, compute) {
184
+ const cached = store.get(key);
185
+ if (cached !== void 0 || store.has(key)) return cached;
186
+ const value = compute();
187
+ store.set(key, value);
188
+ return value;
189
+ }
190
+ function createStore({ type }) {
191
+ if (type === "weak") return /* @__PURE__ */ new WeakMap();
192
+ const entry = /* @__PURE__ */ new Map();
193
+ if (type === "map") return entry;
194
+ const set = (key, value) => {
195
+ entry.clear();
196
+ entry.set(key, value);
197
+ };
198
+ const touch = (key) => {
199
+ if (!entry.has(key)) return false;
200
+ set(key, entry.get(key));
201
+ return true;
202
+ };
203
+ return {
204
+ has: touch,
205
+ get: (key) => touch(key) ? entry.get(key) : void 0,
206
+ set
207
+ };
208
+ }
209
+ memo.create = createStore;
210
+ /**
176
211
  * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
177
212
  * takes the next item the moment it frees up instead of waiting for a batch to drain.
178
213
  *
@@ -188,25 +223,8 @@ async function inParallel({ items, limit, run }) {
188
223
  };
189
224
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
190
225
  }
191
- // ../../internals/utils/src/time.ts
192
- /**
193
- * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
194
- * Rounds to 2 decimal places for sub-millisecond precision without noise.
195
- *
196
- * @example
197
- * ```ts
198
- * const start = process.hrtime()
199
- * doWork()
200
- * getElapsedMs(start) // 42.35
201
- * ```
202
- */
203
- function getElapsedMs(hrStart) {
204
- const [seconds, nanoseconds] = process.hrtime(hrStart);
205
- const ms = seconds * 1e3 + nanoseconds / 1e6;
206
- return Math.round(ms * 100) / 100;
207
- }
208
226
  // package.json
209
- var version = "5.18.6";
227
+ var version = "5.18.8";
210
228
  // ../../internals/shared/src/constants.ts
211
229
  /**
212
230
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -1360,11 +1378,7 @@ async function generate({ config, hooks, signal, allowExec }) {
1360
1378
  hooks,
1361
1379
  signal
1362
1380
  });
1363
- let input = null;
1364
- const unhook = kubb.hooks.hook("kubb:build:end", (ctx) => {
1365
- if (ctx.config === kubb.config) input = kubb.driver.inputNode;
1366
- });
1367
- const result = await kubb.generate().finally(unhook);
1381
+ const result = await kubb.generate();
1368
1382
  if (!result.success) throw generationFailure(result.diagnostics);
1369
1383
  const { storage, root } = kubb.config;
1370
1384
  return {
@@ -1374,7 +1388,7 @@ async function generate({ config, hooks, signal, allowExec }) {
1374
1388
  root,
1375
1389
  filePath: file.path
1376
1390
  }))),
1377
- input
1391
+ input: result.input
1378
1392
  };
1379
1393
  }
1380
1394
  /**
@@ -1704,15 +1718,6 @@ function createGenerationStream(hooks, jobId) {
1704
1718
  root = config.root;
1705
1719
  });
1706
1720
  for (const type of generationEventTypes) forward(type);
1707
- on("kubb:generation:end", ({ diagnostics = [], status, hrStart, filesCreated }) => {
1708
- if (!hrStart) return;
1709
- emitEvent("kubb:generation:summary", [{
1710
- duration: Math.round(getElapsedMs(hrStart)),
1711
- fileCount: filesCreated ?? 0,
1712
- failedPlugins: Diagnostics.failedPlugins(diagnostics).length,
1713
- status: status ?? "success"
1714
- }]);
1715
- });
1716
1721
  /**
1717
1722
  * Takes this generation's listeners off the session emitter. Safe to call twice.
1718
1723
  */
@@ -2657,7 +2662,7 @@ var Agent = class extends RpcTarget {
2657
2662
  let wroteDocument = false;
2658
2663
  for (const [index, edit] of kept.entries()) {
2659
2664
  if (!("document" in edit) || !edit.document || !outcomes[index].applied) continue;
2660
- await writeFile(path.join(this.#options.root, edit.document.fileName), edit.document.text, "utf-8");
2665
+ await writeFile$1(path.join(this.#options.root, edit.document.fileName), edit.document.text, "utf-8");
2661
2666
  wroteDocument = true;
2662
2667
  }
2663
2668
  const changed = written.changed || wroteDocument;
@@ -3411,7 +3416,7 @@ async function createSnapshotPackage({ files, packageInfo }) {
3411
3416
  const root = await mkdtemp(join(tmpdir(), "kubb-snapshot-"));
3412
3417
  const dist = join(root, "dist");
3413
3418
  try {
3414
- await mkdir$1(dist);
3419
+ await mkdir(dist);
3415
3420
  await Promise.all([...sources].map(async ([path, { content }]) => {
3416
3421
  await writeRaw(join(root, path), content);
3417
3422
  }));
@@ -3475,25 +3480,50 @@ async function createSnapshotPackage({ files, packageInfo }) {
3475
3480
  *
3476
3481
  * @example
3477
3482
  * ```ts
3478
- * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, config, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
3483
+ * const { url } = await createSnapshot({ apiKey: process.env.KUBB_TOKEN!, configs, id: 'gh:123:pr-4', name: 'acme/api#4', packageName: '@acme/api', version: '1.0.0' })
3479
3484
  * ```
3480
3485
  */
3481
- async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, config, hooks, signal, ...metadata }) {
3486
+ async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, configs, hooks, signal, ...metadata }) {
3482
3487
  const url = secureUrl({
3483
3488
  studioUrl,
3484
3489
  path: "/api/snapshots"
3485
3490
  });
3486
- const generated = await generate({
3487
- config: {
3488
- ...config,
3489
- storage: fsStorage()
3490
- },
3491
+ const buildConfigs = configs.map((config) => ({
3492
+ ...config,
3493
+ storage: fsStorage()
3494
+ }));
3495
+ const failures = [];
3496
+ const sources = /* @__PURE__ */ new Map();
3497
+ for await (const { success, error, diagnostics, files, kubb } of Kubb.generate(buildConfigs, {
3491
3498
  hooks,
3492
- signal,
3493
- allowExec: true
3494
- });
3495
- const files = Object.fromEntries(await Promise.all([...generated.paths].map(async (path) => {
3496
- const content = await generated.storage.readItem(resolve(generated.root, path));
3499
+ signal
3500
+ })) {
3501
+ if (!success) {
3502
+ failures.push(error ?? generationFailure(diagnostics));
3503
+ continue;
3504
+ }
3505
+ const { root } = kubb.config;
3506
+ for (const file of files) {
3507
+ const path = relativeStoragePath({
3508
+ root,
3509
+ filePath: file.path
3510
+ });
3511
+ const source = resolve(root, path);
3512
+ const owner = sources.get(path);
3513
+ if (owner && owner !== source) throw new Diagnostics.Error({
3514
+ code: Diagnostics.code.unknown,
3515
+ severity: "error",
3516
+ message: `Snapshot has two generated files at "${path}": "${owner}" and "${source}"`,
3517
+ help: "Give the config entries the same `root`, or output paths that do not overlap."
3518
+ });
3519
+ sources.set(path, source);
3520
+ }
3521
+ }
3522
+ if (failures.length === 1) throw failures[0];
3523
+ if (failures.length) throw new AggregateError(failures, failures.map(getErrorMessage).join("\n"));
3524
+ const storage = fsStorage();
3525
+ const files = Object.fromEntries(await Promise.all([...sources].map(async ([path, source]) => {
3526
+ const content = await storage.readItem(source);
3497
3527
  if (content === null) throw new Diagnostics.Error({
3498
3528
  code: Diagnostics.code.internalError,
3499
3529
  severity: "error",
@@ -3501,12 +3531,13 @@ async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, config, ho
3501
3531
  });
3502
3532
  return [path, content];
3503
3533
  })));
3504
- const pluginNames = config.plugins.map((plugin) => resolveMeta(plugin).name);
3505
- const installed = await readInstalledPackages({
3506
- root: config.root,
3534
+ const pluginNames = [...new Set(configs.flatMap((config) => config.plugins.map((plugin) => resolveMeta(plugin).name)))];
3535
+ const roots = [...new Set(configs.map((config) => config.root))];
3536
+ const installed = (await Promise.all(roots.map((root) => readInstalledPackages({
3537
+ root,
3507
3538
  packages: pluginNames.map(toPackageName),
3508
3539
  resolveFrom: ["kubb"]
3509
- });
3540
+ })))).flat();
3510
3541
  const packageOf = (name) => installed.find(({ manifest }) => manifest?.kind === "plugin" && manifest.name === name)?.package ?? toPackageName(name);
3511
3542
  const names = [...new Set(pluginNames.map(packageOf))];
3512
3543
  const peerDependencies = Object.fromEntries(installed.flatMap(({ package: name, version }) => names.includes(name) && version ? [[name, version]] : []));