@kubb/adapter-oas 5.25.0 → 5.25.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.cjs CHANGED
@@ -8,6 +8,8 @@ let node_url = require("node:url");
8
8
  let node_fs = require("node:fs");
9
9
  let _scalar_openapi_upgrader = require("@scalar/openapi-upgrader");
10
10
  let api_ref_bundler = require("api-ref-bundler");
11
+ let node_dns_promises = require("node:dns/promises");
12
+ let node_net = require("node:net");
11
13
  let js_yaml = require("js-yaml");
12
14
  let yaml = require("yaml");
13
15
  // kubb-extension.json
@@ -16,7 +18,7 @@ var compatibility = {
16
18
  "node": ">=22.22"
17
19
  };
18
20
  // package.json
19
- var version = "5.25.0";
21
+ var version = "5.25.1";
20
22
  // src/constants.ts
21
23
  /**
22
24
  * Default parser options applied when no explicit options are provided.
@@ -388,7 +390,7 @@ function isPathInside(path, parent) {
388
390
  const resolvedParent = (0, node_path.resolve)(parent);
389
391
  if (resolvedPath === resolvedParent) return true;
390
392
  const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
391
- return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
393
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${node_path.sep}`) && !(0, node_path.isAbsolute)(rel);
392
394
  }
393
395
  // src/oas.ts
394
396
  const legacyDocuments = /* @__PURE__ */ new WeakSet();
@@ -556,7 +558,12 @@ function createRefs(document) {
556
558
  applicable: true,
557
559
  value: pointerCache.get(pointer)
558
560
  };
559
- const current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj?.[key], document);
561
+ let current;
562
+ try {
563
+ current = pointer.split("/").filter(Boolean).map((token) => unescapePointerToken(globalThis.decodeURIComponent(token))).reduce((obj, key) => obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0, document);
564
+ } catch {
565
+ current = void 0;
566
+ }
560
567
  if (current) pointerCache.set(pointer, current);
