@kubb/studio 5.18.8 → 5.19.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/README.md CHANGED
@@ -113,8 +113,9 @@ Every permission is off by default, and each covers one trust boundary:
113
113
  | `allowConfigEdit` | Studio may change plugin options in `kubb.config.ts`. |
114
114
  | `allowRead` | Studio may read existing output files and the files a generation produced. |
115
115
  | `allowReadAst` | Studio may read back the parsed spec (the Kubb AST). |
116
+ | `allowFileRefs` | A `$ref` in the spec may read a local file outside the project. |
116
117
 
117
- A sandbox never writes or edits config, and always allows reads.
118
+ A sandbox never writes or edits config. A sandbox the host declares with `agentType: 'sandbox'` or `'global'` always allows reads.
118
119
 
119
120
  ## Pairing
120
121
 
package/dist/index.cjs CHANGED
@@ -20,7 +20,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- const require_protocol = require("./protocol-B4wWGPon.cjs");
23
+ const require_protocol = require("./protocol-CmX5XTPc.cjs");
24
24
  let node_crypto = require("node:crypto");
25
25
  let node_fs = require("node:fs");
26
26
  let node_fs_promises = require("node:fs/promises");
@@ -50,6 +50,63 @@ node_net = __toESM(node_net, 1);
50
50
  let node_stream = require("node:stream");
51
51
  let ofetch = require("ofetch");
52
52
  let node_zlib = require("node:zlib");
53
+ // ../../internals/utils/src/promise.ts
54
+ /**
55
+ * Returns the value cached under `key` in `store`, computing and storing it on the first call.
56
+ * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
57
+ * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
58
+ *
59
+ * @example
60
+ * `const refs = memo(refCache, node, () => collectRefs(node))`
61
+ */
62
+ function memo(store, key, compute) {
63
+ const cached = store.get(key);
64
+ if (cached !== void 0 || store.has(key)) return cached;
65
+ const value = compute();
66
+ store.set(key, value);
67
+ return value;
68
+ }
69
+ function createStore({ weak, max } = {}) {
70
+ if (weak) return /* @__PURE__ */ new WeakMap();
71
+ const entry = /* @__PURE__ */ new Map();
72
+ if (max === void 0) return entry;
73
+ const set = (key, value) => {
74
+ if (entry.size >= max) entry.clear();
75
+ entry.set(key, value);
76
+ };
77
+ if (max !== 1) return {
78
+ has: (key) => entry.has(key),
79
+ get: (key) => entry.get(key),
80
+ set
81
+ };
82
+ const touch = (key) => {
83
+ if (!entry.has(key)) return false;
84
+ set(key, entry.get(key));
85
+ return true;
86
+ };
87
+ return {
88
+ has: touch,
89
+ get: (key) => touch(key) ? entry.get(key) : void 0,
90
+ set
91
+ };
92
+ }
93
+ memo.create = createStore;
94
+ /**
95
+ * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
96
+ * takes the next item the moment it frees up instead of waiting for a batch to drain.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
101
+ * ```
102
+ */
103
+ async function inParallel({ items, limit, run }) {
104
+ const queue = items.entries();
105
+ const worker = async () => {
106
+ for (const [index, item] of queue) await run(item, index);
107
+ };
108
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
109
+ }
53
110
  // ../../internals/utils/src/casing.ts
54
111
  /**
55
112
  * Shared implementation for camelCase and PascalCase conversion.
@@ -64,16 +121,10 @@ function convert(text, pascal) {
64
121
  return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
65
122
  }).join("").replace(/[^a-zA-Z0-9]/g, "");
66
123
  }
67
- const cache = /* @__PURE__ */ new Map();
68
- const cacheLimit = 1e5;
124
+ const cache = memo.create({ max: 1e5 });
69
125
  function toCamelOrPascal(text, pascal) {
70
126
  const key = `${pascal ? "P" : "c"}${text}`;
71
- const cached = cache.get(key);
72
- if (cached !== void 0) return cached;
73
- const result = convert(text, pascal);
74
- if (cache.size >= cacheLimit) cache.clear();
75
- cache.set(key, result);
76
- return result;
127
+ return memo(cache, key, () => convert(text, pascal));
77
128
  }