561
568
  return {
562
569
  applicable: true,
@@ -589,21 +596,26 @@ function createRefs(document) {
589
596
  /**
590
597
  * Resolves a `$ref` to its parsed node via `parse`, guarding against cycles and memoizing per
591
598
  * instance. Returns `null` when the ref is currently being resolved (a cycle) or cannot be
592
- * resolved (e.g. a minimal document in a unit test).
599
+ * resolved (e.g. a minimal document in a unit test). An error from `parse` is thrown, so a bug
600
+ * in a converter is not mistaken for a missing ref.
593
601
  */
594
602
  function resolveNode(refPath, parse) {
595
603
  if (resolvingRefs.has(refPath)) return null;
596
604
  return memo(resolvedNodeCache, refPath, () => {
597
- let resolved = null;
605
+ let referenced;
598
606
  try {
599
- const referenced = resolve(refPath);
600
- if (referenced) {
601
- resolvingRefs.add(refPath);
602
- resolved = parse({ schema: referenced });
603
- resolvingRefs.delete(refPath);
604
- }
605
- } catch {}
606
- return resolved;
607
+ referenced = resolve(refPath);
608
+ } catch (error) {
609
+ if (_kubb_kit.Diagnostics.isError(error) && error.diagnostic.code === _kubb_kit.Diagnostics.code.refNotFound) return null;
610
+ throw error;
611
+ }
612
+ if (!referenced) return null;
613
+ resolvingRefs.add(refPath);
614
+ try {
615
+ return parse({ schema: referenced });
616
+ } finally {
617
+ resolvingRefs.delete(refPath);
618
+ }
607
619
  });
608
620
  }
609
621
  /**
@@ -907,6 +919,31 @@ const locate = (source, location) => {
907
919
  };
908
920
  // src/load/source.ts
909
921
  const urlRegExp = /^https?:\/+/i;
922
+ /** How long one request for a document or a `$ref` may take before Kubb gives up on it. */
923
+ const FETCH_TIMEOUT_MS = 3e4;
924
+ /**
925
+ * Whether `url` names a host that is loopback, private, link-local, or another address that is not
926
+ * public. A host that does not resolve, or not within the request timeout, counts as not public,
927
+ * because the check cannot prove it public. `signal` cancels the lookup.
928
+ *
929
+ * shortcut: the name is resolved again when `fetch` connects, so a host that changes its answer in
930
+ * between can still reach a private address. Upgrade to a pinned lookup, like `@kubb/studio`'s
931
+ * `publicFetch`, if a sandbox needs that guarantee.
932
+ */
933
+ async function isPrivateHost(url, { signal } = {}) {
934
+ const host = url.hostname.replace(/^\[|\]$/g, "");
935
+ if ((0, node_net.isIP)(host)) return !(0, _kubb_core.isPublicAddress)(host);
936
+ const deadline = withTimeout(signal);
937
+ deadline.throwIfAborted();
938
+ const stopped = new Promise((_, reject) => deadline.addEventListener("abort", () => reject(deadline.reason), { once: true }));
939
+ const addresses = await Promise.race([(0, node_dns_promises.lookup)(host, { all: true }), stopped]).catch(() => []);
940
+ signal?.throwIfAborted();
941
+ return addresses.length === 0 || addresses.some(({ address }) => !(0, _kubb_core.isPublicAddress)(address));
942
+ }
943
+ function withTimeout(signal) {
944
+ const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);
945
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
946
+ }
910
947
  /**
911
948
  * Node reports every connection failure as `TypeError: fetch failed` and keeps the useful part
912
949
  * (`connect ECONNREFUSED 127.0.0.1:8000`) on `cause`, one level deeper again when a host resolves
@@ -923,24 +960,34 @@ function helpForStatus(status) {
923
960
  if (status >= 500) return "The server failed while serving the document. Check that it is healthy, then run Kubb again.";
924
961
  return "Open the URL in a browser or with `curl` to see what the server returns, then point `input` at a URL that serves the OpenAPI document.";
925
962
  }
926
- async function fetchSource(url) {
963
+ async function fetchSource(url, { signal, publicOnly }) {
964
+ const deadline = withTimeout(signal);
927
965
  try {
928
- return await fetch(url);
966
+ const response = await fetch(url, {
967
+ signal: deadline,
968
+ redirect: publicOnly ? "error" : "follow"
969
+ });
970
+ return {
971
+ response,
972
+ body: response.ok ? await response.text() : ""
973
+ };
929
974
  } catch (error) {
975
+ if (signal?.aborted) throw signal.reason;
976
+ const reason = deadline.aborted ? `no answer within ${FETCH_TIMEOUT_MS / 1e3} seconds` : describeFetchFailure(error);
930
977
  throw new _kubb_kit.Diagnostics.Error({
931
978
  code: _kubb_kit.Diagnostics.code.inputUnreachable,
932
979
  severity: "error",
933
- message: `Cannot reach ${url.href}: ${describeFetchFailure(error)}`,
980
+ message: `Cannot reach ${url.href}: ${reason}`,
934
981
  help: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`.",
935
982
  location: { kind: "config" },
936
983
  cause: error instanceof Error ? error : void 0
937
984
  });
938
985
  }
939
986
  }
940
- async function readSource(sourcePath) {
987
+ async function readSource(sourcePath, options) {
941
988
  if (urlRegExp.test(sourcePath)) {
942
989
  const url = new URL(sourcePath);
943
- const response = await fetchSource(url);
990
+ const { response, body } = await fetchSource(url, options);
944
991
  if (!response.ok) {
945
992
  const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
946
993
  throw new _kubb_kit.Diagnostics.Error({
@@ -951,7 +998,7 @@ async function readSource(sourcePath) {
951
998
  location: { kind: "config" }
952
999
  });
953
1000
  }
954
- return response.text();
1001
+ return body;
955
1002
  }
956
1003
  return read(sourcePath);
957
1004
  }
@@ -959,8 +1006,8 @@ async function readSource(sourcePath) {
959
1006
  * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an
960
1007
  * object, Markdown is returned as-is (bundled inline rather than dereferenced).
961
1008
  */