78
129
  /**
79
130
  * Converts `text` to camelCase.
@@ -199,60 +250,8 @@ function isPathInside(path, parent) {
199
250
  const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
200
251
  return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
201
252
  }
202
- // ../../internals/utils/src/promise.ts
203
- /**
204
- * Returns the value cached under `key` in `store`, computing and storing it on the first call.
205
- * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive
206
- * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.
207
- *
208
- * @example
209
- * `const refs = memo(refCache, node, () => collectRefs(node))`
210
- */
211
- function memo(store, key, compute) {
212
- const cached = store.get(key);
213
- if (cached !== void 0 || store.has(key)) return cached;
214
- const value = compute();
215
- store.set(key, value);
216
- return value;
217
- }
218
- function createStore({ type }) {
219
- if (type === "weak") return /* @__PURE__ */ new WeakMap();
220
- const entry = /* @__PURE__ */ new Map();
221
- if (type === "map") return entry;
222
- const set = (key, value) => {
223
- entry.clear();
224
- entry.set(key, value);
225
- };
226
- const touch = (key) => {
227
- if (!entry.has(key)) return false;
228
- set(key, entry.get(key));
229
- return true;
230
- };
231
- return {
232
- has: touch,
233
- get: (key) => touch(key) ? entry.get(key) : void 0,
234
- set
235
- };
236
- }
237
- memo.create = createStore;
238
- /**
239
- * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
240
- * takes the next item the moment it frees up instead of waiting for a batch to drain.
241
- *
242
- * @example
243
- * ```ts
244
- * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
245
- * ```
246
- */
247
- async function inParallel({ items, limit, run }) {
248
- const queue = items.entries();
249
- const worker = async () => {
250
- for (const [index, item] of queue) await run(item, index);
251
- };
252
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
253
- }
254
253
  // package.json
255
- var version = "5.18.8";
254
+ var version = "5.19.1";
256
255
  // ../../internals/shared/src/constants.ts
257
256
  /**
258
257
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -389,6 +388,22 @@ function isOutputValue({ key, value }) {
389
388
  function pickOutput(output) {
390
389
  return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)));
391
390
  }
391
+ /**
392
+ * Returns the first `output.path` in `value`, at any depth (`override` entries included), that is
393
+ * absolute or climbs out of the folder it resolves against.
394
+ */
395
+ function findEscapingOutputPath(value) {
396
+ if (!Array.isArray(value) && !isPlainObject(value)) return void 0;
397
+ const output = isPlainObject(value) ? value.output : void 0;
398
+ if (isPlainObject(output) && typeof output.path === "string") {
399
+ const normalized = node_path.default.posix.normalize(output.path.replaceAll("\\", "/"));
400
+ if (node_path.default.posix.isAbsolute(normalized) || /^[a-z]:/i.test(output.path) || normalized === ".." || normalized.startsWith("../")) return output.path;
401
+ }
402
+ for (const entry of Object.values(value)) {
403
+ const found = findEscapingOutputPath(entry);
404
+ if (found !== void 0) return found;
405
+ }
406
+ }
392
407
  // ../../internals/shared/src/configFile/text.ts
393
408
  /**
394
409
  * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
@@ -484,13 +499,15 @@ function isNonEmptyString(value) {
484
499
  }
485
500
  /** Edits cross the wire, so their shape is checked before anything reads them. */