962
- async function resolveSource(sourcePath, { remember } = {}) {
963
- const data = await readSource(sourcePath);
1009
+ async function resolveSource(sourcePath, { remember, ...options } = {}) {
1010
+ const data = await readSource(sourcePath, options);
964
1011
  if (sourcePath.toLowerCase().endsWith(".md")) return data;
965
1012
  const pathname = urlRegExp.test(sourcePath) ? new URL(sourcePath).pathname : sourcePath;
966
1013
  return parseYaml(data, {
@@ -1124,6 +1171,9 @@ async function isInsideFolders(filePath, folders) {
1124
1171
  * including one that fails, lands in `sources`. A `$ref` that cannot be read reports
1125
1172
  * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.
1126
1173
  * So does any local file from a URL input, and a local file outside every `fileRefs` folder.
1174
+ * With `fileRefs` set, a `$ref` URL on a host that is not public is refused too, and a redirect
1175
+ * fails, so a document sent to a sandboxed host cannot make it request internal addresses.
1176
+ * `signal` cancels every request.
1127
1177
  *
1128
1178
  * @example Local file
1129
1179
  * `const document = await bundleDocument('./openapi.yaml')`
@@ -1131,23 +1181,37 @@ async function isInsideFolders(filePath, folders) {
1131
1181
  * @example Remote URL
1132
1182
  * `const document = await bundleDocument('https://example.com/openapi.yaml')`
1133
1183
  */
1134
- async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } = {}) {
1184
+ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, signal } = {}) {
1135
1185
  const cache = memo.create();
1136
1186
  const toKey = (sourcePath) => urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath;
1137
1187
  const folders = urlRegExp.test(pathOrUrl) ? [] : fileRefs;
1188
+ const publicOnly = fileRefs !== void 0;
1138
1189
  const refused = /* @__PURE__ */ new Set();
1190
+ const refusedHelp = (refusedPath) => {
1191
+ if (urlRegExp.test(refusedPath)) return "This run only fetches `$ref` URLs on public hosts. Inline the schema, or serve it from a public URL. On your own agent, `--allow-file-refs` lifts the limit.";
1192
+ if (folders?.length) return "This run only reads local files inside the folders its host allows, such as the project. Move the file there or inline the schema. On your own agent, `--allow-file-refs` lifts the limit.";
1193
+ return "This input reads no local file. Inline the schema, or serve the file from a URL.";
1194
+ };
1139
1195
  let entry = pathOrUrl;
1140
1196
  let entryDocument = document;
1141
1197
  const resolver = async (sourcePath) => {
1142
1198
  if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return entryDocument;
1143
1199
  const key = toKey(sourcePath);
1144
- if (key !== toKey(pathOrUrl) && !urlRegExp.test(sourcePath) && folders && !await isInsideFolders(sourcePath, folders)) {
1200
+ const isRef = key !== toKey(pathOrUrl);
1201
+ const isUrl = urlRegExp.test(sourcePath);
1202
+ const refusedUrl = isRef && isUrl && publicOnly && await isPrivateHost(new URL(sourcePath), { signal });
1203
+ const refusedFile = isRef && !isUrl && folders !== void 0 && !await isInsideFolders(sourcePath, folders);
1204
+ if (refusedUrl || refusedFile) {
1145
1205
  refused.add(sourcePath);
1146
1206
  throw new Error(`Refused ${sourcePath}`);
1147
1207
  }
1148
1208
  return memo(cache, key, () => {
1149
1209
  sources.push(key);
1150
- return resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
1210
+ return resolveSource(sourcePath, {
1211
+ remember: !isRef,
1212
+ signal,
1213
+ publicOnly: publicOnly && isRef
1214
+ });
1151
1215
  });
1152
1216
  };
1153
1217
  const root = await resolver(pathOrUrl);
@@ -1159,13 +1223,14 @@ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } =
1159
1223
  entry = getBaseUri(pathOrUrl, root);
1160
1224
  entryDocument = root;
1161
1225
  return await (0, api_ref_bundler.bundle)(entry, resolver, { hooks: { onError: (message, { path, state }) => {
1226
+ signal?.throwIfAborted();
1162
1227
  const pointer = toKey(state.baseFile) === toKey(entry) ? `#/${path.map((token) => escapePointerToken(String(token))).join("/")}` : void 0;
1163
1228
  const refusedPath = [...refused].find((sourcePath) => message.includes(sourcePath));
1164
1229
  const diagnostic = {
1165
1230
  code: _kubb_kit.Diagnostics.code.refNotFound,
1166
1231
  severity: isExtensionPath(path) ? "warning" : "error",
1167
- message: refusedPath ? `Refused an external \`$ref\` to the local file ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1168
- help: refusedPath ? folders?.length ? "This run only reads local files inside the folders its host allows, such as the project. Move the file there or inline the schema. On your own agent, `--allow-file-refs` lifts the limit." : "This input reads no local file. Inline the schema, or serve the file from a URL." : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1232
+ message: refusedPath ? `Refused an external \`$ref\` to ${urlRegExp.test(refusedPath) ? "a host that is not public" : "the local file"} ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1233
+ help: refusedPath ? refusedHelp(refusedPath) : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1169
1234
  ...pointer && { location: {
1170
1235
  kind: "schema",
1171
1236
  pointer
@@ -1192,7 +1257,7 @@ const inlineInputName = "<inline input>";
1192
1257
  * const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
1193
1258
  * ```
1194
1259
  */
1195
- async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1260
+ async function parseFromConfig(source, sources = [], { fileRefs, signal } = {}) {
1196
1261
  const raw = await (async () => {
1197
1262
  if (source.type === "data") {
1198
1263
  const data = typeof source.data === "string" ? parseYaml(source.data, {
@@ -1203,7 +1268,8 @@ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1203
1268
  if (source.root && isObject) return bundleDocument((0, node_path.join)(source.root, inlineInputName), {
1204
1269
  document: data,
1205
1270
  sources,
1206
- fileRefs
1271
+ fileRefs,
1272
+ signal
1207
1273
  });
1208
1274
  const scan = resolveTargets(data);
1209
1275
  if (isObject) scans.set(data, scan);
@@ -1212,7 +1278,8 @@ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1212
1278
  await assertInputExists(source.path);
1213
1279
  return bundleDocument(source.path, {
1214
1280
  sources,
1215
- fileRefs
1281
+ fileRefs,
1282
+ signal
1216
1283
  });
1217
1284
  })();
1218
1285
  return upgradeDocument(raw, { pathRefs: scans.get(raw)?.pathRefs ?? true });
@@ -2259,7 +2326,47 @@ function getOperations(document, refs) {
2259
2326
  pathItem
2260
2327
  });
2261
2328
  }
2262
- return operations;
2329
+ return withUniqueOperationIds(operations);
2330
+ }
2331
+ function suffixed(id, taken, counts) {
2332
+ const count = (counts.get(id) ?? 1) + 1;
2333
+ counts.set(id, count);
2334
+ const candidate = `${id}_${count}`;
2335
+ return taken.has((0, _kubb_core.pascalCase)(candidate)) ? suffixed(id, taken, counts) : candidate;
2336
+ }
2337
+ function withUniqueOperationIds(operations) {
2338
+ const taken = new Set(operations.flatMap(({ schema }) => typeof schema.operationId === "string" && schema.operationId ? [(0, _kubb_core.pascalCase)(schema.operationId)] : []));
2339
+ const claimed = /* @__PURE__ */ new Set();
2340
+ const counts = /* @__PURE__ */ new Map();
2341
+ return operations.map((operation) => {
2342
+ const operationId = getOperationId(operation);
2343
+ const name = (0, _kubb_core.pascalCase)(operationId);
2344
+ if (!claimed.has(name)) {
2345
+ claimed.add(name);
2346
+ taken.add(name);
2347
+ return operation;
2348
+ }
2349
+ const unique = suffixed(operationId, taken, counts);
2350
+ taken.add((0, _kubb_core.pascalCase)(unique));
2351
+ claimed.add((0, _kubb_core.pascalCase)(unique));
2352
+ _kubb_kit.Diagnostics.report({
2353
+ code: _kubb_kit.Diagnostics.code.duplicateOperationId,
2354
+ severity: "warning",
2355
+ message: `operationId "${operationId}" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to "${unique}".`,
2356
+ help: "Give each operation its own `operationId`.",
2357
+ location: {
2358
+ kind: "operation",
2359
+ pointer: getOperationPointer(operation)
2360
+ }
2361
+ });
2362
+ return {
2363
+ ...operation,
2364
+ schema: {
2365
+ ...operation.schema,
2366
+ operationId: unique
2367
+ }
2368
+ };
2369
+ });
2263
2370
  }
2264
2371
  /** Property names whose schema has a truthy `readOnly` or `writeOnly` flag; `$ref` entries are skipped. */
2265
2372
  function collectPropertyKeysByFlag(schema, flag) {
@@ -3138,9 +3245,13 @@ function inheritScalarType(members, { schema, type }) {
3138
3245
  function convertUnion(context) {
3139
3246
  if (context.schema.enum?.length) {
3140
3247
  const { enum: values, ...union } = context.schema;
3248
+ const nullable = context.nullable || [...union.oneOf ?? [], ...union.anyOf ?? []].some((member) => {
3249
+ const resolved = isReference(member) ? context.refs.resolve(member.$ref, { report: false }) : member;
3250
+ return !!resolved && !isReference(resolved) && isNullable(resolved, context.document);
3251
+ });
3141
3252
  const enumSchema = {
3142
3253
  type: union.type,
3143
- enum: isLegacyDocument(context.document) ? [...values, null] : values
3254
+ enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values
3144
3255
  };
3145
3256
  const members = [convertUnion({
3146
3257
  ...context,
@@ -4150,7 +4261,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4150
4261
  const document = await parseFromConfig({
4151
4262
  type: "path",
4152
4263
  path: input
4153
- });
4264
+ }, [], { fileRefs: options?.fileRefs });
4154
4265
  assertDocument(document);
4155
4266
  await validateDocument(document, options);
4156
4267
  },
@@ -4162,15 +4273,24 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4162
4273
  const cached = inputCache.get(source);
4163
4274
  if (cached) {
4164
4275
  sources = cached.sources;
4276
+ parsedDocument = cached.document;
4165
4277
  return cached.promise;
4166
4278
  }
4167
4279
  const read = [];
4168
4280
  sources = read;
4281
+ const entry = {
4282
+ sources: read,
4283
+ document: null
4284
+ };
4169
4285
  const promise = (async () => {
4170
- const document = await parseFromConfig(source, read, { fileRefs });
4286
+ const document = await parseFromConfig(source, read, {
4287
+ fileRefs,
4288
+ signal
4289
+ });
4171
4290
  signal?.throwIfAborted();
4172
4291
  assertDocument(document);
4173
4292
  if (validate) pendingValidations.push(validateDocumentInWorker(document));
4293
+ entry.document = document;
4174
4294
  parsedDocument = document;
4175
4295
  const refs = createRefs(document);
4176
4296
  const { schemas, renames, pointers } = getSchemas(document, { contentType }, refs);
@@ -4188,10 +4308,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4188
4308
  parseSchema
4189
4309
  }));
4190
4310
  })();
4191
- inputCache.set(source, {
4192
- promise,
4193
- sources: read
4194
- });
4311
+ inputCache.set(source, Object.assign(entry, { promise }));
4195
4312
  return promise.catch((error) => {
4196
4313
  if (signal?.aborted) inputCache.delete(source);
4197
4314
  throw error;