486
501
  function validateEdit(edit) {
487
- const { operation, plugin, config, path, kind, input } = typeof edit === "object" && edit !== null ? edit : {};
502
+ const { operation, plugin, config, path, kind, input, value, options } = typeof edit === "object" && edit !== null ? edit : {};
488
503
  if (typeof operation !== "string" || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`;
489
504
  if (config !== void 0 && typeof config !== "string" && !Number.isSafeInteger(config)) return "config must name an entry or give its index";
490
505
  if (operation === require_protocol.ConfigEditOperation.SET_INPUT) return typeof input === "string" && input.trim() !== "" ? void 0 : "the edit names no input";
491
506
  const isOption = OPTION_OPERATIONS.has(operation);
492
507
  const isOutput = OUTPUT_OPERATIONS.has(operation);
493
508
  if (!isOutput && !isNonEmptyString(plugin)) return "the edit names no plugin";
509
+ const escaping = findEscapingOutputPath(operation === require_protocol.ConfigEditOperation.SET_OPTION && Array.isArray(path) ? path.reduceRight((inner, key) => ({ [String(key)]: inner }), value) : options);
510
+ if (escaping !== void 0) return `output.path ${JSON.stringify(escaping)} resolves outside the output folder`;
494
511
  if (kind !== void 0) {
495
512
  if (typeof kind !== "string" || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`;
496
513
  const takesKind = operation === require_protocol.ConfigEditOperation.ADD_PLUGIN || operation === require_protocol.ConfigEditOperation.REMOVE_EXTENSION;
@@ -992,14 +1009,14 @@ function addPlugin({ source, parsed, config, edit, quote, extensions }) {
992
1009
  if (array ? array.type !== nodeTypes.arrayExpression : !isParser) return { reason: `${key} is not an array literal` };
993
1010
  const defaults = isParser && !array ? DEFAULT_PARSERS.filter((parser) => parser.importName !== importName) : [];
994
1011
  const imports = getImports(parsed.program);
995
- const missing = /* @__PURE__ */ new Map();
1012
+ const missing = memo.create();
996
1013
  for (const item of [...defaults, {
997
1014
  importName,
998
1015
  packageName: edit.plugin
999
1016
  }]) {
1000
1017
  const from = imports.get(item.importName)?.from;
1001
1018
  if (from && from !== item.packageName) return { reason: `${item.importName} is already imported from ${from}` };
1002
- if (!from) missing.set(item.packageName, [...missing.get(item.packageName) ?? [], item.importName]);
1019
+ if (!from) memo(missing, item.packageName, () => []).push(item.importName);
1003
1020
  }
1004
1021
  const call = `${importName}(${Object.keys(options).length ? printValue(options, quote) : ""})`;
1005
1022
  const next = array?.type === nodeTypes.arrayExpression ? appendItem(source, array, call) : appendItem(source, config, `parsers: [${[...defaults.map((parser) => `${parser.importName}()`), call].join(", ")}]`);
@@ -1149,13 +1166,13 @@ function applyEdit({ source, edit, extensions }) {
1149
1166
  function editConfig({ source, edits, extensions = /* @__PURE__ */ new Map() }) {
1150
1167
  let current = source;
1151
1168
  const outcomes = edits.map((edit) => {
1152
- const invalid = validateEdit(edit);
1153
- if (invalid) return {
1154
- edit,
1155
- applied: false,
1156
- reason: invalid
1157
- };
1158
1169
  try {
1170
+ const invalid = validateEdit(edit);
1171
+ if (invalid) return {
1172
+ edit,
1173
+ applied: false,
1174
+ reason: invalid
1175
+ };
1159
1176
  const result = applyEdit({
1160
1177
  source: current,
1161
1178
  edit,
@@ -1392,7 +1409,7 @@ function generationFailure(diagnostics) {
1392
1409
  * Runs one generation and returns the files it produced. The formatter, the linter, and
1393
1410
  * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
1394
1411
  */
1395
- async function generate({ config, hooks, signal, allowExec }) {
1412
+ async function generate({ config, hooks, signal, allowExec, fileRefs }) {
1396
1413
  const output = allowExec ? config.output : {
1397
1414
  ...config.output,
1398
1415
  format: false,
@@ -1404,7 +1421,8 @@ async function generate({ config, hooks, signal, allowExec }) {
1404
1421
  output
1405
1422
  }, {
1406
1423
  hooks,
1407
- signal
1424
+ signal,
1425
+ fileRefs
1408
1426
  });
1409
1427
  const result = await kubb.generate();
1410
1428
  if (!result.success) throw generationFailure(result.diagnostics);
@@ -1787,7 +1805,7 @@ const NO_BODY = /* @__PURE__ */ new Set([
1787
1805
  304
1788
1806
  ]);
1789
1807
  function notPublic(host) {
1790
- return /* @__PURE__ */ new Error(`${host} is not a public address, so a managed agent does not fetch from it`);
1808
+ return /* @__PURE__ */ new Error(`${host} is not a public address, so this agent does not fetch from it`);
1791
1809
  }
1792
1810
  function createLookup(blocked) {
1793
1811
  return (hostname, options, callback) => {
@@ -1839,8 +1857,8 @@ function request({ url, blocked, signal }) {
1839
1857
  */
1840
1858
  function createPublicFetch(blocked) {
1841
1859
  const publicFetch = async (input, init) => {
1842
- if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("A managed agent fetches by URL only");
1843
- if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("A managed agent only sends GET requests");
1860
+ if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("This agent fetches by URL only");
1861
+ if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("This agent only sends GET requests");
1844
1862
  let url = new URL(input);
1845
1863
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
1846
1864
  const response = await request({
@@ -1859,7 +1877,7 @@ function createPublicFetch(blocked) {
1859
1877
  }
1860
1878
  /**
1861
1879
  * Runs `run` with the global `fetch` limited to public addresses, then puts the original back.
1862
- * A managed agent runs one job at a time, so nothing else shares the window.
1880
+ * A sandbox or managed agent runs one job at a time, so nothing else shares the window.
1863
1881
  */
1864
1882
  async function withPublicFetch(run) {
1865
1883
  const original = globalThis.fetch;
@@ -2132,6 +2150,18 @@ function assertOutputPaths({ plugins, diskPlugins, root, outputPath }) {
2132
2150
  }
2133
2151
  }
2134
2152
  /**
2153
+ * The folders a `$ref` may read local files from on each kind of agent. Studio may have sent the
2154
+ * spec, so a shared agent gets none, and a managed agent only the git checkout it made itself. A
2155
+ * project agent gets its `root` and the folder of the file `input` in its own config. `undefined`
2156
+ * means no limit, which only `allowFileRefs` grants.
2157
+ */
2158
+ function resolveFileRefs({ agentType, allowFileRefs, root, input, checkoutDir }) {
2159
+ if (agentType === "sandbox" || agentType === "global") return [];
2160
+ if (agentType === "managed") return checkoutDir ? [checkoutDir] : [];
2161
+ if (allowFileRefs) return void 0;
2162
+ return typeof input === "string" && (0, _kubb_core.getInputKind)(input) === "file" ? [root, node_path.default.dirname(node_path.default.resolve(root, input))] : [root];
2163
+ }
2164
+ /**
2135
2165
  * Re-invokes the factory behind a disk adapter or parser with Studio's options merged over its own.
2136
2166
  * An instance carries live functions (`parse`, `print`, ...) that cannot survive JSON, so Studio's
2137
2167
  * options are a patch, not a replacement, and the factory is found from the disk instance itself: the
@@ -2223,6 +2253,7 @@ function secureUrl({ studioUrl, path, socket = false }) {
2223
2253
  }
2224
2254
  // src/connect.ts
2225
2255
  const HEARTBEAT_INTERVAL_MS = 3e4;
2256
+ const SHARED_AGENT_TYPES = /* @__PURE__ */ new Set(["sandbox", "global"]);
2226
2257
  const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
2227
2258
  const PING_TIMEOUT_MS = 1e4;
2228
2259
  const OPEN_TIMEOUT_MS = 5e3;
@@ -2348,14 +2379,25 @@ var Agent = class extends capnweb.RpcTarget {
2348
2379
  this.#session = session;
2349
2380
  }
2350
2381
  get #sandbox() {
2351
- return this.#session.info?.sandbox === true;
2382
+ return SHARED_AGENT_TYPES.has(this.#options.agentType) || this.#session.info?.sandbox === true;
2352
2383
  }
2353
2384
  get #managed() {
2354
- return this.#session.info?.managed === true;
2385
+ return this.#options.agentType === "managed" || this.#session.info?.managed === true;
2386
+ }
2387
+ get #agentType() {
2388
+ if (this.#sandbox) return "sandbox";
2389
+ if (this.#managed) return "managed";
2390
+ return this.#options.agentType;
2355
2391
  }
2356
2392
  get #permissions() {
2357
- const { permissions } = this.#options;
2358
- return this.#sandbox ? {
2393
+ const { permissions, agentType } = this.#options;
2394
+ const sandbox = SHARED_AGENT_TYPES.has(agentType);
2395
+ if (this.#managed) return {
2396
+ ...permissions,
2397
+ allowFileRefs: false
2398
+ };
2399
+ if (!this.#sandbox) return permissions;
2400
+ return {
2359
2401
  ...permissions,
2360
2402
  allowWrite: false,
2361
2403
  allowConfigEdit: false,
@@ -2363,9 +2405,10 @@ var Agent = class extends capnweb.RpcTarget {
2363
2405
  allowUpdate: false,
2364
2406
  allowRemove: false,
2365
2407
  allowSaveInput: false,
2366
- allowRead: true,
2367
- allowReadAst: true
2368
- } : permissions;
2408
+ allowFileRefs: false,
2409
+ allowRead: sandbox || permissions.allowRead,
2410
+ allowReadAst: sandbox || permissions.allowReadAst
2411
+ };
2369
2412
  }
2370
2413
  get #generations() {
2371
2414
  this.#store ??= createGenerationStore({
@@ -2587,7 +2630,8 @@ var Agent = class extends capnweb.RpcTarget {
2587
2630
  });
2588
2631
  const activePlugins = plugins ?? config.plugins;
2589
2632
  if (patch?.input && !this.#sandbox && !this.#managed) await emit(this.#options.hooks, "kubb:warn", { message: "Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox or managed agent" });
2590
- const checkout = this.#managed && studioInput !== void 0 && (0, _kubb_core.getInputKind)(studioInput) === "git" ? await (0, _kubb_core.checkoutGitInput)(studioInput, signal, {
2633
+ const managedInput = this.#managed ? studioInput ?? config.input : void 0;
2634
+ const checkout = typeof managedInput === "string" && (0, _kubb_core.getInputKind)(managedInput) === "git" ? await (0, _kubb_core.checkoutGitInput)(managedInput, signal, {
2591
2635
  publicOnly: true,
2592
2636
  authorization: input.gitAuth?.authorization
2593
2637
  }).catch((error) => this.#refuse({
@@ -2613,9 +2657,16 @@ var Agent = class extends capnweb.RpcTarget {
2613
2657
  },
2614
2658
  hooks: this.#options.hooks,
2615
2659
  signal,
2616
- allowExec: this.#permissions.allowWrite && this.#permissions.allowExec
2660
+ allowExec: this.#permissions.allowWrite && this.#permissions.allowExec,
2661
+ fileRefs: resolveFileRefs({
2662
+ agentType: this.#agentType,
2663
+ allowFileRefs: this.#permissions.allowFileRefs,
2664
+ root: this.#options.root,
2665
+ input: config.input,
2666
+ checkoutDir: checkout?.dir
2667
+ })
2617
2668
  });
2618
- const files = await (this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2669
+ const files = await (this.#sandbox || this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2619
2670
  await this.#generations.drop(jobId);
2620
2671
  await this.#logCommand("generate", getErrorMessage(error), input.requestedBy, true);
2621
2672
  throw error;
@@ -2710,7 +2761,7 @@ var Agent = class extends capnweb.RpcTarget {
2710
2761
  /**
2711
2762
  * Readies a `set-input` edit for the config file: a document is pointed at `openapi.yaml` (`openapi.json`
2712
2763
  * for JSON) in the project, one file per config entry, for `saveConfig` to write once the edit applies.
2713
- * A managed agent refuses a file path, as in a generation.
2764
+ * A managed agent refuses a file path, as in a generation. Every agent refuses a file path outside the project.
2714
2765
  */
2715
2766
  async #keepInput(edit) {
2716
2767
  if (edit?.operation !== require_protocol.ConfigEditOperation.SET_INPUT || typeof edit.input !== "string" || !edit.input.trim()) return edit;
@@ -2723,6 +2774,7 @@ var Agent = class extends capnweb.RpcTarget {
2723
2774
  }
2724
2775
  const kind = (0, _kubb_core.getInputKind)(edit.input);
2725
2776
  if (this.#managed && !MANAGED_INPUT_KINDS.has(kind)) return { reason: require_protocol.AgentMessage.MANAGED_INPUT_KIND };
2777
+ if ((kind === "file" || kind === "url" && !/^https?:/i.test(edit.input)) && !isPathInside(node_path.default.resolve(this.#options.root, edit.input), this.#options.root)) return { reason: "the input is a file outside the project" };
2726
2778
  if (kind !== "inline") return edit;
2727
2779
  const fileName = `openapi${edit.config === void 0 || edit.config === 0 ? "" : `-${String(edit.config).replace(/[^\w.-]/g, "-")}`}.${isJson(edit.input) ? "json" : "yaml"}`;
2728
2780
  return {
@@ -3133,6 +3185,7 @@ async function runAgent({ options, openRpc }) {
3133
3185
  ...options,
3134
3186
  studioUrl: options.studioUrl ?? "https://kubb.studio",
3135
3187
  root,
3188
+ agentType: options.agentType ?? "user",
3136
3189
  configFile: node_path.default.resolve(root, options.configPath),
3137
3190
  permissions: {
3138
3191
  allowWrite: false,
@@ -3141,6 +3194,7 @@ async function runAgent({ options, openRpc }) {
3141
3194
  allowUpdate: false,
3142
3195
  allowRemove: false,
3143
3196
  allowSaveInput: false,
3197
+ allowFileRefs: false,
3144
3198
  allowExec: false,
3145
3199
  allowRead: false,
3146
3200
  allowReadAst: false,