@kubb/adapter-oas 5.28.6 → 5.29.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
@@ -1,24 +1,21 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_rolldown_runtime = require("./rolldown-runtime-BRMrT0dX.cjs");
2
+ require("./rolldown-runtime-BRMrT0dX.cjs");
3
3
  let _kubb_core = require("@kubb/core");
4
4
  let _kubb_kit = require("@kubb/kit");
5
- let node_fs_promises = require("node:fs/promises");
6
5
  let node_path = require("node:path");
7
6
  let node_url = require("node:url");
8
- let node_fs = require("node:fs");
9
7
  let _scalar_openapi_upgrader = require("@scalar/openapi-upgrader");
10
8
  let api_ref_bundler = require("api-ref-bundler");
11
- let node_dns_promises = require("node:dns/promises");
12
- let node_net = require("node:net");
9
+ let node_fs = require("node:fs");
10
+ let node_fs_promises = require("node:fs/promises");
13
11
  let js_yaml = require("js-yaml");
14
- let yaml = require("yaml");
15
12
  // kubb-extension.json
16
13
  var compatibility = {
17
14
  "kubb": ">=5.8.3",
18
15
  "node": ">=22.22"
19
16
  };
20
17
  // package.json
21
- var version = "5.28.6";
18
+ var version = "5.29.1";
22
19
  // src/constants.ts
23
20
  /**
24
21
  * Default parser options applied when no explicit options are provided.
@@ -42,6 +39,29 @@ const DEFAULT_PARSER_OPTIONS = {
42
39
  */
43
40
  const SCHEMA_REF_PREFIX = "#/components/schemas/";
44
41
  /**
42
+ * Keys whose value maps names the user chose to entries: `properties`-like schema maps, schema definitions,
43
+ * and the OpenAPI component and path-level maps. An entry name here is never a keyword, so `x-rate-limit`
44
+ * under `headers` is a real header, not a vendor extension, and a property named `default` holds a schema.
45
+ */
46
+ const namedEntryKeys = /* @__PURE__ */ new Set([
47
+ "properties",
48
+ "patternProperties",
49
+ "dependentSchemas",
50
+ "$defs",
51
+ "definitions",
52
+ "schemas",
53
+ "headers",
54
+ "responses",
55
+ "parameters",
56
+ "requestBodies",
57
+ "examples",
58
+ "links",
59
+ "callbacks",
60
+ "securitySchemes",
61
+ "securityDefinitions",
62
+ "pathItems"
63
+ ]);
64
+ /**
45
65
  * HTTP methods that count as operations on an OpenAPI path item. Other keys
46
66
  * (`parameters`, `summary`, `$ref`, vendor extensions) are skipped when iterating operations.
47
67
  * `query` is the OpenAPI 3.2 field for the HTTP QUERY method (RFC 10008).
@@ -136,6 +156,13 @@ const formatMap = {
136
156
  double: "number"
137
157
  };
138
158
  /**
159
+ * The `formatMap` entry for `format`. Reads own keys only, so `constructor` or `toString` never match.
160
+ */
161
+ function getFormatType(format) {
162
+ const formats = formatMap;
163
+ return Object.hasOwn(formats, format) ? formats[format] : void 0;
164
+ }
165
+ /**
139
166
  * Vendor extension keys that attach human-readable labels to enum values, checked in priority order.
140
167
  */
141
168
  const enumExtensionKeys = ["x-enumNames", "x-enum-varnames"];
@@ -144,8 +171,29 @@ const enumExtensionKeys = ["x-enumNames", "x-enum-varnames"];
144
171
  */
145
172
  const enumDescriptionKeys = ["x-enumDescriptions", "x-enum-descriptions"];
146
173
  // src/emit/discriminator/propagate.ts
174
+ function findUnion(schema) {
175
+ return _kubb_kit.ast.schema.narrow(schema, "union") ?? _kubb_kit.ast.schema.narrow(schema, "intersection")?.members?.map((member) => _kubb_kit.ast.schema.narrow(member, "union")).find((union) => union);
176
+ }
177
+ function pinnedValues({ objNode, propertyName }) {
178
+ const prop = objNode.properties.find((p) => p.name === propertyName);
179
+ return (prop ? _kubb_kit.ast.schema.narrow(prop.schema, "enum") : null)?.enumValues?.filter((v) => v !== null) ?? [];
180
+ }
181
+ function memberDiscriminant({ member, propertyName }) {
182
+ const members = _kubb_kit.ast.schema.narrow(member, "intersection")?.members ?? [];
183
+ const refNode = members.map((m) => _kubb_kit.ast.schema.narrow(m, "ref")).find(Boolean);
184
+ const objNode = members.map((m) => _kubb_kit.ast.schema.narrow(m, "object")).find(Boolean);
185
+ if (!refNode?.name || !objNode) return null;
186
+ const enumValues = pinnedValues({
187
+ objNode,
188
+ propertyName
189
+ });
190
+ return enumValues.length ? {
191
+ name: refNode.targetName ?? refNode.name,
192
+ enumValues
193
+ } : null;
194
+ }
147
195
  /**
148
- * Maps each child schema name to its discriminator patch data by scanning the given
196
+ * Maps each child schema's emitted name to its discriminator patch data by scanning the given
149
197
  * top-level AST schema nodes for union schemas that carry a `discriminatorPropertyName`.
150
198
  *
151
199
  * Called on a small pre-parsed subset of schemas (only the discriminator parents)
@@ -154,33 +202,21 @@ const enumDescriptionKeys = ["x-enumDescriptions", "x-enum-descriptions"];
154
202
  function buildDiscriminatorChildMap(schemas) {
155
203
  const childMap = /* @__PURE__ */ new Map();
156
204
  for (const schema of schemas) {
157
- const unionNode = _kubb_kit.ast.schema.narrow(schema, "union") ?? _kubb_kit.ast.schema.narrow(schema, "intersection")?.members?.map((member) => _kubb_kit.ast.schema.narrow(member, "union")).find((union) => union);
205
+ const unionNode = findUnion(schema);
158
206
  if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue;
159
- const { discriminatorPropertyName, members } = unionNode;
160
- for (const member of members) {
161
- const intersectionNode = _kubb_kit.ast.schema.narrow(member, "intersection");
162
- if (!intersectionNode?.members) continue;
163
- let refNode = null;
164
- let objNode = null;
165
- for (const m of intersectionNode.members) {
166
- refNode ??= _kubb_kit.ast.schema.narrow(m, "ref");
167
- objNode ??= _kubb_kit.ast.schema.narrow(m, "object");
168
- }
169
- if (!refNode?.name || !objNode) continue;
170
- const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName);
171
- const enumNode = prop ? _kubb_kit.ast.schema.narrow(prop.schema, "enum") : null;
172
- if (!enumNode?.enumValues?.length) continue;
173
- const enumValues = enumNode.enumValues.filter((v) => v !== null);
174
- if (!enumValues.length) continue;
175
- const existing = childMap.get(refNode.name);
176
- if (!existing) {
177
- childMap.set(refNode.name, {
178
- propertyName: discriminatorPropertyName,
179
- enumValues: [...new Set(enumValues)]
180
- });
181
- continue;
182
- }
183
- existing.enumValues = [.../* @__PURE__ */ new Set([...existing.enumValues, ...enumValues])];
207
+ const propertyName = unionNode.discriminatorPropertyName;
208
+ for (const member of unionNode.members) {
209
+ const child = memberDiscriminant({
210
+ member,
211
+ propertyName
212
+ });
213
+ if (!child) continue;
214
+ const existing = childMap.get(child.name);
215
+ const enumValues = [.../* @__PURE__ */ new Set([...existing?.enumValues ?? [], ...child.enumValues])];
216
+ childMap.set(child.name, {
217
+ propertyName: existing?.propertyName ?? propertyName,
218
+ enumValues
219
+ });
184
220
  }
185
221
  }
186
222
  return childMap;
@@ -386,27 +422,6 @@ async function read(path) {
386
422
  if (runtime.isBun) return Bun.file(path).text();
387
423
  return new Promise((resolvePromise, reject) => (0, node_fs.readFile)(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
388
424
  }
389
- /**
390
- * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
391
- * to absolute paths first, so relative and `..`-containing inputs compare correctly.
392
- *
393
- * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
394
- * it does not contain the project root, and before loading a path a caller supplied, check that it
395
- * did not escape the directory it is allowed to read from.
396
- *
397
- * @example
398
- * isPathInside('./src/gen', '.') // true — nested inside the root
399
- * isPathInside('.', '.') // true — the same directory counts as inside
400
- * isPathInside('.', './src/gen') // false — the root is not inside its own output
401
- * isPathInside('../other', '.') // false — escapes the root
402
- */
403
- function isPathInside(path, parent) {
404
- const resolvedPath = (0, node_path.resolve)(path);
405
- const resolvedParent = (0, node_path.resolve)(parent);
406
- if (resolvedPath === resolvedParent) return true;
407
- const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
408
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${node_path.sep}`) && !(0, node_path.isAbsolute)(rel);
409
- }
410
425
  // src/oas.ts
411
426
  const legacyDocuments = /* @__PURE__ */ new WeakSet();
412
427
  /**
@@ -571,11 +586,13 @@ var Refs = class {
571
586
  const trimmed = $ref.trim();
572
587
  if (trimmed === "" || !trimmed.startsWith("#")) return {
573
588
  applicable: false,
589
+ found: false,
574
590
  value: null
575
591
  };
576
592
  const pointer = trimmed.substring(1);
577
593
  if (this.#pointerCache.has(pointer)) return {
578
594
  applicable: true,
595
+ found: true,
579
596
  value: this.#pointerCache.get(pointer)
580
597
  };
581
598
  let current;
@@ -584,21 +601,28 @@ var Refs = class {
584
601
  } catch {
585
602
  current = void 0;
586
603
  }
587
- if (current) this.#pointerCache.set(pointer, current);
604
+ if (current === void 0) return {
605
+ applicable: true,
606
+ found: false,
607
+ value: null
608
+ };
609
+ this.#pointerCache.set(pointer, current);
588
610
  return {
589
611
  applicable: true,
590
- value: current ?? null
612
+ found: true,
613
+ value: current
591
614
  };
592
615
  }
593
616
  /**
594
- * Resolves a local `#/...` JSON pointer. Returns `null` for an empty or non-local ref.
617
+ * Resolves a local `#/...` JSON pointer. Returns `null` for an empty, non-local or missing ref.
618
+ * A target that exists is returned as is, even when it is falsy, such as a boolean `false` schema.
595
619
  * `report: true` (default) reports a `refNotFound` diagnostic into the active build (or throws
596
620
  * outside one) when the pointer cannot be resolved. `report: false` resolves to `null` silently,
597
621
  * for a speculative lookup where a missing ref is not an error.
598
622
  */
599
623
  resolve(refPath, options) {
600
- const { applicable, value } = this.#walkPointer(refPath);
601
- if (!applicable || value || options?.report === false) return value;
624
+ const { applicable, found, value } = this.#walkPointer(refPath);
625
+ if (!applicable || found || options?.report === false) return value;
602
626
  const diagnostic = {
603
627
  code: _kubb_kit.Diagnostics.code.refNotFound,
604
628
  severity: "error",
@@ -629,7 +653,7 @@ var Refs = class {
629
653
  if (_kubb_kit.Diagnostics.isError(error) && error.diagnostic.code === _kubb_kit.Diagnostics.code.refNotFound) return null;
630
654
  throw error;
631
655
  }
632
- if (!referenced) return null;
656
+ if (referenced === null) return null;
633
657
  this.#resolvingRefs.add(refPath);
634
658
  try {
635
659
  return parse({ schema: referenced });
@@ -675,28 +699,43 @@ const DATA_KEYS = /* @__PURE__ */ new Set([
675
699
  "enum",
676
700
  "default"
677
701
  ]);
678
- const NAMED_ENTRY_KEYS = /* @__PURE__ */ new Set([
679
- "properties",
680
- "patternProperties",
681
- "$defs",
682
- "definitions",
683
- "schemas",
684
- "dependentSchemas"
685
- ]);
686
702
  const TARGET_KEYS = [
687
703
  "$id",
688
704
  "$anchor",
689
705
  "$dynamicAnchor"
690
706
  ];
691
- function walk(node, pointer, visit, parentKey) {
707
+ function isNamedMap({ node, keyword }) {
708
+ return keyword !== void 0 && !Array.isArray(node) && namedEntryKeys.has(keyword);
709
+ }
710
+ function childKeyword({ node, key, named }) {
711
+ return named || Array.isArray(node) ? void 0 : key;
712
+ }
713
+ function walk(node, pointer, visit, keyword) {
692
714
  if (!node || typeof node !== "object") return;
693
715
  if (!Array.isArray(node)) visit(node, pointer);
694
- const named = parentKey !== void 0 && NAMED_ENTRY_KEYS.has(parentKey);
716
+ const named = isNamedMap({
717
+ node,
718
+ keyword
719
+ });
695
720
  for (const [key, value] of Object.entries(node)) {
696
- if (!named && (DATA_KEYS.has(key) || key.startsWith("x-"))) continue;
697
- walk(value, `${pointer}/${escapePointerToken(key)}`, visit, Array.isArray(node) ? parentKey : key);
721
+ if (!named && isDataOrExtension(key)) continue;
722
+ walk(value, `${pointer}/${escapePointerToken(key)}`, visit, childKeyword({
723
+ node,
724
+ key,
725
+ named
726
+ }));
698
727
  }
699
728
  }
729
+ function isDataOrExtension(key) {
730
+ return DATA_KEYS.has(key) || key.startsWith("x-");
731
+ }
732
+ function scanNode({ scan, node, readsIds }) {
733
+ const record = node;
734
+ const ref = record["$ref"];
735
+ if (typeof ref === "string" && !ref.startsWith("#")) scan.externalRef = true;
736
+ if (typeof ref === "string" && ref.startsWith("#/paths/")) scan.pathRefs = true;
737
+ if (readsIds && !Array.isArray(node) && TARGET_KEYS.some((key) => typeof record[key] === "string")) scan.schemaIds = true;
738
+ }
700
739
  /** Answers, in one walk and without building JSON pointers, what the loading steps after it need to know. */
701
740
  function scanDocument(document) {
702
741
  const scan = {
@@ -704,23 +743,27 @@ function scanDocument(document) {
704
743
  schemaIds: false,
705
744
  pathRefs: false
706
745
  };
707
- const visit = ({ node, readsIds, parentKey }) => {
746
+ const visit = ({ node, readsIds, keyword }) => {
708
747
  if (!node || typeof node !== "object") return;
709
- const isArray = Array.isArray(node);
748
+ scanNode({
749
+ scan,
750
+ node,
751
+ readsIds
752
+ });
753
+ const named = isNamedMap({
754
+ node,
755
+ keyword
756
+ });
710
757
  const record = node;
711
- const ref = record["$ref"];
712
- if (typeof ref === "string" && !ref.startsWith("#")) scan.externalRef = true;
713
- if (typeof ref === "string" && ref.startsWith("#/paths/")) scan.pathRefs = true;
714
- if (readsIds && !isArray && TARGET_KEYS.some((key) => typeof record[key] === "string")) scan.schemaIds = true;
715
- const named = parentKey !== void 0 && NAMED_ENTRY_KEYS.has(parentKey);
716
- for (const key in record) {
717
- const childReadsIds = readsIds && (named || !(DATA_KEYS.has(key) || key.startsWith("x-")));
718
- visit({
719
- node: record[key],
720
- readsIds: childReadsIds,
721
- parentKey: isArray ? parentKey : key
722
- });
723
- }
758
+ for (const key in record) visit({
759
+ node: record[key],
760
+ readsIds: readsIds && (named || !isDataOrExtension(key)),
761
+ keyword: childKeyword({
762
+ node,
763
+ key,
764
+ named
765
+ })
766
+ });
724
767
  };
725
768
  visit({
726
769
  node: document,
@@ -764,7 +807,45 @@ function resolveSchemaIds(document) {
764
807
  }
765
808
  // src/sourceLocator.ts
766
809
  const flowGap = /(?:[\s,]|#[^\n]*)*/y;
767
- const indexes = memo.create({ max: 1 });
810
+ /**
811
+ * How long the indexes of the last sources stay in memory after their last use, in milliseconds.
812
+ */
813
+ const INDEX_IDLE_MS = 6e4;
814
+ var IndexCache = class IndexCache {
815
+ #indexes = IndexCache.#createStore();
816
+ #lastUsed = 0;
817
+ #timer;
818
+ static #createStore() {
819
+ return memo.create({ max: 8 });
820
+ }
821
+ get({ source, compute }) {
822
+ const index = memo(this.#indexes, source, compute);
823
+ this.#keep();
824
+ return index;
825
+ }
826
+ set({ source, index }) {
827
+ this.#indexes.set(source, index);
828
+ this.#keep();
829
+ }
830
+ #keep() {
831
+ this.#lastUsed = Date.now();
832
+ if (!this.#timer) this.#schedule(INDEX_IDLE_MS);
833
+ }
834
+ #schedule(ms) {
835
+ this.#timer = setTimeout(this.#dropWhenIdle, ms);
836
+ this.#timer.unref?.();
837
+ }
838
+ #dropWhenIdle = () => {
839
+ const remaining = this.#lastUsed + INDEX_IDLE_MS - Date.now();
840
+ if (remaining > 0) return this.#schedule(remaining);
841
+ this.#indexes = IndexCache.#createStore();
842
+ this.#timer = void 0;
843
+ };
844
+ };
845
+ function createIndexCache() {
846
+ return new IndexCache();
847
+ }
848
+ const indexes = createIndexCache();
768
849
  function toKeyText(text) {
769
850
  if (!/^[-+.~\d]|^(?:null|true|false)$/i.test(text)) return text;
770
851
  try {
@@ -949,25 +1030,34 @@ var SourceLocator = class {
949
1030
  function createSourceLocator(options) {
950
1031
  return new SourceLocator(options);
951
1032
  }
952
- function parse$1(source) {
1033
+ function parse(source) {
953
1034
  try {
954
1035
  return indexEvents((0, js_yaml.parseEvents)(source, { maxDepth: Number.POSITIVE_INFINITY }));
955
1036
  } catch {
956
1037
  return;
957
1038
  }
958
1039
  }
959
- require_rolldown_runtime.__name(parse$1, "parse");
1040
+ /**
1041
+ * Keeps the event index of a source the adapter already parsed, so `locate` does not parse it again.
1042
+ */
960
1043
  function rememberEvents({ source, events }) {
961
- indexes.set(source, indexEvents(events));
1044
+ indexes.set({
1045
+ source,
1046
+ index: indexEvents(events)
1047
+ });
962
1048
  }
963
1049
  const withoutAllOf = (pointer) => pointer.replace(/\/allOf\/\d+(?=\/|$)/g, "");
964
1050
  /**
965
1051
  * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source. A pointer through an `allOf`
966
- * the spec does not have falls back to the same pointer without its `allOf` steps.
1052
+ * the spec does not have falls back to the same pointer without its `allOf` steps. The indexes of the last few
1053
+ * sources are reused until they go unused for `INDEX_IDLE_MS`.
967
1054
  */
968
1055
  const locate = (source, location) => {
969
1056
  if (!("pointer" in location)) return void 0;
970
- const index = memo(indexes, source, () => parse$1(source));
1057
+ const index = indexes.get({
1058
+ source,
1059
+ compute: () => parse(source)
1060
+ });
971
1061
  if (!index) return void 0;
972
1062
  const locator = createSourceLocator({
973
1063
  index,
@@ -982,23 +1072,10 @@ const urlRegExp = /^https?:\/+/i;
982
1072
  /** How long one request for a document or a `$ref` may take before Kubb gives up on it. */
983
1073
  const FETCH_TIMEOUT_MS = 3e4;
984
1074
  /**
985
- * Whether `url` names a host that is loopback, private, link-local, or another address that is not
986
- * public. A host that does not resolve, or not within the request timeout, counts as not public,
987
- * because the check cannot prove it public. `signal` cancels the lookup.
988
- *
989
- * shortcut: the name is resolved again when `fetch` connects, so a host that changes its answer in
990
- * between can still reach a private address. Upgrade to a pinned lookup, like `@kubb/studio`'s
991
- * `publicFetch`, if a sandbox needs that guarantee.
1075
+ * Whether `error` is a harness refusal. It checks the code, since a host may load another copy of `@kubb/core`.
992
1076
  */
993
- async function isPrivateHost(url, { signal } = {}) {
994
- const host = url.hostname.replace(/^\[|\]$/g, "");
995
- if ((0, node_net.isIP)(host)) return !(0, _kubb_core.isPublicAddress)(host);
996
- const deadline = withTimeout(signal);
997
- deadline.throwIfAborted();
998
- const stopped = new Promise((_, reject) => deadline.addEventListener("abort", () => reject(deadline.reason), { once: true }));
999
- const addresses = await Promise.race([(0, node_dns_promises.lookup)(host, { all: true }), stopped]).catch(() => []);
1000
- signal?.throwIfAborted();
1001
- return addresses.length === 0 || addresses.some(({ address }) => !(0, _kubb_core.isPublicAddress)(address));
1077
+ function isAccessRefused(error) {
1078
+ return error?.diagnostic?.code === _kubb_kit.Diagnostics.code.accessRefused;
1002
1079
  }
1003
1080
  function withTimeout(signal) {
1004
1081
  const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);
@@ -1020,19 +1097,17 @@ function helpForStatus(status) {
1020
1097
  if (status >= 500) return "The server failed while serving the document. Check that it is healthy, then run Kubb again.";
1021
1098
  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.";
1022
1099
  }
1023
- async function fetchSource(url, { signal, publicOnly }) {
1100
+ async function fetchSource(url, { signal, fetch = globalThis.fetch }) {
1024
1101
  const deadline = withTimeout(signal);
1025
1102
  try {
1026
- const response = await fetch(url, {
1027
- signal: deadline,
1028
- redirect: publicOnly ? "error" : "follow"
1029
- });
1103
+ const response = await fetch(url, { signal: deadline });
1030
1104
  return {
1031
1105
  response,
1032
1106
  body: response.ok ? await response.text() : ""
1033
1107
  };
1034
1108
  } catch (error) {
1035
1109
  if (signal?.aborted) throw signal.reason;
1110
+ if (isAccessRefused(error)) throw error;
1036
1111
  const reason = deadline.aborted ? `no answer within ${FETCH_TIMEOUT_MS / 1e3} seconds` : describeFetchFailure(error);
1037
1112
  throw new _kubb_kit.Diagnostics.Error({
1038
1113
  code: _kubb_kit.Diagnostics.code.inputUnreachable,
@@ -1060,7 +1135,7 @@ async function readSource(sourcePath, options) {
1060
1135
  }
1061
1136
  return body;
1062
1137
  }
1063
- return read(sourcePath);
1138
+ return (options.read ?? read)(sourcePath);
1064
1139
  }
1065
1140
  /**
1066
1141
  * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an
@@ -1086,9 +1161,8 @@ async function resolveSource(sourcePath, { remember, ...options } = {}) {
1086
1161
  * value, as every JSON parser does. YAML flow syntax also starts with `{`, so a parse failure falls
1087
1162
  * through to YAML. Pass `json: false` for a source known to be YAML.
1088
1163
  *
1089
- * `js-yaml` parses about ten times faster than `yaml`, and rejects duplicate keys instead of
1090
- * keeping the last one. Its core schema keeps timestamps as strings and `<<` as a plain key, as
1091
- * `yaml` does for YAML 1.2.
1164
+ * `js-yaml` rejects duplicate keys instead of keeping the last one. Its core schema keeps
1165
+ * timestamps as strings and `<<` as a plain key, as YAML 1.2 does.
1092
1166
  */
1093
1167
  function parseYaml(data, { origin, help, json = true, remember = false }) {
1094
1168
  if (json && /^\s*[[{]/.test(data)) try {
@@ -1100,16 +1174,11 @@ function parseYaml(data, { origin, help, json = true, remember = false }) {
1100
1174
  source: data,
1101
1175
  schema: js_yaml.CORE_SCHEMA
1102
1176
  });
1103
- if (documents.length === 1 && documents[0] !== void 0) {
1104
- if (remember) rememberEvents({
1105
- source: data,
1106
- events
1107
- });
1108
- return documents[0];
1109
- }
1110
- } catch {}
1111
- try {
1112
- return (0, yaml.parse)(data);
1177
+ if (remember && documents.length === 1) rememberEvents({
1178
+ source: data,
1179
+ events
1180
+ });
1181
+ return documents[0];
1113
1182
  } catch (error) {
1114
1183
  throw new _kubb_kit.Diagnostics.Error({
1115
1184
  code: _kubb_kit.Diagnostics.code.invalidDocument,
@@ -1164,29 +1233,18 @@ function inlinePathRefs(node, resolve, visiting = []) {
1164
1233
  for (const [key, value] of Object.entries(node)) node[key] = inlinePathRefs(value, resolve, visiting);
1165
1234
  return node;
1166
1235
  }
1167
- const namedEntryKeys = /* @__PURE__ */ new Set([
1168
- "properties",
1169
- "patternProperties",
1170
- "headers",
1171
- "schemas",
1172
- "responses",
1173
- "parameters",
1174
- "requestBodies",
1175
- "examples",
1176
- "links",
1177
- "callbacks",
1178
- "securitySchemes",
1179
- "securityDefinitions",
1180
- "pathItems",
1181
- "definitions",
1182
- "$defs"
1183
- ]);
1184
1236
  /**
1185
1237
  * True when `path` runs through an `x-` vendor extension. Kubb never reads an extension, so a `$ref`
1186
1238
  * Kubb cannot read inside one cannot change the output.
1187
1239
  */
1188
1240
  function isExtensionPath(path) {
1189
- return path.some((token, index) => String(token).startsWith("x-") && !namedEntryKeys.has(String(path[index - 1])));
1241
+ let inNamedMap = false;
1242
+ for (const token of path) {
1243
+ const key = String(token);
1244
+ if (key.startsWith("x-") && !inNamedMap) return true;
1245
+ inNamedMap = !inNamedMap && namedEntryKeys.has(key);
1246
+ }
1247
+ return false;
1190
1248
  }
1191
1249
  /**
1192
1250
  * Returns the base for relative `$ref`s: the 3.2 `$self` resolved against `pathOrUrl`, else `pathOrUrl`.
@@ -1204,16 +1262,6 @@ function getBaseUri(pathOrUrl, root) {
1204
1262
  }
1205
1263
  }
1206
1264
  /**
1207
- * Whether `filePath` is inside one of `folders`. Links are followed first, so a link inside a
1208
- * folder cannot point outside it.
1209
- */
1210
- async function isInsideFolders(filePath, folders) {
1211
- const real = (item) => (0, node_fs_promises.realpath)((0, node_path.resolve)(item)).catch(() => (0, node_path.resolve)(item));
1212
- const target = await real(filePath);
1213
- const realFolders = await Promise.all(folders.map(real));
1214
- return [...folders, ...realFolders].some((folder) => isPathInside(target, folder));
1215
- }
1216
- /**
1217
1265
  * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.
1218
1266
  *
1219
1267
  * External file schemas are hoisted into named `components.schemas` entries, so a property
@@ -1230,10 +1278,9 @@ async function isInsideFolders(filePath, folders) {
1230
1278
  * against the OpenAPI 3.2 `$self` when the document sets one. Every other file or URL read,
1231
1279
  * including one that fails, lands in `sources`. A `$ref` that cannot be read reports
1232
1280
  * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.
1233
- * So does any local file from a URL input, and a local file outside every `fileRefs` folder.
1234
- * With `fileRefs` set, a `$ref` URL on a host that is not public is refused too, and a redirect
1235
- * fails, so a document sent to a sandboxed host cannot make it request internal addresses.
1236
- * `signal` cancels every request.
1281
+ * So does any local file from a URL input. With `harness`, every `$ref` file and every URL is read
1282
+ * through it, and a target its rules refuse reports `KUBB_ACCESS_REFUSED`. Without one, a `$ref` reads
1283
+ * any file and host. `signal` cancels every request.
1237
1284
  *
1238
1285
  * @example Local file
1239
1286
  * `const document = await bundleDocument('./openapi.yaml')`
@@ -1241,16 +1288,45 @@ async function isInsideFolders(filePath, folders) {
1241
1288
  * @example Remote URL
1242
1289
  * `const document = await bundleDocument('https://example.com/openapi.yaml')`
1243
1290
  */
1244
- async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, signal } = {}) {
1291
+ async function bundleDocument(pathOrUrl, { document, sources = [], harness, signal } = {}) {
1245
1292
  const cache = memo.create();
1246
1293
  const toKey = (sourcePath) => urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath;
1247
- const folders = urlRegExp.test(pathOrUrl) ? [] : fileRefs;
1248
- const publicOnly = fileRefs !== void 0;
1249
1294
  const refused = /* @__PURE__ */ new Set();
1250
- const refusedHelp = (refusedPath) => {
1251
- 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.";
1252
- 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.";
1253
- return "This input reads no local file. Inline the schema, or serve the file from a URL.";
1295
+ const harnessRefusals = /* @__PURE__ */ new Map();
1296
+ const read = ({ sourcePath, isRef }) => {
1297
+ if (!harness) return resolveSource(sourcePath, {
1298
+ remember: !isRef,
1299
+ signal
1300
+ });
1301
+ return resolveSource(sourcePath, {
1302
+ remember: !isRef,
1303
+ signal,
1304
+ fetch: (url, init) => harness.fetch(url, init),
1305
+ read: isRef ? (file) => harness.read(file) : void 0
1306
+ }).catch((error) => {
1307
+ if (isRef && isAccessRefused(error)) harnessRefusals.set(toKey(sourcePath), error.diagnostic);
1308
+ throw error;
1309
+ });
1310
+ };
1311
+ const refTarget = ({ value, baseFile }) => {
1312
+ const ref = value?.$ref;
1313
+ return typeof ref === "string" ? toKey((0, api_ref_bundler.parseRef)(ref, baseFile).filePath) : void 0;
1314
+ };
1315
+ const refDiagnostic = ({ message, target }) => {
1316
+ const harnessRefusal = target === void 0 ? void 0 : harnessRefusals.get(target);
1317
+ if (harnessRefusal) return harnessRefusal;
1318
+ if (target === void 0 || !refused.has(target)) return {
1319
+ code: _kubb_kit.Diagnostics.code.refNotFound,
1320
+ severity: "error",
1321
+ message: `Could not bundle an external \`$ref\`. ${message}.`,
1322
+ help: "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`."
1323
+ };
1324
+ return {
1325
+ code: _kubb_kit.Diagnostics.code.accessRefused,
1326
+ severity: "error",
1327
+ message: `Refused an external \`$ref\` to the local file ${target}.`,
1328
+ help: "This input reads no local file. Inline the schema, or serve the file from a URL."
1329
+ };
1254
1330
  };
1255
1331
  let entry = pathOrUrl;
1256
1332
  let entryDocument = document;
@@ -1258,19 +1334,15 @@ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, sig
1258
1334
  if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return entryDocument;
1259
1335
  const key = toKey(sourcePath);
1260
1336
  const isRef = key !== toKey(pathOrUrl);
1261
- const isUrl = urlRegExp.test(sourcePath);
1262
- const refusedUrl = isRef && isUrl && publicOnly && await isPrivateHost(new URL(sourcePath), { signal });
1263
- const refusedFile = isRef && !isUrl && folders !== void 0 && !await isInsideFolders(sourcePath, folders);
1264
- if (refusedUrl || refusedFile) {
1265
- refused.add(sourcePath);
1337
+ if (isRef && !urlRegExp.test(sourcePath) && urlRegExp.test(pathOrUrl)) {
1338
+ refused.add(key);
1266
1339
  throw new Error(`Refused ${sourcePath}`);
1267
1340
  }
1268
1341
  return memo(cache, key, () => {
1269
1342
  sources.push(key);
1270
- return resolveSource(sourcePath, {
1271
- remember: !isRef,
1272
- signal,
1273
- publicOnly: publicOnly && isRef
1343
+ return read({
1344
+ sourcePath,
1345
+ isRef
1274
1346
  });
1275
1347
  });
1276
1348
  };
@@ -1282,15 +1354,18 @@ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, sig
1282
1354
  }
1283
1355
  entry = getBaseUri(pathOrUrl, root);
1284
1356
  entryDocument = root;
1285
- return await (0, api_ref_bundler.bundle)(entry, resolver, { hooks: { onError: (message, { path, state }) => {
1357
+ return await (0, api_ref_bundler.bundle)(entry, resolver, { hooks: { onError: (message, { path, state, value }) => {
1286
1358
  signal?.throwIfAborted();
1287
1359
  const pointer = toKey(state.baseFile) === toKey(entry) ? `#/${path.map((token) => escapePointerToken(String(token))).join("/")}` : void 0;
1288
- const refusedPath = [...refused].find((sourcePath) => message.includes(sourcePath));
1289
1360
  const diagnostic = {
1290
- code: _kubb_kit.Diagnostics.code.refNotFound,
1361
+ ...refDiagnostic({
1362
+ message,
1363
+ target: refTarget({
1364
+ value,
1365
+ baseFile: state.baseFile
1366
+ })
1367
+ }),
1291
1368
  severity: isExtensionPath(path) ? "warning" : "error",
1292
- 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}.`,
1293
- help: refusedPath ? refusedHelp(refusedPath) : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1294
1369
  ...pointer && { location: {
1295
1370
  kind: "schema",
1296
1371
  pointer
@@ -1299,6 +1374,13 @@ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs, sig
1299
1374
  if (!_kubb_kit.Diagnostics.report(diagnostic) && diagnostic.severity === "error") throw new _kubb_kit.Diagnostics.Error(diagnostic);
1300
1375
  } } });
1301
1376
  }
1377
+ function readInlineData(data) {
1378
+ if (typeof data !== "string") return structuredClone(data);
1379
+ return parseYaml(data, {
1380
+ origin: "the inline `input` string",
1381
+ help: "Fix the syntax at the reported line. Kubb reads `input` as an inline spec, not a file path, because it starts with `{`, `[`, `openapi:`, or `swagger:`, or spans several lines."
1382
+ });
1383
+ }
1302
1384
  const inlineInputName = "<inline input>";
1303
1385
  /**
1304
1386
  * Creates a `Document` from an `AdapterSource`.
@@ -1317,18 +1399,15 @@ const inlineInputName = "<inline input>";
1317
1399
  * const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
1318
1400
  * ```
1319
1401
  */
1320
- async function parseFromConfig(source, sources = [], { fileRefs, signal } = {}) {
1402
+ async function parseFromConfig(source, sources = [], { harness, signal } = {}) {
1321
1403
  const raw = await (async () => {
1322
1404
  if (source.type === "data") {
1323
- const data = typeof source.data === "string" ? parseYaml(source.data, {
1324
- origin: "the inline `input` string",
1325
- help: "Fix the syntax at the reported line. Kubb reads `input` as an inline spec, not a file path, because it starts with `{`, `[`, `openapi:`, or `swagger:`, or spans several lines."
1326
- }) : structuredClone(source.data);
1405
+ const data = readInlineData(source.data);
1327
1406
  const isObject = Boolean(data) && typeof data === "object";
1328
1407
  if (source.root && isObject) return bundleDocument((0, node_path.join)(source.root, inlineInputName), {
1329
1408
  document: data,
1330
1409
  sources,
1331
- fileRefs,
1410
+ harness,
1332
1411
  signal
1333
1412
  });
1334
1413
  const scan = resolveTargets(data);
@@ -1338,7 +1417,7 @@ async function parseFromConfig(source, sources = [], { fileRefs, signal } = {})
1338
1417
  await assertInputExists(source.path);
1339
1418
  return bundleDocument(source.path, {
1340
1419
  sources,
1341
- fileRefs,
1420
+ harness,
1342
1421
  signal
1343
1422
  });
1344
1423
  })();
@@ -1410,28 +1489,17 @@ function reportInvalidSpec(message) {
1410
1489
  * ```
1411
1490
  */
1412
1491
  async function validateDocument(document, { throwOnError = false } = {}) {
1413
- if (isOpenApi32(document)) {
1414
- const diagnostic = {
1415
- code: _kubb_kit.Diagnostics.code.invalidSpec,
1416
- severity: "warning",
1417
- message: "The document was not validated: `@readme/openapi-parser` does not support OpenAPI 3.2 yet.",
1418
- help: "Set `validate: false` on the adapter to skip this check until the validator supports OpenAPI 3.2."
1419
- };
1420
- if (throwOnError) throw new _kubb_kit.Diagnostics.Error(diagnostic);
1421
- _kubb_kit.Diagnostics.report(diagnostic);
1422
- return;
1423
- }
1424
- if (!throwOnError) {
1425
- const { validateSpec } = await Promise.resolve().then(() => require("./validateSpec-Bxf2WZ1Y.cjs"));
1426
- return reportResult(await validateSpec(structuredClone(document)));
1427
- }
1428
- const { compileErrors, validate } = await import("@readme/openapi-parser");
1429
- const result = await validate(structuredClone(document), { validate: { errors: { colorize: true } } });
1430
- if (result.valid) return;
1492
+ const { validateSpec } = await Promise.resolve().then(() => require("./validateSpec-DXIH7vw7.cjs"));
1493
+ const result = await validateSpec(structuredClone(document));
1494
+ if (throwOnError) return throwResult(result);
1495
+ reportResult(result);
1496
+ }
1497
+ function throwResult(result) {
1498
+ if ("valid" in result && result.valid) return;
1431
1499
  throw new _kubb_kit.Diagnostics.Error({
1432
1500
  code: _kubb_kit.Diagnostics.code.invalidSpec,
1433
1501
  severity: "error",
1434
- message: compileErrors(result),
1502
+ message: "thrown" in result ? result.thrown : result.message,
1435
1503
  help: "Fix each problem listed in the spec, then validate again."
1436
1504
  });
1437
1505
  }
@@ -1451,7 +1519,6 @@ const VALIDATION_WORKER_LIMITS = { maxYoungGenerationSizeMb: 4 };
1451
1519
  * validating in place where worker threads are missing, as in edge runtimes.
1452
1520
  */
1453
1521
  async function validateDocumentInWorker(document) {
1454
- if (isOpenApi32(document)) return validateDocument(document);
1455
1522
  let message;
1456
1523
  try {
1457
1524
  const { Worker } = await import("node:worker_threads");
@@ -1594,6 +1661,25 @@ function sortSchemas(schemas, renames) {
1594
1661
  for (const name of sorted) result[name] = schemas[name];
1595
1662
  return result;
1596
1663
  }
1664
+ var SchemaNames = class {
1665
+ #taken;
1666
+ constructor(reserved) {
1667
+ this.#taken = new Set(reserved);
1668
+ }
1669
+ claim({ base, from }) {
1670
+ let n = from ?? 1;
1671
+ let name = from ? `${base}${n}` : base;
1672
+ while (this.#taken.has((0, _kubb_core.pascalCase)(name))) {
1673
+ n = Math.max(n + 1, 2);
1674
+ name = `${base}${n}`;
1675
+ }
1676
+ this.#taken.add((0, _kubb_core.pascalCase)(name));
1677
+ return name;
1678
+ }
1679
+ };
1680
+ function createSchemaNames(reserved) {
1681
+ return new SchemaNames(reserved);
1682
+ }
1597
1683
  const semanticSuffixes = {
1598
1684
  schemas: "Schema",
1599
1685
  responses: "Response",
@@ -1671,15 +1757,21 @@ function getSchemas(document, { contentType }, refs) {
1671
1757
  const schemas = {};
1672
1758
  const renames = /* @__PURE__ */ new Map();
1673
1759
  const pointers = /* @__PURE__ */ new Map();
1760
+ const names = createSchemaNames(normalizedNames.keys());
1674
1761
  for (const [, items] of normalizedNames) {
1675
1762
  const isSingle = items.length === 1;
1676
1763
  const hasMultipleSources = !isSingle && new Set(items.map((item) => item.source)).size > 1;
1677
1764
  items.forEach((item, index) => {
1678
- const suffix = isSingle ? "" : hasMultipleSources ? semanticSuffixes[item.source] : index ? String(index + 1) : "";
1679
- const uniqueName = item.originalName + suffix;
1765
+ const uniqueName = (() => {
1766
+ if (isSingle || !hasMultipleSources && !index) return item.originalName;
1767
+ return hasMultipleSources ? names.claim({ base: item.originalName + semanticSuffixes[item.source] }) : names.claim({
1768
+ base: item.originalName,
1769
+ from: index + 1
1770
+ });
1771
+ })();
1680
1772
  schemas[uniqueName] = item.schema;
1681
1773
  pointers.set(uniqueName, item.pointer ?? item.ref);
1682
- if (suffix || item.nested) renames.set(item.ref, uniqueName);
1774
+ if (uniqueName !== item.originalName || item.nested) renames.set(item.ref, uniqueName);
1683
1775
  });
1684
1776
  }
1685
1777
  return {
@@ -1855,1606 +1947,1674 @@ function toInputTags(tags) {
1855
1947
  };
1856
1948
  });
1857
1949
  }
1858
- // src/model/mediaType.ts
1859
- const streamMediaTypes = /* @__PURE__ */ new Set([
1860
- "application/jsonl",
1861
- "application/x-ndjson",
1862
- "application/json-seq",
1863
- "text/event-stream"
1864
- ]);
1950
+ // src/emit/schemaShape.ts
1865
1951
  /**
1866
- * Returns `true` for a media type read as a stream of items: SSE, JSON Lines, a `+json-seq` sequence, or any media type that declares `itemSchema`.
1952
+ * Whether `format` maps to a dedicated type; `false` is what `KUBB_UNSUPPORTED_FORMAT` flags.
1867
1953
  */
1868
- function isStream(contentType, mediaType) {
1869
- const baseType = _kubb_kit.ast.mediaType.getBase(contentType);
1870
- return streamMediaTypes.has(baseType) || baseType.startsWith("application/") && baseType.endsWith("+json-seq") || mediaType?.itemSchema !== void 0;
1954
+ function isHandledFormat(format) {
1955
+ return getFormatType(format) !== void 0 || specialCasedFormats.has(format);
1871
1956
  }
1872
1957
  /**
1873
- * Whether the media type is `text/event-stream`, with or without parameters.
1958
+ * Resolves the `dateType` option down to the value for one format. The scalar form of
1959
+ * `dateType` applies to every format; the object form picks `dateTime`/`date`/`time`
1960
+ * individually and defaults an omitted key to `'string'`.
1874
1961
  */
1875
- function isEventStream(contentType) {
1876
- return _kubb_kit.ast.mediaType.getBase(contentType) === "text/event-stream";
1962
+ function resolveDateTypeValue(dateType, format) {
1963
+ if (typeof dateType !== "object" || dateType === null) return dateType;
1964
+ return dateType[format === "date-time" ? "dateTime" : format] ?? "string";
1877
1965
  }
1878
1966
  /**
1879
- * Replaces a `data` string that holds JSON with its `contentSchema`, so the event reads as parsed.
1967
+ * Reads schema examples as an array. OAS 3.1 uses an `examples` array, but specs (including ones
1968
+ * labeled 3.1) still use the singular OAS 3.0 `example`, which the upgrader only converts on the
1969
+ * 3.0 -> 3.1 hop. Normalize both into one array so the AST node exposes only `examples`.
1880
1970
  */
1881
- function withParsedData(schema, refs) {
1882
- const data = schema.properties?.data;
1883
- const resolved = data && isReference(data) ? refs.resolve(data.$ref, { report: false }) : data;
1884
- if (!resolved?.contentSchema || !resolved.contentMediaType || !isJsonMimeType(resolved.contentMediaType)) return schema;
1885
- return {
1886
- ...schema,
1887
- properties: {
1888
- ...schema.properties,
1889
- data: resolved.contentSchema
1890
- }
1891
- };
1971
+ function extractExamples(schema) {
1972
+ if (Array.isArray(schema.examples)) return schema.examples;
1973
+ return schema.example !== void 0 ? [schema.example] : void 0;
1892
1974
  }
1893
1975
  /**
1894
- * Inlines a `$ref` event whose JSON `data` string needs its `contentSchema`, so the shared component keeps `data` as a string elsewhere.
1976
+ * Whether the schema and its inline `allOf` members hold more than one distinct `pattern`. A value must match every one.
1895
1977
  */
1896
- function withParsedRef(schema, refs) {
1897
- const resolved = refs.resolve(schema.$ref, { report: false });
1898
- if (!resolved || isReference(resolved)) return schema;
1899
- const parsed = withParsedData(resolved, refs);
1900
- return parsed === resolved ? schema : parsed;
1978
+ function hasSeveralPatterns(schema) {
1979
+ const patterns = [schema, ...schema.allOf ?? []].map((item) => isReference(item) ? void 0 : item.pattern).filter((pattern) => pattern !== void 0);
1980
+ return new Set(patterns).size > 1;
1981
+ }
1982
+ function hasStructuralKeywords(fragment) {
1983
+ return Object.keys(fragment).some((key) => structuralKeys.has(key));
1901
1984
  }
1902
1985
  /**
1903
- * Keywords next to `$ref` that only annotate it, so a reference that carries nothing else stays a reference.
1986
+ * Flattens a keyword-only `allOf` into its parent schema.
1987
+ *
1988
+ * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords
1989
+ * (see `structuralKeys`). Outer schema values take precedence over fragment values. Returns the
1990
+ * original schema unchanged when flattening is unsafe.
1991
+ *
1992
+ * @example
1993
+ * ```ts
1994
+ * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })
1995
+ * // { type: 'object', properties: {}, description: 'A pet' }
1996
+ * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })
1997
+ * // returned unchanged, contains a $ref
1998
+ * ```
1904
1999
  */
1905
- const REF_ANNOTATIONS = /* @__PURE__ */ new Set([
1906
- "$ref",
1907
- "summary",
1908
- "description",
1909
- "$comment"
1910
- ]);
2000
+ function flattenSchema(schema) {
2001
+ if (!schema.allOf?.length) return schema;
2002
+ const allOfFragments = schema.allOf;
2003
+ if (allOfFragments.some((item) => isReference(item))) return schema;
2004
+ if (allOfFragments.some(hasStructuralKeywords)) return schema;
2005
+ if (hasSeveralPatterns(schema)) return schema;
2006
+ const { allOf: _allOf, ...rest } = schema;
2007
+ const merged = rest;
2008
+ for (const fragment of allOfFragments) for (const [key, value] of Object.entries(fragment)) merged[key] ??= value;
2009
+ return merged;
2010
+ }
2011
+ // src/emit/createNode.ts
1911
2012
  /**
1912
- * Applies `extra` on top of `base` the way JSON Schema does: `properties` and `required` add up, other keywords of `extra` win.
2013
+ * Builds a schema node from a converter's base context plus its type-specific fields. Every
2014
+ * converter needs the same metadata fields (`title`, `description`, `examples`, ...) alongside
2015
+ * whatever makes its node distinct; this folds both into one call.
1913
2016
  */
1914
- function mergeSchemas(base, extra) {
1915
- const required = [.../* @__PURE__ */ new Set([...Array.isArray(base.required) ? base.required : [], ...Array.isArray(extra.required) ? extra.required : []])];
1916
- return {
1917
- type: "object",
1918
- ...base,
1919
- ...extra,
1920
- properties: {
1921
- ...base.properties,
1922
- ...extra.properties
1923
- },
1924
- ...required.length ? { required } : {}
1925
- };
2017
+ function createNode({ schema, name, nullable, defaultValue }, extras) {
2018
+ return _kubb_kit.ast.factory.createSchema({
2019
+ name,
2020
+ nullable,
2021
+ title: schema.title,
2022
+ description: schema.description,
2023
+ deprecated: schema.deprecated,
2024
+ readOnly: schema.readOnly,
2025
+ writeOnly: schema.writeOnly,
2026
+ default: defaultValue,
2027
+ examples: extractExamples(schema),
2028
+ format: schema.format,
2029
+ externalDocs: getExternalDocs(schema.externalDocs),
2030
+ extensions: pickExtensions(schema),
2031
+ ...extras
2032
+ });
1926
2033
  }
2034
+ // src/emit/discriminator/preserve.ts
1927
2035
  /**
1928
- * Normalizes the OpenAPI 3.2 `text/event-stream` item schema into one schema per event.
1929
- * - Keywords next to a `$ref` apply to the referenced schema.
1930
- * - Shared `properties` merge into each inline `oneOf`/`anyOf` member.
1931
- * - A JSON `data` string becomes its `contentSchema`.
2036
+ * Turns string mapping keys into the discriminator property's type when they parse cleanly.
1932
2037
  */
1933
- function toEventSchema(schema, refs) {
1934
- if (isReference(schema)) {
1935
- const siblings = Object.fromEntries(Object.entries(schema).filter(([key]) => !REF_ANNOTATIONS.has(key)));
1936
- const resolved = Object.keys(siblings).length ? refs.resolve(schema.$ref, { report: false }) : null;
1937
- return resolved ? toEventSchema(mergeSchemas(resolved, siblings), refs) : withParsedRef(schema, refs);
1938
- }
1939
- const key = schema.oneOf?.length ? "oneOf" : schema.anyOf?.length ? "anyOf" : void 0;
1940
- if (!key) return withParsedData(schema, refs);
1941
- const members = schema[key];
1942
- const { properties, required, ...rest } = schema;
1943
- const merge = !!properties && !members.some(isReference);
1944
- const shared = {
1945
- properties,
1946
- required
1947
- };
1948
- return {
1949
- ...merge ? rest : schema,
1950
- [key]: members.map((member) => isReference(member) ? withParsedRef(member, refs) : withParsedData(merge ? mergeSchemas(shared, member) : member, refs))
1951
- };
2038
+ function typedKeys({ keys, propertyType }) {
2039
+ return keys.map((key) => {
2040
+ if (propertyType === "integer" || propertyType === "number") {
2041
+ const value = Number(key);
2042
+ return key.trim() !== "" && Number.isFinite(value) ? value : key;
2043
+ }
2044
+ if (propertyType === "boolean") {
2045
+ const lower = key.toLowerCase();
2046
+ return lower === "true" ? true : lower === "false" ? false : key;
2047
+ }
2048
+ return key;
2049
+ });
1952
2050
  }
1953
- const SSE_FIELDS = /* @__PURE__ */ new Set([
1954
- "event",
1955
- "id",
1956
- "retry",
1957
- "data"
1958
- ]);
1959
2051
  /**
1960
- * Property names of the schema and its `allOf` members, following `$ref`s, as one combined object declares them.
2052
+ * Reads the declared `type` of `propertyName` on a schema, following `$ref`s and `allOf` members.
2053
+ * A nullable array such as `['integer', 'null']` reads as its one non-null type.
1961
2054
  */
1962
- function collectFields(schema, refs, seen) {
1963
- if (isReference(schema)) {
1964
- if (seen.has(schema.$ref)) return [];
2055
+ function propertyTypeOf({ schema, propertyName, refs, seen = /* @__PURE__ */ new Set() }) {
2056
+ const deref = (value) => value && isReference(value) ? refs.resolve(value.$ref, { report: false }) : value;
2057
+ if (schema && isReference(schema)) {
2058
+ if (seen.has(schema.$ref)) return void 0;
1965
2059
  seen.add(schema.$ref);
1966
- const resolved = refs.resolve(schema.$ref, { report: false });
1967
- return resolved ? collectFields(resolved, refs, seen) : [];
1968
2060
  }
1969
- const members = schema.allOf ?? [];
1970
- return [...Object.keys(schema.properties ?? {}), ...members.flatMap((member) => collectFields(member, refs, seen))];
2061
+ const resolved = deref(schema);
2062
+ const type = deref(resolved?.properties?.[propertyName])?.type ?? resolved?.allOf?.map((member) => propertyTypeOf({
2063
+ schema: member,
2064
+ propertyName,
2065
+ refs,
2066
+ seen
2067
+ })).find(Boolean);
2068
+ const nonNull = Array.isArray(type) ? type.filter((t) => t !== "null") : [];
2069
+ return nonNull.length === 1 ? nonNull[0] : type;
1971
2070
  }
1972
2071
  /**
1973
- * Whether the schema, following `$ref`s, or a `oneOf`/`anyOf` member of it is a whole Server-Sent Event: its combined
1974
- * `allOf` fields declare `data`, or `event` with no field an event cannot carry. An `event` next to fields such as
1975
- * `planet` is the payload's own property, sent as JSON in the `data:` line.
2072
+ * Creates a single-property object schema used as a discriminator literal.
2073
+ *
2074
+ * @example
2075
+ * ```ts
2076
+ * createDiscriminantNode({ propertyName: 'type', values: ['dog'] })
2077
+ * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
2078
+ * ```
1976
2079
  */
1977
- function declaresEventFields(schema, refs, seen) {
1978
- if (isReference(schema)) {
1979
- if (seen.has(schema.$ref)) return false;
1980
- seen.add(schema.$ref);
1981
- const resolved = refs.resolve(schema.$ref, { report: false });
1982
- return !!resolved && declaresEventFields(resolved, refs, seen);
1983
- }
1984
- const fields = collectFields(schema, refs, new Set(seen));
1985
- if (fields.includes("data")) return true;
1986
- if (fields.includes("event")) return fields.every((field) => SSE_FIELDS.has(field));
1987
- return [...schema.oneOf ?? [], ...schema.anyOf ?? []].some((member) => declaresEventFields(member, refs, seen));
2080
+ function createDiscriminantNode({ propertyName, values }) {
2081
+ return _kubb_kit.ast.factory.createSchema({
2082
+ type: "object",
2083
+ primitive: "object",
2084
+ properties: [_kubb_kit.ast.factory.createProperty({
2085
+ name: propertyName,
2086
+ schema: _kubb_kit.ast.factory.createSchema({
2087
+ type: "enum",
2088
+ primitive: (0, _kubb_kit.enumPrimitive)(values),
2089
+ enumValues: values
2090
+ }),
2091
+ required: true
2092
+ })]
2093
+ });
1988
2094
  }
1989
- /**
1990
- * Returns `'event'` when the item is a whole event, directly or in a composition member (see `declaresEventFields`), else `'data'`.
1991
- */
1992
- function getItemShape(schema, refs) {
1993
- return declaresEventFields(schema, refs, /* @__PURE__ */ new Set()) ? "event" : "data";
2095
+ function toMappingRef(value) {
2096
+ return value.includes("/") ? value : `${SCHEMA_REF_PREFIX}${value}`;
1994
2097
  }
1995
2098
  /**
1996
- * Returns the raw item schema: `itemSchema`, or `schema` on `text/event-stream` as 3.0 and 3.1 documents write one event.
2099
+ * Returns the `$ref` of an OpenAPI 3.2 `defaultMapping`, written as a schema name or a `$ref`; `undefined` when none.
1997
2100
  */
1998
- function getItemSchema({ contentType, mediaType, refs, document }) {
1999
- if (!mediaType || !isStream(contentType, mediaType)) return null;
2000
- const raw = mediaType.itemSchema ?? (isEventStream(contentType) && !isOpenApi32(document) ? mediaType.schema : void 0);
2001
- if (!raw) return null;
2002
- return isEventStream(contentType) ? toEventSchema(raw, refs) : raw;
2101
+ function getDefaultMappingRef(discriminator) {
2102
+ const value = discriminator?.defaultMapping;
2103
+ if (!value) return void 0;
2104
+ return toMappingRef(value);
2003
2105
  }
2004
- // src/emit/schemaShape.ts
2005
2106
  /**
2006
- * Whether `format` maps to a dedicated type; `false` is what `KUBB_UNSUPPORTED_FORMAT` flags.
2107
+ * Returns every discriminator key whose mapping value matches `ref`, in mapping order.
2108
+ * A bare schema name in the mapping matches its `#/components/schemas/<name>` ref.
2109
+ *
2110
+ * A mapping may point several keys at the same schema, in which case the member has to be
2111
+ * narrowed to all of them — keeping only the first would drop the rest from the union.
2112
+ *
2113
+ * @example
2114
+ * ```ts
2115
+ * findDiscriminators({ mapping: { dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, ref: '#/components/schemas/Dog' }) // ['dog', 'hound']
2116
+ * ```
2007
2117
  */
2008
- function isHandledFormat(format) {
2009
- return formatMap[format] !== void 0 || specialCasedFormats.has(format);
2118
+ function findDiscriminators({ mapping, ref }) {
2119
+ if (!mapping || !ref) return [];
2120
+ return Object.entries(mapping).filter(([, value]) => toMappingRef(value) === ref).map(([key]) => key);
2010
2121
  }
2011
2122
  /**
2012
- * Resolves the `dateType` option down to the value for one format. The scalar form of
2013
- * `dateType` applies to every format; the object form picks `dateTime`/`date`/`time`
2014
- * individually and defaults an omitted key to `'string'`.
2123
+ * Finds the discriminator a schema declares itself or through an inline `allOf` member.
2015
2124
  */
2016
- function resolveDateTypeValue(dateType, format) {
2017
- if (typeof dateType !== "object" || dateType === null) return dateType;
2018
- return dateType[format === "date-time" ? "dateTime" : format] ?? "string";
2125
+ function getDiscriminator(schema) {
2126
+ return (isDiscriminator(schema) ? schema : schema.allOf?.find(isDiscriminator))?.discriminator;
2019
2127
  }
2020
2128
  /**
2021
- * Reads schema examples as an array. OAS 3.1 uses an `examples` array, but specs (including ones
2022
- * labeled 3.1) still use the singular OAS 3.0 `example`, which the upgrader only converts on the
2023
- * 3.0 -> 3.1 hop. Normalize both into one array so the AST node exposes only `examples`.
2129
+ * Lists the mapping keys of a discriminator plus the keys of the nested discriminators its mapped
2130
+ * schemas declare on the same property, so a root `$type` accepts values from every level.
2024
2131
  */
2025
- function extractExamples(schema) {
2026
- if (Array.isArray(schema.examples)) return schema.examples;
2027
- return schema.example !== void 0 ? [schema.example] : void 0;
2132
+ function getMappingKeys({ discriminator: { propertyName, mapping }, refs, seen = /* @__PURE__ */ new Set() }) {
2133
+ return Object.entries(mapping ?? {}).flatMap(([key, value]) => {
2134
+ const target = toMappingRef(value);
2135
+ if (seen.has(target)) return [key];
2136
+ seen.add(target);
2137
+ const resolved = refs.resolve(target, { report: false });
2138
+ const nested = resolved && getDiscriminator(resolved);
2139
+ return nested?.propertyName === propertyName ? [key, ...getMappingKeys({
2140
+ discriminator: nested,
2141
+ refs,
2142
+ seen
2143
+ })] : [key];
2144
+ });
2028
2145
  }
2029
2146
  /**
2030
- * Whether the schema and its inline `allOf` members hold more than one distinct `pattern`. A value must match every one.
2147
+ * Drops the discriminator from an inline `allOf` member when a `$ref` sibling already declares one on
2148
+ * the same property. That mapping names the schema's own children, and keeping it pins the property
2149
+ * to those keys next to the parent's, which leaves `never`.
2031
2150
  */
2032
- function hasSeveralPatterns(schema) {
2033
- const patterns = [schema, ...schema.allOf ?? []].map((item) => isReference(item) ? void 0 : item.pattern).filter((pattern) => pattern !== void 0);
2034
- return new Set(patterns).size > 1;
2035
- }
2036
- function hasStructuralKeywords(fragment) {
2037
- return Object.keys(fragment).some((key) => structuralKeys.has(key));
2151
+ function removeInheritedDiscriminator({ members, refs }) {
2152
+ const inherited = new Set(members.flatMap((member) => {
2153
+ const parent = isReference(member) ? refs.resolve(member.$ref, { report: false }) : null;
2154
+ return parent && getDiscriminator(parent)?.propertyName || [];
2155
+ }));
2156
+ return members.map((member) => {
2157
+ if (isReference(member) || !isDiscriminator(member) || member.oneOf || member.anyOf) return member;
2158
+ if (!inherited.has(member.discriminator.propertyName)) return member;
2159
+ const { discriminator: _discriminator, ...rest } = member;
2160
+ return rest;
2161
+ });
2038
2162
  }
2039
2163
  /**
2040
- * Flattens a keyword-only `allOf` into its parent schema.
2041
- *
2042
- * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords
2043
- * (see `structuralKeys`). Outer schema values take precedence over fragment values. Returns the
2044
- * original schema unchanged when flattening is unsafe.
2045
- *
2046
- * @example
2047
- * ```ts
2048
- * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })
2049
- * // { type: 'object', properties: {}, description: 'A pet' }
2050
- * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })
2051
- * // returned unchanged, contains a $ref
2052
- * ```
2164
+ * Whether a member can carry the discriminator property. A discriminator is only a hint, so an array
2165
+ * or primitive member keeps its own type instead of an intersection no value can satisfy.
2053
2166
  */
2054
- function flattenSchema(schema) {
2055
- if (!schema.allOf?.length) return schema;
2056
- const allOfFragments = schema.allOf;
2057
- if (allOfFragments.some((item) => isReference(item))) return schema;
2058
- if (allOfFragments.some(hasStructuralKeywords)) return schema;
2059
- if (hasSeveralPatterns(schema)) return schema;
2060
- const { allOf: _allOf, ...rest } = schema;
2061
- const merged = rest;
2062
- for (const fragment of allOfFragments) for (const [key, value] of Object.entries(fragment)) merged[key] ??= value;
2063
- return merged;
2167
+ function isObjectLike(member, refs) {
2168
+ const type = (isReference(member) ? refs.resolve(member.$ref, { report: false }) : member)?.type;
2169
+ if (type === void 0) return true;
2170
+ return Array.isArray(type) ? type.includes("object") : type === "object";
2064
2171
  }
2065
- // src/schemaDiagnostics.ts
2066
2172
  /**
2067
- * Links one freshly converted schema and its nested schemas to their RFC 6901 pointers
2068
- * (`#/components/schemas/Pet/properties/owner/properties/name`), and reports the advisory
2069
- * diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`, `KUBB_DUPLICATE_DISCRIMINATOR`) against them.
2070
- * Refs are not followed, so the resolved schema is handled under its own walk.
2071
- * Reports land in the active build run, are a no-op outside one, and repeats are deduped by the build.
2173
+ * Narrows each `oneOf`/`anyOf` member with its discriminant value, intersecting the member's own
2174
+ * node with either the shared-properties slice carrying that value, or a synthetic discriminant
2175
+ * literal. The referenced child schema's own definition is left untouched — narrowing happens only
2176
+ * at this union usage site, which is what makes this mode "preserve" (as opposed to `propagate`,
2177
+ * which additionally patches the child schema's own definition in a post-pass).
2072
2178
  */
2073
- function scanSchema(node, pointer = node.pointer) {
2074
- if (pointer) visit(node, pointer);
2075
- }
2076
- var FormatTally = class {
2077
- #pointers;
2078
- group(fn) {
2079
- this.#pointers = memo.create();
2080
- try {
2081
- return fn();
2082
- } finally {
2083
- const tally = this.#pointers;
2084
- this.#pointers = void 0;
2085
- for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers]);
2086
- }
2087
- }
2088
- add(format, pointer) {
2089
- if (!this.#pointers) return reportUnsupportedFormat(format, [pointer]);
2090
- memo(this.#pointers, format, () => /* @__PURE__ */ new Set()).add(pointer);
2179
+ function narrowUnionMembers({ unionMembers, discriminator, sharedPropertiesNode, parentType, parse, name, refs }) {
2180
+ function pickDiscriminatorPropertyNode(node, propertyName) {
2181
+ const discriminatorProperty = _kubb_kit.ast.schema.narrow(node, "object")?.properties?.find((property) => property.name === propertyName);
2182
+ if (!discriminatorProperty) return null;
2183
+ return _kubb_kit.ast.factory.createSchema({
2184
+ type: "object",
2185
+ primitive: "object",
2186
+ properties: [discriminatorProperty]
2187
+ });
2091
2188
  }
2092
- };
2093
- const formatTally = new FormatTally();
2094
- /**
2095
- * Runs `fn` and reports `KUBB_UNSUPPORTED_FORMAT` once per format with the number of schemas that use it,
2096
- * instead of once per schema. `format` is an open value in OpenAPI, so a large spec would otherwise print
2097
- * thousands of warnings that say the same thing. `fn` must be synchronous.
2098
- */
2099
- function groupUnsupportedFormats(fn) {
2100
- return formatTally.group(fn);
2101
- }
2102
- function reportUnsupportedFormat(format, pointers) {
2103
- const count = pointers.length;
2104
- _kubb_kit.Diagnostics.report({
2105
- code: _kubb_kit.Diagnostics.code.unsupportedFormat,
2106
- severity: "warning",
2107
- message: count === 1 ? `Kubb does not map the format "${format}" to a specific type, so it falls back to the base type.` : `Kubb does not map the format "${format}" to a specific type, so ${count} schemas fall back to the base type.`,
2108
- help: `Use a format Kubb supports, or handle "${format}" with a custom parser or plugin.`,
2109
- location: {
2110
- kind: "schema",
2111
- pointer: pointers[0]
2112
- }
2113
- });
2114
- }
2115
- function visit(node, pointer) {
2116
- node.pointer ??= pointer;
2117
- if (node.deprecated) _kubb_kit.Diagnostics.report({
2118
- code: _kubb_kit.Diagnostics.code.deprecated,
2119
- severity: "info",
2120
- message: "This schema is marked as deprecated.",
2121
- location: {
2122
- kind: "schema",
2123
- pointer
2189
+ function implicitDiscriminantValue(member) {
2190
+ if (!discriminator || discriminator.mapping || !isReference(member)) return null;
2191
+ const value = _kubb_kit.ast.ref.getName(member.$ref);
2192
+ if (!value) return null;
2193
+ const variant = refs.resolve(member.$ref, { report: false });
2194
+ if (!variant) return null;
2195
+ const propertyName = discriminator.propertyName;
2196
+ const seen = /* @__PURE__ */ new Set([member.$ref]);
2197
+ /** Whether the variant, or a schema it composes, pins the discriminator property to literal values. */
2198
+ function constrains(v) {
2199
+ const prop = v.properties?.[propertyName];
2200
+ const resolved = prop && isReference(prop) ? refs.resolve(prop.$ref, { report: false }) : prop;
2201
+ const pins = (candidate) => Array.isArray(candidate.enum) || candidate.const !== void 0;
2202
+ const members = (resolved?.anyOf ?? resolved?.oneOf ?? []).filter((member) => member.type !== "null");
2203
+ if (resolved && (pins(resolved) || members.length > 0 && members.every(pins))) return true;
2204
+ const composition = v.allOf ?? v.oneOf ?? v.anyOf;
2205
+ if (!composition) return false;
2206
+ return composition.some((m) => {
2207
+ if (!isReference(m)) return constrains(m);
2208
+ if (seen.has(m.$ref)) return false;
2209
+ seen.add(m.$ref);
2210
+ const r = refs.resolve(m.$ref, { report: false });
2211
+ return r ? constrains(r) : false;
2212
+ });
2124
2213
  }
2125
- });
2126
- if (typeof node.format === "string" && !isHandledFormat(node.format)) formatTally.add(node.format, pointer);
2127
- if (node.type === "object") {
2128
- for (const property of node.properties) visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`);
2129
- if (node.additionalProperties && typeof node.additionalProperties === "object") visit(node.additionalProperties, `${pointer}/additionalProperties`);
2130
- return;
2131
- }
2132
- if (node.type === "array") {
2133
- for (const item of node.items ?? []) visit(item, `${pointer}/items`);
2134
- return;
2135
- }
2136
- if (node.type === "tuple") {
2137
- for (const [index, item] of (node.items ?? []).entries()) visit(item, `${pointer}/items/${index}`);
2138
- return;
2139
- }
2140
- if (node.type === "not") {
2141
- for (const member of node.members ?? []) visit(member, `${pointer}/not`);
2142
- return;
2143
- }
2144
- if (node.type === "union" && node.discriminatorPropertyName) reportDuplicateDiscriminators(node, node.discriminatorPropertyName, pointer);
2145
- if (node.type === "union" || node.type === "intersection") {
2146
- const keyword = node.type === "intersection" ? "allOf" : node.strategy === "any" ? "anyOf" : "oneOf";
2147
- for (const [index, member] of (node.members ?? []).entries()) visit(member, `${pointer}/${keyword}/${index}`);
2214
+ return constrains(variant) ? null : value;
2148
2215
  }
2216
+ const defaultRef = getDefaultMappingRef(discriminator);
2217
+ return unionMembers.map((s) => {
2218
+ const ref = isReference(s) ? s.$ref : void 0;
2219
+ const isDefault = ref !== void 0 && ref === defaultRef;
2220
+ const mappedValues = isDefault ? [] : findDiscriminators({
2221
+ mapping: discriminator?.mapping,
2222
+ ref
2223
+ });
2224
+ const implicitValue = mappedValues.length || isDefault ? null : implicitDiscriminantValue(s);
2225
+ const propertyType = propertyTypeOf({
2226
+ schema: s,
2227
+ propertyName: discriminator?.propertyName ?? "",
2228
+ refs
2229
+ }) ?? parentType;
2230
+ const discriminatorValues = typedKeys({
2231
+ keys: mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : [],
2232
+ propertyType
2233
+ });
2234
+ const memberNode = parse({
2235
+ schema: s,
2236
+ name
2237
+ });
2238
+ if (!discriminatorValues.length || !discriminator || !isObjectLike(s, refs)) return memberNode;
2239
+ const narrowedDiscriminatorNode = sharedPropertiesNode ? pickDiscriminatorPropertyNode(_kubb_kit.ast.macro.apply(sharedPropertiesNode, [(0, _kubb_kit.macroDiscriminatorEnum)({
2240
+ propertyName: discriminator.propertyName,
2241
+ values: discriminatorValues
2242
+ })], { depth: "shallow" }), discriminator.propertyName) : void 0;
2243
+ return _kubb_kit.ast.factory.createSchema({
2244
+ type: "intersection",
2245
+ members: [memberNode, narrowedDiscriminatorNode ?? createDiscriminantNode({
2246
+ propertyName: discriminator.propertyName,
2247
+ values: discriminatorValues
2248
+ })]
2249
+ });
2250
+ });
2149
2251
  }
2150
2252
  /**
2151
- * Reports a declared discriminator whose value pins more than one member. The spec cannot tell
2152
- * those members apart, and Zod's `z.discriminatedUnion` throws on the first parse.
2153
- * One diagnostic per union, since the build dedupes by code and pointer.
2253
+ * Filters the discriminated members out of an `allOf` list: an `allOf` member that `$ref`s a
2254
+ * discriminated union's parent, where this schema is itself one of that union's children, is
2255
+ * dropped from `members` and its discriminant value collected instead — the same synthetic
2256
+ * literal `narrowUnionMembers` produces, so the emitted node stays a plain intersection rather
2257
+ * than nesting the whole parent union one level deeper.
2154
2258
  */
2155
- function reportDuplicateDiscriminators(node, propertyName, pointer) {
2156
- const keyword = node.strategy === "any" ? "anyOf" : "oneOf";
2157
- const membersByValue = memo.create();
2158
- for (const [index, member] of (node.members ?? []).entries()) {
2159
- const label = memberName(member) ?? `${keyword}/${index}`;
2160
- for (const value of memberValues(member, propertyName)) memo(membersByValue, value, () => []).push(label);
2161
- }
2162
- const duplicates = [...membersByValue].filter(([, members]) => members.length > 1);
2163
- if (!duplicates.length) return;
2164
- _kubb_kit.Diagnostics.report({
2165
- code: _kubb_kit.Diagnostics.code.duplicateDiscriminator,
2166
- severity: "warning",
2167
- message: duplicates.map(([value, members]) => `Discriminator "${propertyName}" value ${JSON.stringify(value)} matches more than one member (${members.join(", ")}).`).join(" "),
2168
- help: `Give each member its own "${propertyName}" value, or drop the discriminator. Zod's z.discriminatedUnion throws on the first parse of this union.`,
2169
- location: {
2170
- kind: "schema",
2171
- pointer
2172
- }
2173
- });
2174
- }
2175
- function memberValues(node, propertyName, seen = /* @__PURE__ */ new Set()) {
2176
- if (seen.has(node)) return [];
2177
- seen.add(node);
2178
- const target = node.type === "ref" && node.schema ? node.schema : node;
2179
- if (target.type === "union") return [...new Set(target.members?.flatMap((member) => memberValues(member, propertyName, seen)))];
2180
- return intersect(_kubb_kit.ast.schema.findProperties({
2181
- node,
2182
- propertyName
2183
- }).map((property) => [..._kubb_kit.ast.schema.getLiterals(property.schema)]));
2184
- }
2185
- function intersect(slices) {
2186
- const pinned = slices.filter((values) => values.length > 0);
2187
- return pinned.reduce((acc, values) => acc.filter((value) => values.includes(value)), pinned[0] ?? []);
2259
+ function extractDiscriminatedAllOfMembers({ allOfMembers, name, refs }) {
2260
+ const discriminantValues = [];
2261
+ return {
2262
+ members: allOfMembers.filter((item) => {
2263
+ if (!isReference(item) || !name) return true;
2264
+ const deref = refs.resolve(item.$ref);
2265
+ const discriminator = deref && getDiscriminator(deref);
2266
+ const parentUnion = deref?.oneOf ?? deref?.anyOf;
2267
+ if (!deref || !discriminator || isDiscriminator(deref) && !parentUnion) return true;
2268
+ const childRef = `${SCHEMA_REF_PREFIX}${name}`;
2269
+ const isDefault = childRef === getDefaultMappingRef(discriminator);
2270
+ const values = isDefault ? [] : findDiscriminators({
2271
+ mapping: discriminator.mapping,
2272
+ ref: childRef
2273
+ });
2274
+ if (values.length) {
2275
+ const { propertyName } = discriminator;
2276
+ const propertyType = propertyTypeOf({
2277
+ schema: deref,
2278
+ propertyName,
2279
+ refs
2280
+ }) ?? propertyTypeOf({
2281
+ schema: { $ref: childRef },
2282
+ propertyName,
2283
+ refs
2284
+ });
2285
+ discriminantValues.push({
2286
+ propertyName,
2287
+ values: typedKeys({
2288
+ keys: values,
2289
+ propertyType
2290
+ })
2291
+ });
2292
+ }
2293
+ return !(parentUnion && (isDefault || values.length > 0 || parentUnion.some((member) => isReference(member) && member.$ref === childRef)));
2294
+ }),
2295
+ discriminantValues
2296
+ };
2188
2297
  }
2189
- function memberName(member) {
2190
- if (member.type === "ref") return member.name ?? void 0;
2191
- if (member.type === "intersection") return member.members?.map(memberName).find(Boolean);
2298
+ // src/emit/converters/annotatedEnum.ts
2299
+ const ANNOTATIONS = /* @__PURE__ */ new Set([
2300
+ "title",
2301
+ "description",
2302
+ "default",
2303
+ "deprecated",
2304
+ "readOnly",
2305
+ "writeOnly",
2306
+ "example",
2307
+ "examples",
2308
+ "xml",
2309
+ "externalDocs"
2310
+ ]);
2311
+ const UNION_KEYS = /* @__PURE__ */ new Set([
2312
+ ...ANNOTATIONS,
2313
+ "type",
2314
+ "nullable",
2315
+ "oneOf",
2316
+ "anyOf"
2317
+ ]);
2318
+ const MEMBER_KEYS = /* @__PURE__ */ new Set([
2319
+ ...ANNOTATIONS,
2320
+ "type",
2321
+ "const"
2322
+ ]);
2323
+ function hasOnlyKeys(schema, keys) {
2324
+ return typeof schema === "object" && schema !== null && !Array.isArray(schema) && Object.keys(schema).every((key) => keys.has(key) || key.startsWith("x-"));
2192
2325
  }
2193
- // src/operation.ts
2194
- function slugify(value) {
2195
- return value.replace(/[^a-zA-Z0-9]/g, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "");
2326
+ function matchesType(type, value) {
2327
+ return type === void 0 || type === typeof value || type === "integer" && typeof value === "number" && Number.isInteger(value);
2196
2328
  }
2197
- /**
2198
- * Returns the operation's JSON pointer, under `additionalOperations` for an OpenAPI 3.2 method outside the fixed fields.
2199
- */
2200
- function getOperationPointer({ path, method }) {
2201
- const pathPointer = `#/paths/${escapePointerToken(path)}`;
2202
- return SUPPORTED_METHODS.has(method.toLowerCase()) ? `${pathPointer}/${method.toLowerCase()}` : `${pathPointer}/additionalOperations/${escapePointerToken(method)}`;
2329
+ /** Recognizes annotated const unions only when replacing them cannot discard validation constraints. */
2330
+ function convertAnnotatedEnum(context) {
2331
+ const { schema, document } = context;
2332
+ if (!document.openapi?.startsWith("3.1.")) return void 0;
2333
+ if (!hasOnlyKeys(schema, UNION_KEYS) || schema.oneOf !== void 0 && schema.anyOf !== void 0) return void 0;
2334
+ const members = schema.oneOf ?? schema.anyOf;
2335
+ if (!members?.length) return void 0;
2336
+ const names = /* @__PURE__ */ new Set();
2337
+ const values = /* @__PURE__ */ new Set();
2338
+ const namedEnumValues = [];
2339
+ let primitive;
2340
+ for (const member of members) {
2341
+ if (!hasOnlyKeys(member, MEMBER_KEYS)) return void 0;
2342
+ const value = member.const;
2343
+ if (typeof value !== "string" && (typeof value !== "number" || !Number.isFinite(value))) return void 0;
2344
+ if (typeof member.title !== "string" || !member.title.trim() || names.has(member.title) || values.has(value)) return void 0;
2345
+ if (!matchesType(schema.type, value) || !matchesType(member.type, value)) return void 0;
2346
+ const valueType = typeof value === "number" ? "number" : "string";
2347
+ if (primitive !== void 0 && primitive !== valueType) return void 0;
2348
+ primitive = valueType;
2349
+ names.add(member.title);
2350
+ values.add(value);
2351
+ namedEnumValues.push({
2352
+ name: member.title,
2353
+ value,
2354
+ primitive: valueType,
2355
+ description: member.description
2356
+ });
2357
+ }
2358
+ return createNode(context, {
2359
+ type: "enum",
2360
+ primitive,
2361
+ namedEnumValues
2362
+ });
2203
2363
  }
2364
+ // src/emit/converters/composition.ts
2204
2365
  /**
2205
- * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.
2366
+ * Collects property schemas from all `allOf` members and outer schema properties,
2367
+ * recursively resolving `$ref` pointers.
2206
2368
  */
2207
- function getOperationId({ path, method, schema }) {
2208
- const { operationId } = schema;
2209
- if (typeof operationId === "string" && operationId.length > 0) return operationId;
2210
- return `${method}_${slugify(path).toLowerCase()}`;
2369
+ function collectSiblingProperties(allOfMembers, refs, outerProperties) {
2370
+ const properties = Object.assign(Object.create(null), outerProperties);
2371
+ const visited = /* @__PURE__ */ new Set();
2372
+ /** Adds the properties of one member, following its `$ref` and its own `allOf`. */
2373
+ function collectFrom(item) {
2374
+ if (!item) return;
2375
+ if (isReference(item)) {
2376
+ const { $ref, ...siblings } = item;
2377
+ if (!visited.has($ref)) {
2378
+ visited.add($ref);
2379
+ collectFrom(refs.resolve($ref, { report: false }) ?? void 0);
2380
+ }
2381
+ collectFrom(siblings);
2382
+ return;
2383
+ }
2384
+ if (item.properties) Object.assign(properties, item.properties);
2385
+ if (Array.isArray(item.allOf)) for (const member of item.allOf) collectFrom(member);
2386
+ }
2387
+ for (const item of allOfMembers) collectFrom(item);
2388
+ return properties;
2211
2389
  }
2212
2390
  /**
2213
- * Returns the declared response status codes, skipping `x-` extensions and non-object entries.
2391
+ * Enriches union members that declare `required` properties without declaring corresponding
2392
+ * property schemas, populating the missing property definitions from available sibling schemas
2393
+ * (or an empty schema falling back to the configured emptySchemaType).
2214
2394
  */
2215
- function getResponseStatusCodes({ schema }) {
2216
- const responses = schema.responses;
2217
- if (!responses || isReference(responses)) return [];
2218
- return Object.keys(responses).filter((key) => !key.startsWith("x-") && !!responses[key] && typeof responses[key] === "object");
2395
+ function resolveUnionMembers(members, siblingProperties) {
2396
+ return members.map((member) => {
2397
+ if (!member || typeof member !== "object" || isReference(member)) return member;
2398
+ const obj = member;
2399
+ if (!Array.isArray(obj.required) || obj.required.length === 0) return member;
2400
+ const existingProps = obj.properties ?? {};
2401
+ const missingKeys = obj.required.filter((key) => !Object.hasOwn(existingProps, key));
2402
+ if (missingKeys.length === 0) return member;
2403
+ const newProperties = { ...existingProps };
2404
+ for (const key of missingKeys) {
2405
+ const value = Object.hasOwn(siblingProperties, key) ? siblingProperties[key] : {};
2406
+ Object.defineProperty(newProperties, key, {
2407
+ value,
2408
+ enumerable: true,
2409
+ writable: true,
2410
+ configurable: true
2411
+ });
2412
+ }
2413
+ return {
2414
+ type: obj.type ?? "object",
2415
+ ...obj,
2416
+ properties: newProperties
2417
+ };
2418
+ });
2219
2419
  }
2220
2420
  /**
2221
- * Returns the response object for a status code, resolving a `$ref` through `refs`. `null` when absent.
2421
+ * Enriches a schema object, and any `oneOf` or `anyOf` branches on it, with properties from sibling schemas.
2222
2422
  */
2223
- function getResponseByStatusCode({ operation, refs, statusCode }) {
2224
- const responses = operation.schema.responses;
2225
- if (!responses || isReference(responses)) return null;
2226
- return refs.deref(responses[statusCode]);
2423
+ function resolveUnionSchema(schema, siblingProperties) {
2424
+ const next = { ...resolveUnionMembers([schema], siblingProperties)[0] ?? schema };
2425
+ if (schema.oneOf) next.oneOf = resolveUnionMembers(schema.oneOf, siblingProperties);
2426
+ if (schema.anyOf) next.anyOf = resolveUnionMembers(schema.anyOf, siblingProperties);
2427
+ return next;
2227
2428
  }
2228
2429
  /**
2229
- * Resolves the operation's request body, dereferencing a `$ref` through `refs`. Returns `null`
2230
- * when the operation has no request body or it cannot be resolved.
2430
+ * Converts a `$ref` schema into a `RefSchemaNode`.
2431
+ *
2432
+ * The resolved schema is stored in `node.schema`. Usage-site sibling fields
2433
+ * (description, readOnly, nullable, etc.) are stored directly on the ref node.
2434
+ * Use `ast.ref.mergeSchema(node)` in printers to get a merged view of both.
2435
+ * Circular refs are detected in `refs.resolveNode` and leave `schema` as `null`.
2231
2436
  */
2232
- function getRequestBody({ operation, refs }) {
2233
- return refs.deref(operation.schema.requestBody);
2234
- }
2235
- /** Merges path-level and operation-level parameters; operation-level wins per `in:name`. */
2236
- function getParameters({ operation, refs }) {
2237
- const resolveParams = (params, pointer) => params.flatMap((entry, index) => {
2238
- const param = refs.derefKeepingRef(entry);
2239
- return param && typeof param === "object" && "in" in param && "name" in param ? [{
2240
- param,
2241
- pointer: `${pointer}/parameters/${index}`
2242
- }] : [];
2243
- });
2244
- const pathPointer = `#/paths/${escapePointerToken(operation.path)}`;
2245
- const operationParams = resolveParams(operation.schema?.parameters || [], getOperationPointer(operation));
2246
- const pathLevelParams = resolveParams(operation.pathItem.parameters ?? [], pathPointer);
2247
- const paramMap = /* @__PURE__ */ new Map();
2248
- for (const entry of [...pathLevelParams, ...operationParams]) if (entry.param.name && entry.param.in) paramMap.set(`${entry.param.in}:${entry.param.name}`, entry);
2249
- return Array.from(paramMap.values());
2250
- }
2251
- const PARAMETER_STYLES = /* @__PURE__ */ new Set([
2252
- "matrix",
2253
- "label",
2254
- "form",
2255
- "simple",
2256
- "spaceDelimited",
2257
- "pipeDelimited",
2258
- "deepObject",
2259
- "cookie"
2260
- ]);
2261
- function pickStyleFields({ style, explode, allowReserved }) {
2262
- return {
2263
- ...style !== void 0 && PARAMETER_STYLES.has(style) ? { style } : {},
2264
- ...explode !== void 0 ? { explode } : {},
2265
- ...allowReserved !== void 0 ? { allowReserved } : {}
2266
- };
2267
- }
2268
- function getEncodingFields({ encoding, prefixEncoding, itemEncoding }) {
2269
- const entries = Object.entries(encoding ?? {}).flatMap(([property, entry]) => {
2270
- const node = toEncodingNode(entry);
2271
- return Object.keys(node).length ? [[property, node]] : [];
2272
- });
2273
- const item = itemEncoding && toEncodingNode(itemEncoding);
2274
- return {
2275
- ...entries.length && { encoding: Object.fromEntries(entries) },
2276
- ...prefixEncoding?.length && { prefixEncoding: prefixEncoding.map(toEncodingNode) },
2277
- ...item && Object.keys(item).length && { itemEncoding: item }
2437
+ function convertRef({ schema, name, nullable, defaultValue, document, parse, refs, renames }) {
2438
+ const refPath = schema.$ref;
2439
+ const resolvedSchema = refPath ? refs.resolveNode(refPath, parse) : null;
2440
+ const ctx = {
2441
+ schema,
2442
+ name,
2443
+ nullable,
2444
+ defaultValue
2278
2445
  };
2279
- }
2280
- function toEncodingNode({ contentType, encoding, prefixEncoding, itemEncoding, ...rest }) {
2281
- return {
2282
- ...contentType !== void 0 && { contentType },
2283
- ...pickStyleFields(rest),
2284
- ...getEncodingFields({
2285
- encoding,
2286
- prefixEncoding,
2287
- itemEncoding
2446
+ if (refPath && document.components && refs.resolve(refPath, { report: false }) === null) return createNode(ctx, { type: _kubb_kit.ast.schema.types.unknown });
2447
+ if (refPath && !refPath.startsWith("#/components/schemas/") && resolvedSchema) return _kubb_kit.ast.factory.createSchema({
2448
+ ...resolvedSchema,
2449
+ title: schema.title ?? resolvedSchema.title,
2450
+ description: schema.description ?? resolvedSchema.description,
2451
+ deprecated: schema.deprecated ?? resolvedSchema.deprecated,
2452
+ readOnly: schema.readOnly ?? resolvedSchema.readOnly,
2453
+ writeOnly: schema.writeOnly ?? resolvedSchema.writeOnly,
2454
+ default: defaultValue ?? resolvedSchema.default,
2455
+ name: name ?? resolvedSchema.name,
2456
+ nullable: nullable ?? resolvedSchema.nullable,
2457
+ extensions: pickExtensions({
2458
+ ...resolvedSchema.extensions,
2459
+ ...schema
2288
2460
  })
2289
- };
2461
+ });
2462
+ const targetName = renames?.get(schema.$ref);
2463
+ return createNode(ctx, {
2464
+ type: _kubb_kit.ast.schema.types.ref,
2465
+ name: _kubb_kit.ast.ref.getName(schema.$ref),
2466
+ ref: schema.$ref,
2467
+ ...targetName ? { targetName } : {},
2468
+ schema: resolvedSchema
2469
+ });
2290
2470
  }
2291
- function getExamples({ example, examples }, refs) {
2292
- const named = Object.entries(examples ?? {}).flatMap(([name, entry]) => {
2293
- const resolved = refs.deref(entry);
2294
- if (!resolved) return [];
2295
- const { summary, description, dataValue, value, serializedValue } = resolved;
2296
- const data = dataValue !== void 0 ? dataValue : value;
2297
- return [{
2298
- name,
2299
- ...typeof summary === "string" && { summary },
2300
- ...typeof description === "string" && { description },
2301
- ...data !== void 0 && { value: data },
2302
- ...typeof serializedValue === "string" && { serializedValue }
2303
- }];
2471
+ /** Converts `{ ...rest, not: X }` into `intersection[rest, not[X]]`; a bare `required` inside `not` borrows the outer `properties`. */
2472
+ function convertNot({ schema, name, nullable, defaultValue, parse }) {
2473
+ const { not, ...rest } = schema;
2474
+ const [subschema] = resolveUnionMembers([not], rest.properties ?? {});
2475
+ const notNode = _kubb_kit.ast.factory.createSchema({
2476
+ type: _kubb_kit.ast.schema.types.not,
2477
+ members: [parse({ schema: subschema })]
2478
+ });
2479
+ return createNode({
2480
+ schema,
2481
+ name,
2482
+ nullable,
2483
+ defaultValue
2484
+ }, {
2485
+ type: _kubb_kit.ast.schema.types.intersection,
2486
+ members: [parse({
2487
+ schema: rest,
2488
+ name
2489
+ }), notNode]
2304
2490
  });
2305
- if (named.length) return { examples: named };
2306
- return example !== void 0 ? { examples: [{ value: example }] } : {};
2307
2491
  }
2308
2492
  /**
2309
- * Returns the media type entry for `contentType`, resolving a `$ref` into `components.mediaTypes`. `null` when absent.
2493
+ * Keywords that describe a schema or conditionally constrain it, but add no structure.
2310
2494
  */
2311
- function getMediaType({ content, contentType, refs }) {
2312
- return contentType ? refs.deref(content?.[contentType]) : null;
2313
- }
2495
+ const annotationKeys = /* @__PURE__ */ new Set([
2496
+ "description",
2497
+ "title",
2498
+ "example",
2499
+ "examples",
2500
+ "default",
2501
+ "deprecated",
2502
+ "readOnly",
2503
+ "writeOnly",
2504
+ "if",
2505
+ "then",
2506
+ "else"
2507
+ ]);
2314
2508
  /**
2315
- * Returns the schema for one media type of a `content` map, with the binary fallback for an emptied non-JSON
2316
- * entry. For a stream this is the item schema, so `schema: string` next to `itemSchema` types one item.
2509
+ * Moves `allOf` members that hold only annotations or `if`/`then`/`else` onto the parent, so they do
2510
+ * not become `unknown`. The parent's own values win. The parser reads their `if`/`then`/`else` into `conditionals`.
2317
2511
  */
2318
- function getBodySchema({ content, contentType, refs, document }) {
2319
- const entry = getMediaType({
2320
- content,
2321
- contentType,
2322
- refs
2323
- });
2324
- if (!contentType || !entry) return null;
2325
- const schema = getItemSchema({
2326
- contentType,
2327
- mediaType: entry,
2328
- refs,
2329
- document
2330
- }) ?? entry.schema;
2331
- const binary = entry.itemSchema ? void 0 : getBinaryFallbackSchema(contentType, schema);
2332
- if (binary) return binary;
2333
- return schema ? refs.derefKeepingRef(schema) : null;
2334
- }
2335
- function getLinks(links, refs) {
2336
- const entries = Object.entries(links ?? {}).flatMap(([name, value]) => {
2337
- const link = refs.deref(value);
2338
- if (!link) return [];
2339
- const server = link.server ? toInputServers([link.server])[0] : void 0;
2340
- return [[name, {
2341
- ...pickStrings(link, [
2342
- "operationId",
2343
- "operationRef",
2344
- "description"
2345
- ]),
2346
- ...link.parameters && { parameters: link.parameters },
2347
- ..."requestBody" in link && { requestBody: link.requestBody },
2348
- ...server && { server }
2349
- }]];
2350
- });
2351
- return entries.length ? Object.fromEntries(entries) : void 0;
2512
+ function isAnnotationMember(member) {
2513
+ return !!member && typeof member === "object" && !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key));
2352
2514
  }
2353
- /** The `stream` field of a content node, set when the media type is a stream. `node` is the parsed item schema. */
2354
- function getStreamField({ contentType, mediaType, refs, document, node }) {
2355
- if (!isStream(contentType, mediaType)) return {};
2356
- const raw = getItemSchema({
2357
- contentType,
2358
- mediaType,
2359
- refs,
2360
- document
2361
- });
2362
- return { stream: {
2363
- ...raw ? { schema: node } : {},
2364
- ...raw && isEventStream(contentType) ? { shape: getItemShape(raw, refs) } : {}
2365
- } };
2515
+ function mergeAnnotations(schema) {
2516
+ const members = schema.allOf;
2517
+ const annotations = members.filter(isAnnotationMember);
2518
+ const rest = members.filter((member) => !isAnnotationMember(member));
2519
+ return annotations.length && rest.length ? {
2520
+ ...Object.assign({}, ...annotations),
2521
+ ...schema,
2522
+ allOf: rest
2523
+ } : schema;
2366
2524
  }
2367
- /** The media type keyword the body schema was read from, for the diagnostic pointer. */
2368
- function schemaKeyword(mediaType) {
2369
- return mediaType?.itemSchema ? "itemSchema" : "schema";
2525
+ /**
2526
+ * Whether the parent's own keywords become an intersection member: always beside `properties`, and
2527
+ * beside several patterns when the parent holds more than its type and annotations, such as `minLength`.
2528
+ */
2529
+ function keepsOwnKeywords(schema) {
2530
+ if (schema.properties) return true;
2531
+ if (!hasSeveralPatterns(schema)) return false;
2532
+ return Object.keys(schema).some((key) => key !== "allOf" && key !== "type" && key !== "nullable" && !annotationKeys.has(key));
2370
2533
  }
2371
- /** Pointer of a media type entry, following a `$ref` into `components.mediaTypes` so a diagnostic lands on the source. */
2372
- function mediaTypePointer(content, contentType, fallback) {
2373
- const entry = content?.[contentType];
2374
- return isReference(entry) ? entry.$ref : fallback;
2534
+ /**
2535
+ * Whether a one-member `allOf` adds nothing but annotations, so it parses as that member.
2536
+ */
2537
+ function isSingleMemberAllOf(schema) {
2538
+ return schema.allOf.length === 1 && !schema.properties && !(Array.isArray(schema.required) && schema.required.length) && schema.additionalProperties === void 0 && !hasSeveralPatterns(schema);
2375
2539
  }
2376
2540
  /**
2377
- * Builds an `Operation` for every supported HTTP method and every OpenAPI 3.2 `additionalOperations` entry on
2378
- * every path, in document order. `x-` path keys and unresolvable path-item `$ref`s are skipped.
2541
+ * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.
2379
2542
  */
2380
- function getOperations(document, refs) {
2381
- const operations = [];
2382
- const paths = document.paths;
2383
- if (!paths) return operations;
2384
- for (const path of Object.keys(paths)) {
2385
- if (path.startsWith("x-")) continue;
2386
- const pathItem = refs.deref(paths[path]);
2387
- if (!pathItem) continue;
2388
- const item = pathItem;
2389
- for (const method of Object.keys(item)) {
2390
- if (!SUPPORTED_METHODS.has(method)) continue;
2391
- const schema = item[method];
2392
- if (!schema || typeof schema !== "object") continue;
2393
- operations.push({
2394
- path,
2395
- method,
2396
- schema,
2397
- pathItem
2398
- });
2399
- }
2400
- for (const [method, schema] of Object.entries(pathItem.additionalOperations ?? {})) if (schema && typeof schema === "object" && !SUPPORTED_METHODS.has(method.toLowerCase())) operations.push({
2401
- path,
2402
- method,
2403
- schema,
2404
- pathItem
2543
+ function convertAllOf({ schema: original, name, nullable, defaultValue, parse, refs }) {
2544
+ const schema = mergeAnnotations(original);
2545
+ if (isSingleMemberAllOf(schema)) {
2546
+ const [memberSchema] = schema.allOf;
2547
+ const memberNode = parse({
2548
+ schema: memberSchema,
2549
+ name
2405
2550
  });
2406
- }
2407
- return withUniqueOperationIds(operations);
2408
- }
2409
- function suffixed(id, taken, counts) {
2410
- const count = (counts.get(id) ?? 1) + 1;
2411
- counts.set(id, count);
2412
- const candidate = `${id}_${count}`;
2413
- return taken.has((0, _kubb_core.pascalCase)(candidate)) ? suffixed(id, taken, counts) : candidate;
2414
- }
2415
- function withUniqueOperationIds(operations) {
2416
- const taken = new Set(operations.flatMap(({ schema }) => typeof schema.operationId === "string" && schema.operationId ? [(0, _kubb_core.pascalCase)(schema.operationId)] : []));
2417
- const claimed = /* @__PURE__ */ new Set();
2418
- const counts = /* @__PURE__ */ new Map();
2419
- return operations.map((operation) => {
2420
- const operationId = getOperationId(operation);
2421
- const name = (0, _kubb_core.pascalCase)(operationId);
2422
- if (!claimed.has(name)) {
2423
- claimed.add(name);
2424
- taken.add(name);
2425
- return operation;
2426
- }
2427
- const unique = suffixed(operationId, taken, counts);
2428
- taken.add((0, _kubb_core.pascalCase)(unique));
2429
- claimed.add((0, _kubb_core.pascalCase)(unique));
2430
- _kubb_kit.Diagnostics.report({
2431
- code: _kubb_kit.Diagnostics.code.duplicateOperationId,
2432
- severity: "warning",
2433
- message: `operationId "${operationId}" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to "${unique}".`,
2434
- help: "Give each operation its own `operationId`.",
2435
- location: {
2436
- kind: "operation",
2437
- pointer: getOperationPointer(operation)
2438
- }
2551
+ const { kind: _kind, ...memberNodeProps } = memberNode;
2552
+ const mergedNullable = nullable || memberNode.nullable || void 0;
2553
+ const mergedDefault = schema.default === null && mergedNullable ? void 0 : schema.default ?? memberNode.default;
2554
+ return _kubb_kit.ast.factory.createSchema({
2555
+ ...memberNodeProps,
2556
+ name,
2557
+ title: schema.title ?? memberNode.title,
2558
+ description: schema.description ?? memberNode.description,
2559
+ deprecated: schema.deprecated ?? memberNode.deprecated,
2560
+ nullable: mergedNullable,
2561
+ readOnly: schema.readOnly ?? memberNode.readOnly,
2562
+ writeOnly: schema.writeOnly ?? memberNode.writeOnly,
2563
+ default: mergedDefault,
2564
+ examples: extractExamples(schema) ?? memberNode.examples,
2565
+ pattern: schema.pattern ?? ("pattern" in memberNode ? memberNode.pattern : void 0),
2566
+ format: schema.format ?? memberNode.format,
2567
+ extensions: pickExtensions({
2568
+ ...memberNode.extensions,
2569
+ ...schema
2570
+ }),
2571
+ externalDocs: getExternalDocs(schema.externalDocs) ?? memberNode.externalDocs
2439
2572
  });
2440
- return {
2441
- ...operation,
2442
- schema: {
2443
- ...operation.schema,
2444
- operationId: unique
2445
- }
2446
- };
2447
- });
2448
- }
2449
- /** Property names whose schema has a truthy `readOnly` or `writeOnly` flag; `$ref` entries are skipped. */
2450
- function collectPropertyKeysByFlag(schema, flag) {
2451
- if (!schema?.properties) return null;
2452
- const keys = [];
2453
- for (const key in schema.properties) {
2454
- const prop = schema.properties[key];
2455
- if (prop && !isReference(prop) && prop[flag]) keys.push(key);
2456
2573
  }
2457
- return keys.length ? keys : null;
2458
- }
2459
- /** Converts one parameter into a `ParameterNode`, naming an inline schema after the operation and the parameter. */
2460
- function parseParameter({ param, pointer, parentName, options, parseSchema, refs }) {
2461
- const schemaName = parentName && param.name ? (0, _kubb_core.pascalCase)(`${parentName} ${param.name}`) : void 0;
2462
- const contentType = param.schema ? void 0 : Object.keys(param.content ?? {})[0];
2463
- const mediaType = getMediaType({
2464
- content: param.content,
2465
- contentType,
2574
+ const { members: discriminatedAllOf, discriminantValues } = extractDiscriminatedAllOfMembers({
2575
+ allOfMembers: removeInheritedDiscriminator({
2576
+ members: schema.allOf,
2577
+ refs
2578
+ }),
2579
+ name,
2466
2580
  refs
2467
2581
  });
2468
- const rawSchema = param.schema ?? mediaType?.schema;
2469
- const parsed = rawSchema ? parseSchema({
2470
- schema: rawSchema,
2471
- name: schemaName
2472
- }) : _kubb_kit.ast.factory.createSchema({ type: options.unknownType });
2473
- const schema = parentName && param.name ? _kubb_kit.ast.macro.apply(parsed, [(0, _kubb_kit.macroEnumName)({
2474
- parentName,
2475
- propName: param.name,
2476
- enumSuffix: options.enumSuffix
2477
- })], { depth: "shallow" }) : parsed;
2478
- if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`);
2479
- return _kubb_kit.ast.factory.createParameter({
2480
- pointer,
2481
- name: param.name,
2482
- in: param.in,
2483
- schema: {
2484
- ...schema,
2485
- description: param.description ?? schema.description
2486
- },
2487
- required: param.required ?? false,
2488
- ...pickStyleFields(param),
2489
- ...contentType !== void 0 ? { contentType } : {},
2490
- ...mediaType?.encoding && { encoding: getEncodingFields({ encoding: mediaType.encoding }).encoding },
2491
- ...getExamples(mediaType ?? param, refs),
2492
- ...param.deprecated && { deprecated: true },
2493
- ...param.allowEmptyValue && { allowEmptyValue: true },
2494
- extensions: pickExtensions(param)
2582
+ const siblingProperties = collectSiblingProperties(schema.allOf, refs, schema.properties);
2583
+ const allOfMembers = discriminatedAllOf.map((s) => isReference(s) ? s : resolveUnionSchema(s, siblingProperties)).map((s) => parse({
2584
+ schema: s,
2585
+ name
2586
+ }));
2587
+ const syntheticStart = allOfMembers.length;
2588
+ if (Array.isArray(schema.required) && schema.required.length) {
2589
+ const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : /* @__PURE__ */ new Set();
2590
+ const missingRequired = schema.required.filter((key) => !outerKeys.has(key));
2591
+ if (missingRequired.length) {
2592
+ const resolvedMembers = schema.allOf.flatMap((item) => {
2593
+ if (!isReference(item)) return [item];
2594
+ const seen = /* @__PURE__ */ new Set();
2595
+ let deref = item;
2596
+ while (deref && isReference(deref) && !seen.has(deref.$ref)) {
2597
+ seen.add(deref.$ref);
2598
+ deref = refs.resolve(deref.$ref);
2599
+ }
2600
+ return deref && !isReference(deref) ? [deref] : [];
2601
+ });
2602
+ for (const key of missingRequired) for (const resolved of resolvedMembers) {
2603
+ const prop = resolved.properties?.[key];
2604
+ if (prop) {
2605
+ const memberSchema = {
2606
+ properties: { [key]: prop },
2607
+ required: [key]
2608
+ };
2609
+ allOfMembers.push(parse({
2610
+ schema: memberSchema,
2611
+ name
2612
+ }));
2613
+ break;
2614
+ }
2615
+ }
2616
+ }
2617
+ }
2618
+ if (keepsOwnKeywords(schema)) {
2619
+ const { allOf: _allOf, ...schemaWithoutAllOf } = schema;
2620
+ allOfMembers.push(parse({ schema: schemaWithoutAllOf }));
2621
+ }
2622
+ for (const { propertyName, values } of discriminantValues) allOfMembers.push(createDiscriminantNode({
2623
+ propertyName,
2624
+ values
2625
+ }));
2626
+ return createNode({
2627
+ schema,
2628
+ name,
2629
+ nullable,
2630
+ defaultValue
2631
+ }, {
2632
+ type: _kubb_kit.ast.schema.types.intersection,
2633
+ members: [...(0, _kubb_kit.mergeAdjacentObjectsLazy)(allOfMembers.slice(0, syntheticStart)), ...(0, _kubb_kit.mergeAdjacentObjectsLazy)(allOfMembers.slice(syntheticStart))]
2495
2634
  });
2496
2635
  }
2497
- function spreadQuerystring(param) {
2498
- if (param.in !== "querystring") return [param];
2499
- const schema = _kubb_kit.ast.ref.getSchema(param.schema);
2500
- const formEncoded = !param.contentType || _kubb_kit.ast.mediaType.getBase(param.contentType) === "application/x-www-form-urlencoded";
2501
- if (schema.type !== "object" || !formEncoded) return [param];
2502
- return schema.properties.map((property) => {
2503
- const { style, explode, allowReserved } = param.encoding?.[property.name] ?? {};
2504
- return _kubb_kit.ast.factory.createParameter({
2505
- ...param.pointer ? { pointer: param.pointer } : {},
2506
- name: property.name,
2507
- in: "query",
2508
- schema: property.schema,
2509
- required: param.required && property.required,
2510
- ...style !== void 0 && { style },
2511
- ...explode !== void 0 && { explode },
2512
- ...allowReserved !== void 0 && { allowReserved },
2513
- ...param.extensions && { extensions: param.extensions }
2514
- });
2636
+ const scalarTypes = /* @__PURE__ */ new Set([
2637
+ "string",
2638
+ "number",
2639
+ "integer",
2640
+ "boolean"
2641
+ ]);
2642
+ /**
2643
+ * Copies a scalar parent `type` and `format` onto inline members without a `type`. JSON Schema applies
2644
+ * sibling keywords to every member, so `type: 'integer', anyOf: [{ minimum: 10 }]` keeps each member an integer.
2645
+ */
2646
+ function inheritScalarType(members, { schema, type }) {
2647
+ if (!type || !scalarTypes.has(type)) return members;
2648
+ if (Array.isArray(schema.type) && schema.type.filter((t) => t !== "null").length > 1) return members;
2649
+ return members.map((member) => {
2650
+ if (!member || typeof member !== "object" || isReference(member) || member.type !== void 0) return member;
2651
+ const obj = member;
2652
+ return {
2653
+ type,
2654
+ ...schema.format !== void 0 && obj.format === void 0 && { format: schema.format },
2655
+ ...obj
2656
+ };
2515
2657
  });
2516
2658
  }
2517
2659
  /**
2518
- * Converts an OAS `Operation` into an `OperationNode`.
2660
+ * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.
2519
2661
  */
2520
- function parseOperation({ operation, ...ctx }) {
2521
- const { document, refs, contentType, options, parseSchema } = ctx;
2522
- const operationId = getOperationId(operation);
2523
- const operationName = operationId ? (0, _kubb_core.pascalCase)(operationId) : void 0;
2524
- const pointer = getOperationPointer(operation);
2525
- const parameters = getParameters({
2526
- operation,
2527
- refs
2528
- }).map((entry) => parseParameter({
2529
- options,
2530
- parseSchema,
2531
- refs,
2532
- ...entry,
2533
- parentName: operationName
2534
- })).flatMap(spreadQuerystring);
2535
- const body = getRequestBody({
2536
- operation,
2537
- refs
2538
- });
2539
- const bodyRequired = body?.required === true;
2540
- const requestBodyName = operationName ? `${operationName}Request` : void 0;
2541
- const content = (contentType ? [contentType] : Object.keys(body?.content ?? {})).flatMap((ct) => {
2542
- const schema = getBodySchema({
2543
- content: body?.content,
2544
- contentType: ct,
2545
- refs,
2546
- document
2662
+ function convertUnion(context) {
2663
+ if (context.schema.enum?.length) {
2664
+ const { enum: values, ...union } = context.schema;
2665
+ const nullable = context.nullable || [...union.oneOf ?? [], ...union.anyOf ?? []].some((member) => {
2666
+ const resolved = isReference(member) ? context.refs.resolve(member.$ref, { report: false }) : member;
2667
+ return !!resolved && !isReference(resolved) && isNullable(resolved, context.document);
2547
2668
  });
2548
- if (!schema) return [];
2549
- const mediaType = getMediaType({
2550
- content: body?.content,
2551
- contentType: ct,
2552
- refs
2669
+ const enumSchema = {
2670
+ type: union.type,
2671
+ enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values
2672
+ };
2673
+ const members = [convertUnion({
2674
+ ...context,
2675
+ schema: union
2676
+ }), context.parse({ schema: enumSchema })];
2677
+ return createNode(context, {
2678
+ type: _kubb_kit.ast.schema.types.intersection,
2679
+ members
2553
2680
  });
2554
- const node = _kubb_kit.ast.schema.applyOptionality(parseSchema({
2555
- schema,
2556
- name: requestBodyName
2557
- }), bodyRequired);
2558
- scanSchema(node, `${mediaTypePointer(body?.content, ct, `${pointer}/requestBody/content/${escapePointerToken(ct)}`)}/${schemaKeyword(mediaType)}`);
2559
- return [_kubb_kit.ast.factory.createContent({
2560
- contentType: ct,
2561
- schema: node,
2562
- keysToOmit: collectPropertyKeysByFlag(schema, "readOnly"),
2563
- ...mediaType && getEncodingFields(mediaType),
2564
- ...mediaType && getExamples(mediaType, refs),
2565
- ...getStreamField({
2566
- contentType: ct,
2567
- mediaType,
2568
- refs,
2569
- document,
2570
- node
2681
+ }
2682
+ const annotatedEnum = convertAnnotatedEnum(context);
2683
+ if (annotatedEnum) return annotatedEnum;
2684
+ const { schema, name, nullable, defaultValue, parse, refs } = context;
2685
+ const ctx = {
2686
+ schema,
2687
+ name,
2688
+ nullable,
2689
+ defaultValue
2690
+ };
2691
+ const discriminator = isDiscriminator(schema) ? schema.discriminator : void 0;
2692
+ const declaredMembers = [...schema.oneOf ?? [], ...schema.anyOf ?? []];
2693
+ const defaultRef = getDefaultMappingRef(typeof schema.discriminator === "object" ? schema.discriminator : void 0);
2694
+ const unionMembers = resolveUnionMembers(inheritScalarType(defaultRef && !declaredMembers.some((member) => isReference(member) && member.$ref === defaultRef) ? [...declaredMembers, { $ref: defaultRef }] : declaredMembers, context), schema.properties ?? {});
2695
+ const strategy = schema.oneOf ? "one" : "any";
2696
+ const explicitDiscriminatorPropertyName = discriminator?.propertyName;
2697
+ const { oneOf: _o, anyOf: _a, discriminator: _d, ...memberBaseSchema } = schema;
2698
+ const sharedPropertiesNode = schema.properties ? parse({
2699
+ schema: memberBaseSchema,
2700
+ name
2701
+ }) : void 0;
2702
+ const missingRequired = (Array.isArray(schema.required) ? schema.required : []).filter((key) => !Object.hasOwn(schema.properties ?? {}, key));
2703
+ if (sharedPropertiesNode || discriminator || missingRequired.length) {
2704
+ const members = narrowUnionMembers({
2705
+ unionMembers,
2706
+ discriminator,
2707
+ sharedPropertiesNode,
2708
+ parentType: discriminator && propertyTypeOf({
2709
+ schema,
2710
+ propertyName: discriminator.propertyName,
2711
+ refs
2571
2712
  }),
2572
- extensions: pickExtensions(mediaType)
2573
- })];
2574
- });
2575
- const requestBody = content.length > 0 || body?.description ? {
2576
- pointer: `${pointer}/requestBody`,
2577
- description: body?.description,
2578
- required: bodyRequired || void 0,
2579
- content: content.length > 0 ? content : void 0,
2580
- extensions: pickExtensions(body)
2581
- } : void 0;
2582
- const responses = getResponseStatusCodes(operation).map((key) => {
2583
- const response = getResponseByStatusCode({
2584
- operation,
2585
- refs,
2586
- statusCode: key
2713
+ parse,
2714
+ name,
2715
+ refs
2587
2716
  });
2588
- const statusCode = key.toLowerCase();
2589
- const responseName = operationName ? `${operationName}Status${statusCode}` : void 0;
2590
- const parseEntrySchema = (ct) => {
2591
- const raw = getBodySchema({
2592
- content: response?.content,
2593
- contentType: ct,
2594
- refs,
2595
- document
2596
- });
2597
- const mediaType = getMediaType({
2598
- content: response?.content,
2599
- contentType: ct,
2600
- refs
2601
- });
2602
- const node = raw && Object.keys(raw).length > 0 ? parseSchema({
2603
- schema: raw,
2604
- name: responseName
2605
- }) : _kubb_kit.ast.factory.createSchema({ type: options.emptySchemaType });
2606
- if (raw && ct) scanSchema(node, `${mediaTypePointer(response?.content, ct, `${pointer}/responses/${key}/content/${escapePointerToken(ct)}`)}/${schemaKeyword(mediaType)}`);
2607
- return {
2608
- schema: node,
2609
- keysToOmit: collectPropertyKeysByFlag(raw, "writeOnly"),
2610
- ...mediaType && getEncodingFields(mediaType),
2611
- ...mediaType && getExamples(mediaType, refs),
2612
- ...ct ? getStreamField({
2613
- contentType: ct,
2614
- mediaType,
2615
- refs,
2616
- document,
2617
- node
2618
- }) : {},
2619
- extensions: pickExtensions(mediaType)
2620
- };
2621
- };
2622
- const declaredContentTypes = Object.keys(response?.content ?? {});
2623
- const responseContent = (contentType && declaredContentTypes.length ? [contentType] : declaredContentTypes).map((ct) => _kubb_kit.ast.factory.createContent({
2624
- contentType: ct,
2625
- ...parseEntrySchema(ct)
2717
+ const unionNode = createNode(ctx, {
2718
+ type: _kubb_kit.ast.schema.types.union,
2719
+ strategy,
2720
+ members,
2721
+ discriminatorPropertyName: explicitDiscriminatorPropertyName ?? _kubb_kit.ast.schema.inferDiscriminator(members)
2722
+ });
2723
+ const requiredProperties = missingRequired.map((name) => _kubb_kit.ast.factory.createProperty({
2724
+ name,
2725
+ required: true,
2726
+ schema: _kubb_kit.ast.factory.createSchema({ type: _kubb_kit.ast.schema.types.unknown })
2626
2727
  }));
2627
- if (responseContent.length === 0) responseContent.push(_kubb_kit.ast.factory.createContent({
2628
- contentType: "",
2629
- ...parseEntrySchema(contentType)
2728
+ const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : [];
2729
+ if (requiredProperties.length) siblings.push(_kubb_kit.ast.factory.createSchema({
2730
+ type: _kubb_kit.ast.schema.types.object,
2731
+ properties: requiredProperties
2630
2732
  }));
2631
- const responsePointer = `${pointer}/responses/${key}`;
2632
- const headers = Object.entries(response?.headers ?? {}).flatMap(([name, value]) => {
2633
- const header = name.toLowerCase() === "content-type" ? null : refs.deref(value);
2634
- if (!header) return [];
2635
- return [parseParameter({
2636
- param: {
2637
- ...header,
2638
- name,
2639
- in: "header"
2640
- },
2641
- pointer: `${responsePointer}/headers/${escapePointerToken(name)}`,
2642
- parentName: responseName,
2643
- options,
2644
- parseSchema,
2645
- refs
2646
- })];
2647
- });
2648
- const links = getLinks(response?.links, refs);
2649
- return _kubb_kit.ast.factory.createResponse({
2650
- pointer: responsePointer,
2651
- statusCode,
2652
- summary: response?.summary,
2653
- description: response?.description,
2654
- content: responseContent,
2655
- ...headers.length && { headers },
2656
- ...links && { links },
2657
- extensions: pickExtensions(response)
2733
+ if (!siblings.length) return unionNode;
2734
+ return createNode(ctx, {
2735
+ type: _kubb_kit.ast.schema.types.intersection,
2736
+ members: [unionNode, ...siblings]
2658
2737
  });
2738
+ }
2739
+ const members = unionMembers.map((s) => parse({
2740
+ schema: s,
2741
+ name
2742
+ }));
2743
+ const unionNode = createNode(ctx, {
2744
+ type: _kubb_kit.ast.schema.types.union,
2745
+ strategy,
2746
+ members,
2747
+ discriminatorPropertyName: explicitDiscriminatorPropertyName ?? _kubb_kit.ast.schema.inferDiscriminator(members)
2659
2748
  });
2660
- const pickDoc = (key) => {
2661
- const own = operation.schema[key];
2662
- if (typeof own === "string") return own;
2663
- const fallback = operation.pathItem[key];
2664
- return typeof fallback === "string" ? fallback : void 0;
2665
- };
2666
- const servers = operation.schema.servers?.length ? operation.schema.servers : operation.pathItem.servers;
2667
- const auth = toAuthRequirements(operation.schema.security ?? document.security, document);
2668
- return _kubb_kit.ast.factory.createOperation({
2669
- pointer,
2670
- operationId,
2671
- protocol: "http",
2672
- method: SUPPORTED_METHODS.has(operation.method) ? operation.method.toUpperCase() : operation.method,
2673
- path: operation.path,
2674
- tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],
2675
- summary: pickDoc("summary") || void 0,
2676
- description: pickDoc("description") || void 0,
2677
- deprecated: operation.schema.deprecated || void 0,
2678
- externalDocs: getExternalDocs(operation.schema.externalDocs),
2679
- parameters,
2680
- requestBody,
2681
- responses,
2682
- extensions: pickExtensions(operation.schema),
2683
- ...servers && { servers: toInputServers(servers) },
2684
- ...auth && { auth }
2749
+ return _kubb_kit.ast.macro.apply(unionNode, [_kubb_kit.macroDedupeUnion], { depth: "shallow" });
2750
+ }
2751
+ /**
2752
+ * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.
2753
+ * Only called once the multi-type rule's `match` has confirmed more than one non-`null` type
2754
+ * remains; a single remaining type (e.g. `['string', 'null']`) is handled as that type instead,
2755
+ * with nullability already folded in.
2756
+ */
2757
+ function convertMultiType({ schema, name, nullable, defaultValue, parse }) {
2758
+ const nonNullTypes = schema.type.filter((t) => t !== "null");
2759
+ return createNode({
2760
+ schema,
2761
+ name,
2762
+ nullable,
2763
+ defaultValue
2764
+ }, {
2765
+ type: _kubb_kit.ast.schema.types.union,
2766
+ members: nonNullTypes.map((t) => {
2767
+ return parse({
2768
+ schema: {
2769
+ ...Object.fromEntries(Object.entries(schema).filter(([key]) => !key.startsWith("x-"))),
2770
+ type: t
2771
+ },
2772
+ name
2773
+ });
2774
+ })
2685
2775
  });
2686
2776
  }
2687
- /** Renames path parameters and their `{placeholder}` to the camelCase names from {@link Url.toParamNames}. */
2688
- function camelCasePathParams(node) {
2689
- if (!node.path || node.parameters.some((param) => param.in === "path" && param.style === "matrix")) return node;
2690
- const names = _kubb_kit.Url.toParamNames(node.path);
2691
- return {
2692
- ...node,
2693
- path: node.path.replace(/\{([^}]+)\}/g, (_match, name) => `{${names.get(name) ?? name}}`),
2694
- parameters: node.parameters.map((param) => param.in === "path" && names.has(param.name) ? {
2695
- ...param,
2696
- name: names.get(param.name)
2697
- } : param)
2698
- };
2777
+ // src/schemaDiagnostics.ts
2778
+ /**
2779
+ * Links one freshly converted schema and its nested schemas to their RFC 6901 pointers
2780
+ * (`#/components/schemas/Pet/properties/owner/properties/name`), and reports the advisory
2781
+ * diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`, `KUBB_DUPLICATE_DISCRIMINATOR`) against them.
2782
+ * Refs are not followed, so the resolved schema is handled under its own walk.
2783
+ * Reports land in the active build run, are a no-op outside one, and repeats are deduped by the build.
2784
+ */
2785
+ function scanSchema(node, pointer = node.pointer) {
2786
+ if (pointer) visit(node, pointer);
2699
2787
  }
2700
- // src/emit/createNode.ts
2788
+ var FormatTally = class {
2789
+ #pointers;
2790
+ group(fn) {
2791
+ this.#pointers = memo.create();
2792
+ try {
2793
+ return fn();
2794
+ } finally {
2795
+ const tally = this.#pointers;
2796
+ this.#pointers = void 0;
2797
+ for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers]);
2798
+ }
2799
+ }
2800
+ add(format, pointer) {
2801
+ if (!this.#pointers) return reportUnsupportedFormat(format, [pointer]);
2802
+ memo(this.#pointers, format, () => /* @__PURE__ */ new Set()).add(pointer);
2803
+ }
2804
+ };
2805
+ const formatTally = new FormatTally();
2701
2806
  /**
2702
- * Builds a schema node from a converter's base context plus its type-specific fields. Every
2703
- * converter needs the same metadata fields (`title`, `description`, `examples`, ...) alongside
2704
- * whatever makes its node distinct; this folds both into one call.
2807
+ * Runs `fn` and reports `KUBB_UNSUPPORTED_FORMAT` once per format with the number of schemas that use it,
2808
+ * instead of once per schema. `format` is an open value in OpenAPI, so a large spec would otherwise print
2809
+ * thousands of warnings that say the same thing. `fn` must be synchronous.
2705
2810
  */
2706
- function createNode({ schema, name, nullable, defaultValue }, extras) {
2707
- return _kubb_kit.ast.factory.createSchema({
2708
- name,
2709
- nullable,
2710
- title: schema.title,
2711
- description: schema.description,
2712
- deprecated: schema.deprecated,
2713
- readOnly: schema.readOnly,
2714
- writeOnly: schema.writeOnly,
2715
- default: defaultValue,
2716
- examples: extractExamples(schema),
2717
- format: schema.format,
2718
- externalDocs: getExternalDocs(schema.externalDocs),
2719
- extensions: pickExtensions(schema),
2720
- ...extras
2811
+ function groupUnsupportedFormats(fn) {
2812
+ return formatTally.group(fn);
2813
+ }
2814
+ function reportUnsupportedFormat(format, pointers) {
2815
+ const count = pointers.length;
2816
+ _kubb_kit.Diagnostics.report({
2817
+ code: _kubb_kit.Diagnostics.code.unsupportedFormat,
2818
+ severity: "warning",
2819
+ message: count === 1 ? `Kubb does not map the format "${format}" to a specific type, so it falls back to the base type.` : `Kubb does not map the format "${format}" to a specific type, so ${count} schemas fall back to the base type.`,
2820
+ help: `Use a format Kubb supports, or handle "${format}" with a custom parser or plugin.`,
2821
+ location: {
2822
+ kind: "schema",
2823
+ pointer: pointers[0]
2824
+ }
2721
2825
  });
2722
2826
  }
2723
- // src/emit/discriminator/preserve.ts
2827
+ function visit(node, pointer) {
2828
+ node.pointer ??= pointer;
2829
+ if (node.deprecated) _kubb_kit.Diagnostics.report({
2830
+ code: _kubb_kit.Diagnostics.code.deprecated,
2831
+ severity: "info",
2832
+ message: "This schema is marked as deprecated.",
2833
+ location: {
2834
+ kind: "schema",
2835
+ pointer
2836
+ }
2837
+ });
2838
+ if (typeof node.format === "string" && !isHandledFormat(node.format)) formatTally.add(node.format, pointer);
2839
+ if (node.type === "object") {
2840
+ for (const property of node.properties) visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`);
2841
+ if (node.additionalProperties && typeof node.additionalProperties === "object") visit(node.additionalProperties, `${pointer}/additionalProperties`);
2842
+ return;
2843
+ }
2844
+ if (node.type === "array") {
2845
+ for (const item of node.items ?? []) visit(item, `${pointer}/items`);
2846
+ return;
2847
+ }
2848
+ if (node.type === "tuple") {
2849
+ for (const [index, item] of (node.items ?? []).entries()) visit(item, `${pointer}/items/${index}`);
2850
+ return;
2851
+ }
2852
+ if (node.type === "not") {
2853
+ for (const member of node.members ?? []) visit(member, `${pointer}/not`);
2854
+ return;
2855
+ }
2856
+ if (node.type === "union" && node.discriminatorPropertyName) reportDuplicateDiscriminators(node, node.discriminatorPropertyName, pointer);
2857
+ if (node.type === "union" || node.type === "intersection") {
2858
+ const keyword = node.type === "intersection" ? "allOf" : node.strategy === "any" ? "anyOf" : "oneOf";
2859
+ for (const [index, member] of (node.members ?? []).entries()) visit(member, `${pointer}/${keyword}/${index}`);
2860
+ }
2861
+ }
2724
2862
  /**
2725
- * Turns string mapping keys into the discriminator property's type when they parse cleanly.
2863
+ * Reports a declared discriminator whose value pins more than one member. The spec cannot tell
2864
+ * those members apart, and Zod's `z.discriminatedUnion` throws on the first parse.
2865
+ * One diagnostic per union, since the build dedupes by code and pointer.
2726
2866
  */
2727
- function typedKeys({ keys, propertyType }) {
2728
- return keys.map((key) => {
2729
- if (propertyType === "integer" || propertyType === "number") {
2730
- const value = Number(key);
2731
- return key.trim() !== "" && Number.isFinite(value) ? value : key;
2732
- }
2733
- if (propertyType === "boolean") {
2734
- const lower = key.toLowerCase();
2735
- return lower === "true" ? true : lower === "false" ? false : key;
2867
+ function reportDuplicateDiscriminators(node, propertyName, pointer) {
2868
+ const keyword = node.strategy === "any" ? "anyOf" : "oneOf";
2869
+ const membersByValue = memo.create();
2870
+ for (const [index, member] of (node.members ?? []).entries()) {
2871
+ const label = memberName(member) ?? `${keyword}/${index}`;
2872
+ for (const value of memberValues(member, propertyName)) memo(membersByValue, value, () => []).push(label);
2873
+ }
2874
+ const duplicates = [...membersByValue].filter(([, members]) => members.length > 1);
2875
+ if (!duplicates.length) return;
2876
+ _kubb_kit.Diagnostics.report({
2877
+ code: _kubb_kit.Diagnostics.code.duplicateDiscriminator,
2878
+ severity: "warning",
2879
+ message: duplicates.map(([value, members]) => `Discriminator "${propertyName}" value ${JSON.stringify(value)} matches more than one member (${members.join(", ")}).`).join(" "),
2880
+ help: `Give each member its own "${propertyName}" value, or drop the discriminator. Zod's z.discriminatedUnion throws on the first parse of this union.`,
2881
+ location: {
2882
+ kind: "schema",
2883
+ pointer
2736
2884
  }
2737
- return key;
2738
2885
  });
2739
2886
  }
2887
+ function memberValues(node, propertyName, seen = /* @__PURE__ */ new Set()) {
2888
+ if (seen.has(node)) return [];
2889
+ seen.add(node);
2890
+ const target = node.type === "ref" && node.schema ? node.schema : node;
2891
+ if (target.type === "union") return [...new Set(target.members?.flatMap((member) => memberValues(member, propertyName, seen)))];
2892
+ return intersect(_kubb_kit.ast.schema.findProperties({
2893
+ node,
2894
+ propertyName
2895
+ }).map((property) => [..._kubb_kit.ast.schema.getLiterals(property.schema)]));
2896
+ }
2897
+ function intersect(slices) {
2898
+ const pinned = slices.filter((values) => values.length > 0);
2899
+ return pinned.reduce((acc, values) => acc.filter((value) => values.includes(value)), pinned[0] ?? []);
2900
+ }
2901
+ function memberName(member) {
2902
+ if (member.type === "ref") return member.name ?? void 0;
2903
+ if (member.type === "intersection") return member.members?.map(memberName).find(Boolean);
2904
+ }
2905
+ // src/model/mediaType.ts
2906
+ const streamMediaTypes = /* @__PURE__ */ new Set([
2907
+ "application/jsonl",
2908
+ "application/x-ndjson",
2909
+ "application/json-seq",
2910
+ "text/event-stream"
2911
+ ]);
2740
2912
  /**
2741
- * Reads the declared `type` of `propertyName` on a schema, following `$ref`s and `allOf` members.
2742
- * A nullable array such as `['integer', 'null']` reads as its one non-null type.
2913
+ * Returns `true` for a media type read as a stream of items: SSE, JSON Lines, a `+json-seq` sequence, or any media type that declares `itemSchema`.
2743
2914
  */
2744
- function propertyTypeOf({ schema, propertyName, refs, seen = /* @__PURE__ */ new Set() }) {
2745
- const deref = (value) => value && isReference(value) ? refs.resolve(value.$ref, { report: false }) : value;
2746
- if (schema && isReference(schema)) {
2747
- if (seen.has(schema.$ref)) return void 0;
2748
- seen.add(schema.$ref);
2749
- }
2750
- const resolved = deref(schema);
2751
- const type = deref(resolved?.properties?.[propertyName])?.type ?? resolved?.allOf?.map((member) => propertyTypeOf({
2752
- schema: member,
2753
- propertyName,
2754
- refs,
2755
- seen
2756
- })).find(Boolean);
2757
- const nonNull = Array.isArray(type) ? type.filter((t) => t !== "null") : [];
2758
- return nonNull.length === 1 ? nonNull[0] : type;
2915
+ function isStream(contentType, mediaType) {
2916
+ const baseType = _kubb_kit.ast.mediaType.getBase(contentType);
2917
+ return streamMediaTypes.has(baseType) || baseType.startsWith("application/") && baseType.endsWith("+json-seq") || mediaType?.itemSchema !== void 0;
2759
2918
  }
2760
2919
  /**
2761
- * Creates a single-property object schema used as a discriminator literal.
2762
- *
2763
- * @example
2764
- * ```ts
2765
- * createDiscriminantNode({ propertyName: 'type', values: ['dog'] })
2766
- * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }
2767
- * ```
2920
+ * Whether the media type is `text/event-stream`, with or without parameters.
2768
2921
  */
2769
- function createDiscriminantNode({ propertyName, values }) {
2770
- return _kubb_kit.ast.factory.createSchema({
2771
- type: "object",
2772
- primitive: "object",
2773
- properties: [_kubb_kit.ast.factory.createProperty({
2774
- name: propertyName,
2775
- schema: _kubb_kit.ast.factory.createSchema({
2776
- type: "enum",
2777
- primitive: (0, _kubb_kit.enumPrimitive)(values),
2778
- enumValues: values
2779
- }),
2780
- required: true
2781
- })]
2782
- });
2922
+ function isEventStream(contentType) {
2923
+ return _kubb_kit.ast.mediaType.getBase(contentType) === "text/event-stream";
2783
2924
  }
2784
2925
  /**
2785
- * Returns the `$ref` of an OpenAPI 3.2 `defaultMapping`, written as a schema name or a `$ref`; `undefined` when none.
2926
+ * Replaces a `data` string that holds JSON with its `contentSchema`, so the event reads as parsed.
2786
2927
  */
2787
- function getDefaultMappingRef(discriminator) {
2788
- const value = discriminator?.defaultMapping;
2789
- if (!value) return void 0;
2790
- return value.includes("/") ? value : `${SCHEMA_REF_PREFIX}${value}`;
2928
+ function withParsedData(schema, refs) {
2929
+ const data = schema.properties?.data;
2930
+ const resolved = data && isReference(data) ? refs.resolve(data.$ref, { report: false }) : data;
2931
+ if (!resolved?.contentSchema || !resolved.contentMediaType || !isJsonMimeType(resolved.contentMediaType)) return schema;
2932
+ return {
2933
+ ...schema,
2934
+ properties: {
2935
+ ...schema.properties,
2936
+ data: resolved.contentSchema
2937
+ }
2938
+ };
2791
2939
  }
2792
2940
  /**
2793
- * Returns every discriminator key whose mapping value matches `ref`, in mapping order.
2794
- *
2795
- * A mapping may point several keys at the same schema, in which case the member has to be
2796
- * narrowed to all of them — keeping only the first would drop the rest from the union.
2797
- *
2798
- * @example
2799
- * ```ts
2800
- * findDiscriminators({ mapping: { dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, ref: '#/components/schemas/Dog' }) // ['dog', 'hound']
2801
- * ```
2941
+ * Inlines a `$ref` event whose JSON `data` string needs its `contentSchema`, so the shared component keeps `data` as a string elsewhere.
2802
2942
  */
2803
- function findDiscriminators({ mapping, ref }) {
2804
- if (!mapping || !ref) return [];
2805
- return Object.entries(mapping).filter(([, value]) => value === ref).map(([key]) => key);
2943
+ function withParsedRef(schema, refs) {
2944
+ const resolved = refs.resolve(schema.$ref, { report: false });
2945
+ if (!resolved || isReference(resolved)) return schema;
2946
+ const parsed = withParsedData(resolved, refs);
2947
+ return parsed === resolved ? schema : parsed;
2806
2948
  }
2807
2949
  /**
2808
- * Finds the discriminator a schema declares itself or through an inline `allOf` member.
2950
+ * Keywords next to `$ref` that only annotate it, so a reference that carries nothing else stays a reference.
2951
+ */
2952
+ const REF_ANNOTATIONS = /* @__PURE__ */ new Set([
2953
+ "$ref",
2954
+ "summary",
2955
+ "description",
2956
+ "$comment"
2957
+ ]);
2958
+ /**
2959
+ * Applies `extra` on top of `base` the way JSON Schema does: `properties` and `required` add up, other keywords of `extra` win.
2960
+ */
2961
+ function mergeSchemas(base, extra) {
2962
+ const required = [.../* @__PURE__ */ new Set([...Array.isArray(base.required) ? base.required : [], ...Array.isArray(extra.required) ? extra.required : []])];
2963
+ return {
2964
+ type: "object",
2965
+ ...base,
2966
+ ...extra,
2967
+ properties: {
2968
+ ...base.properties,
2969
+ ...extra.properties
2970
+ },
2971
+ ...required.length ? { required } : {}
2972
+ };
2973
+ }
2974
+ /**
2975
+ * Normalizes the OpenAPI 3.2 `text/event-stream` item schema into one schema per event.
2976
+ * - Keywords next to a `$ref` apply to the referenced schema.
2977
+ * - Shared `properties` merge into each inline `oneOf`/`anyOf` member.
2978
+ * - A JSON `data` string becomes its `contentSchema`.
2809
2979
  */
2810
- function getDiscriminator(schema) {
2811
- return (isDiscriminator(schema) ? schema : schema.allOf?.find(isDiscriminator))?.discriminator;
2980
+ function toEventSchema(schema, refs) {
2981
+ if (isReference(schema)) {
2982
+ const siblings = Object.fromEntries(Object.entries(schema).filter(([key]) => !REF_ANNOTATIONS.has(key)));
2983
+ const resolved = Object.keys(siblings).length ? refs.resolve(schema.$ref, { report: false }) : null;
2984
+ return resolved ? toEventSchema(mergeSchemas(resolved, siblings), refs) : withParsedRef(schema, refs);
2985
+ }
2986
+ const key = schema.oneOf?.length ? "oneOf" : schema.anyOf?.length ? "anyOf" : void 0;
2987
+ if (!key) return withParsedData(schema, refs);
2988
+ const members = schema[key];
2989
+ const { properties, required, ...rest } = schema;
2990
+ const merge = !!properties && !members.some(isReference);
2991
+ const shared = {
2992
+ properties,
2993
+ required
2994
+ };
2995
+ return {
2996
+ ...merge ? rest : schema,
2997
+ [key]: members.map((member) => isReference(member) ? withParsedRef(member, refs) : withParsedData(merge ? mergeSchemas(shared, member) : member, refs))
2998
+ };
2812
2999
  }
3000
+ const SSE_FIELDS = /* @__PURE__ */ new Set([
3001
+ "event",
3002
+ "id",
3003
+ "retry",
3004
+ "data"
3005
+ ]);
2813
3006
  /**
2814
- * Lists the mapping keys of a discriminator plus the keys of the nested discriminators its mapped
2815
- * schemas declare on the same property, so a root `$type` accepts values from every level.
3007
+ * Property names of the schema and its `allOf` members, following `$ref`s, as one combined object declares them.
2816
3008
  */
2817
- function getMappingKeys({ discriminator: { propertyName, mapping }, refs, seen = /* @__PURE__ */ new Set() }) {
2818
- return Object.entries(mapping ?? {}).flatMap(([key, target]) => {
2819
- if (seen.has(target)) return [key];
2820
- seen.add(target);
2821
- const resolved = refs.resolve(target, { report: false });
2822
- const nested = resolved && getDiscriminator(resolved);
2823
- return nested?.propertyName === propertyName ? [key, ...getMappingKeys({
2824
- discriminator: nested,
2825
- refs,
2826
- seen
2827
- })] : [key];
2828
- });
3009
+ function collectFields(schema, refs, seen) {
3010
+ if (isReference(schema)) {
3011
+ if (seen.has(schema.$ref)) return [];
3012
+ seen.add(schema.$ref);
3013
+ const resolved = refs.resolve(schema.$ref, { report: false });
3014
+ return resolved ? collectFields(resolved, refs, seen) : [];
3015
+ }
3016
+ const members = schema.allOf ?? [];
3017
+ return [...Object.keys(schema.properties ?? {}), ...members.flatMap((member) => collectFields(member, refs, seen))];
2829
3018
  }
2830
3019
  /**
2831
- * Drops the discriminator from an inline `allOf` member when a `$ref` sibling already declares one on
2832
- * the same property. That mapping names the schema's own children, and keeping it pins the property
2833
- * to those keys next to the parent's, which leaves `never`.
3020
+ * Whether the schema, following `$ref`s, or a `oneOf`/`anyOf` member of it is a whole Server-Sent Event: its combined
3021
+ * `allOf` fields declare `data`, or `event` with no field an event cannot carry. An `event` next to fields such as
3022
+ * `planet` is the payload's own property, sent as JSON in the `data:` line.
2834
3023
  */
2835
- function removeInheritedDiscriminator({ members, refs }) {
2836
- const inherited = new Set(members.flatMap((member) => {
2837
- const parent = isReference(member) ? refs.resolve(member.$ref, { report: false }) : null;
2838
- return parent && getDiscriminator(parent)?.propertyName || [];
2839
- }));
2840
- return members.map((member) => {
2841
- if (isReference(member) || !isDiscriminator(member) || member.oneOf || member.anyOf) return member;
2842
- if (!inherited.has(member.discriminator.propertyName)) return member;
2843
- const { discriminator: _discriminator, ...rest } = member;
2844
- return rest;
2845
- });
3024
+ function declaresEventFields(schema, refs, seen) {
3025
+ if (isReference(schema)) {
3026
+ if (seen.has(schema.$ref)) return false;
3027
+ seen.add(schema.$ref);
3028
+ const resolved = refs.resolve(schema.$ref, { report: false });
3029
+ return !!resolved && declaresEventFields(resolved, refs, seen);
3030
+ }
3031
+ const fields = collectFields(schema, refs, new Set(seen));
3032
+ if (fields.includes("data")) return true;
3033
+ if (fields.includes("event")) return fields.every((field) => SSE_FIELDS.has(field));
3034
+ return [...schema.oneOf ?? [], ...schema.anyOf ?? []].some((member) => declaresEventFields(member, refs, seen));
2846
3035
  }
2847
3036
  /**
2848
- * Whether a member can carry the discriminator property. A discriminator is only a hint, so an array
2849
- * or primitive member keeps its own type instead of an intersection no value can satisfy.
3037
+ * Returns `'event'` when the item is a whole event, directly or in a composition member (see `declaresEventFields`), else `'data'`.
2850
3038
  */
2851
- function isObjectLike(member, refs) {
2852
- const type = (isReference(member) ? refs.resolve(member.$ref, { report: false }) : member)?.type;
2853
- if (type === void 0) return true;
2854
- return Array.isArray(type) ? type.includes("object") : type === "object";
3039
+ function getItemShape(schema, refs) {
3040
+ return declaresEventFields(schema, refs, /* @__PURE__ */ new Set()) ? "event" : "data";
2855
3041
  }
2856
3042
  /**
2857
- * Narrows each `oneOf`/`anyOf` member with its discriminant value, intersecting the member's own
2858
- * node with either the shared-properties slice carrying that value, or a synthetic discriminant
2859
- * literal. The referenced child schema's own definition is left untouched — narrowing happens only
2860
- * at this union usage site, which is what makes this mode "preserve" (as opposed to `propagate`,
2861
- * which additionally patches the child schema's own definition in a post-pass).
3043
+ * Returns the raw item schema: `itemSchema`, or `schema` on `text/event-stream` as 3.0 and 3.1 documents write one event.
2862
3044
  */
2863
- function narrowUnionMembers({ unionMembers, discriminator, sharedPropertiesNode, parentType, parse, name, refs }) {
2864
- function pickDiscriminatorPropertyNode(node, propertyName) {
2865
- const discriminatorProperty = _kubb_kit.ast.schema.narrow(node, "object")?.properties?.find((property) => property.name === propertyName);
2866
- if (!discriminatorProperty) return null;
2867
- return _kubb_kit.ast.factory.createSchema({
2868
- type: "object",
2869
- primitive: "object",
2870
- properties: [discriminatorProperty]
2871
- });
2872
- }
2873
- function implicitDiscriminantValue(member) {
2874
- if (!discriminator || discriminator.mapping || !isReference(member)) return null;
2875
- const value = _kubb_kit.ast.ref.getName(member.$ref);
2876
- if (!value) return null;
2877
- const variant = refs.resolve(member.$ref, { report: false });
2878
- if (!variant) return null;
2879
- const propertyName = discriminator.propertyName;
2880
- const seen = /* @__PURE__ */ new Set([member.$ref]);
2881
- /** Whether the variant, or a schema it composes, pins the discriminator property to literal values. */
2882
- function constrains(v) {
2883
- const prop = v.properties?.[propertyName];
2884
- const resolved = prop && isReference(prop) ? refs.resolve(prop.$ref, { report: false }) : prop;
2885
- const pins = (candidate) => Array.isArray(candidate.enum) || candidate.const !== void 0;
2886
- const members = (resolved?.anyOf ?? resolved?.oneOf ?? []).filter((member) => member.type !== "null");
2887
- if (resolved && (pins(resolved) || members.length > 0 && members.every(pins))) return true;
2888
- const composition = v.allOf ?? v.oneOf ?? v.anyOf;
2889
- if (!composition) return false;
2890
- return composition.some((m) => {
2891
- if (!isReference(m)) return constrains(m);
2892
- if (seen.has(m.$ref)) return false;
2893
- seen.add(m.$ref);
2894
- const r = refs.resolve(m.$ref, { report: false });
2895
- return r ? constrains(r) : false;
2896
- });
2897
- }
2898
- return constrains(variant) ? null : value;
2899
- }
2900
- const defaultRef = getDefaultMappingRef(discriminator);
2901
- return unionMembers.map((s) => {
2902
- const ref = isReference(s) ? s.$ref : void 0;
2903
- const isDefault = ref !== void 0 && ref === defaultRef;
2904
- const mappedValues = isDefault ? [] : findDiscriminators({
2905
- mapping: discriminator?.mapping,
2906
- ref
2907
- });
2908
- const implicitValue = mappedValues.length || isDefault ? null : implicitDiscriminantValue(s);
2909
- const propertyType = propertyTypeOf({
2910
- schema: s,
2911
- propertyName: discriminator?.propertyName ?? "",
2912
- refs
2913
- }) ?? parentType;
2914
- const discriminatorValues = typedKeys({
2915
- keys: mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : [],
2916
- propertyType
2917
- });
2918
- const memberNode = parse({
2919
- schema: s,
2920
- name
2921
- });
2922
- if (!discriminatorValues.length || !discriminator || !isObjectLike(s, refs)) return memberNode;
2923
- const narrowedDiscriminatorNode = sharedPropertiesNode ? pickDiscriminatorPropertyNode(_kubb_kit.ast.macro.apply(sharedPropertiesNode, [(0, _kubb_kit.macroDiscriminatorEnum)({
2924
- propertyName: discriminator.propertyName,
2925
- values: discriminatorValues
2926
- })], { depth: "shallow" }), discriminator.propertyName) : void 0;
2927
- return _kubb_kit.ast.factory.createSchema({
2928
- type: "intersection",
2929
- members: [memberNode, narrowedDiscriminatorNode ?? createDiscriminantNode({
2930
- propertyName: discriminator.propertyName,
2931
- values: discriminatorValues
2932
- })]
2933
- });
2934
- });
3045
+ function getItemSchema({ contentType, mediaType, refs, document }) {
3046
+ if (!mediaType || !isStream(contentType, mediaType)) return null;
3047
+ const raw = mediaType.itemSchema ?? (isEventStream(contentType) && !isOpenApi32(document) ? mediaType.schema : void 0);
3048
+ if (!raw) return null;
3049
+ return isEventStream(contentType) ? toEventSchema(raw, refs) : raw;
2935
3050
  }
2936
- /**
2937
- * Filters the discriminated members out of an `allOf` list: an `allOf` member that `$ref`s a
2938
- * discriminated union's parent, where this schema is itself one of that union's children, is
2939
- * dropped from `members` and its discriminant value collected instead — the same synthetic
2940
- * literal `narrowUnionMembers` produces, so the emitted node stays a plain intersection rather
2941
- * than nesting the whole parent union one level deeper.
2942
- */
2943
- function extractDiscriminatedAllOfMembers({ allOfMembers, name, refs }) {
2944
- const discriminantValues = [];
3051
+ // src/model/content.ts
3052
+ const PARAMETER_STYLES = /* @__PURE__ */ new Set([
3053
+ "matrix",
3054
+ "label",
3055
+ "form",
3056
+ "simple",
3057
+ "spaceDelimited",
3058
+ "pipeDelimited",
3059
+ "deepObject",
3060
+ "cookie"
3061
+ ]);
3062
+ function pickStyleFields({ style, explode, allowReserved }) {
2945
3063
  return {
2946
- members: allOfMembers.filter((item) => {
2947
- if (!isReference(item) || !name) return true;
2948
- const deref = refs.resolve(item.$ref);
2949
- const discriminator = deref && getDiscriminator(deref);
2950
- const parentUnion = deref?.oneOf ?? deref?.anyOf;
2951
- if (!deref || !discriminator || isDiscriminator(deref) && !parentUnion) return true;
2952
- const childRef = `${SCHEMA_REF_PREFIX}${name}`;
2953
- const isDefault = childRef === getDefaultMappingRef(discriminator);
2954
- const values = isDefault ? [] : findDiscriminators({
2955
- mapping: discriminator.mapping,
2956
- ref: childRef
2957
- });
2958
- if (values.length) {
2959
- const { propertyName } = discriminator;
2960
- const propertyType = propertyTypeOf({
2961
- schema: deref,
2962
- propertyName,
2963
- refs
2964
- }) ?? propertyTypeOf({
2965
- schema: { $ref: childRef },
2966
- propertyName,
2967
- refs
2968
- });
2969
- discriminantValues.push({
2970
- propertyName,
2971
- values: typedKeys({
2972
- keys: values,
2973
- propertyType
2974
- })
2975
- });
2976
- }
2977
- return !(parentUnion && (isDefault || values.length > 0 || parentUnion.some((member) => isReference(member) && member.$ref === childRef)));
2978
- }),
2979
- discriminantValues
3064
+ ...style !== void 0 && PARAMETER_STYLES.has(style) ? { style } : {},
3065
+ ...explode !== void 0 ? { explode } : {},
3066
+ ...allowReserved !== void 0 ? { allowReserved } : {}
2980
3067
  };
2981
3068
  }
2982
- // src/emit/converters/annotatedEnum.ts
2983
- const ANNOTATIONS = /* @__PURE__ */ new Set([
2984
- "title",
2985
- "description",
2986
- "default",
2987
- "deprecated",
2988
- "readOnly",
2989
- "writeOnly",
2990
- "example",
2991
- "examples",
2992
- "xml",
2993
- "externalDocs"
2994
- ]);
2995
- const UNION_KEYS = /* @__PURE__ */ new Set([
2996
- ...ANNOTATIONS,
2997
- "type",
2998
- "nullable",
2999
- "oneOf",
3000
- "anyOf"
3001
- ]);
3002
- const MEMBER_KEYS = /* @__PURE__ */ new Set([
3003
- ...ANNOTATIONS,
3004
- "type",
3005
- "const"
3006
- ]);
3007
- function hasOnlyKeys(schema, keys) {
3008
- return typeof schema === "object" && schema !== null && !Array.isArray(schema) && Object.keys(schema).every((key) => keys.has(key) || key.startsWith("x-"));
3069
+ function getEncodingFields({ encoding, prefixEncoding, itemEncoding }) {
3070
+ const entries = Object.entries(encoding ?? {}).flatMap(([property, entry]) => {
3071
+ const node = toEncodingNode(entry);
3072
+ return Object.keys(node).length ? [[property, node]] : [];
3073
+ });
3074
+ const item = itemEncoding && toEncodingNode(itemEncoding);
3075
+ return {
3076
+ ...entries.length && { encoding: Object.fromEntries(entries) },
3077
+ ...prefixEncoding?.length && { prefixEncoding: prefixEncoding.map(toEncodingNode) },
3078
+ ...item && Object.keys(item).length && { itemEncoding: item }
3079
+ };
3009
3080
  }
3010
- function matchesType(type, value) {
3011
- return type === void 0 || type === typeof value || type === "integer" && typeof value === "number" && Number.isInteger(value);
3081
+ function toEncodingNode({ contentType, encoding, prefixEncoding, itemEncoding, ...rest }) {
3082
+ return {
3083
+ ...contentType !== void 0 && { contentType },
3084
+ ...pickStyleFields(rest),
3085
+ ...getEncodingFields({
3086
+ encoding,
3087
+ prefixEncoding,
3088
+ itemEncoding
3089
+ })
3090
+ };
3012
3091
  }
3013
- /** Recognizes annotated const unions only when replacing them cannot discard validation constraints. */
3014
- function convertAnnotatedEnum(context) {
3015
- const { schema, document } = context;
3016
- if (!document.openapi?.startsWith("3.1.")) return void 0;
3017
- if (!hasOnlyKeys(schema, UNION_KEYS) || schema.oneOf !== void 0 && schema.anyOf !== void 0) return void 0;
3018
- const members = schema.oneOf ?? schema.anyOf;
3019
- if (!members?.length) return void 0;
3020
- const names = /* @__PURE__ */ new Set();
3021
- const values = /* @__PURE__ */ new Set();
3022
- const namedEnumValues = [];
3023
- let primitive;
3024
- for (const member of members) {
3025
- if (!hasOnlyKeys(member, MEMBER_KEYS)) return void 0;
3026
- const value = member.const;
3027
- if (typeof value !== "string" && (typeof value !== "number" || !Number.isFinite(value))) return void 0;
3028
- if (typeof member.title !== "string" || !member.title.trim() || names.has(member.title) || values.has(value)) return void 0;
3029
- if (!matchesType(schema.type, value) || !matchesType(member.type, value)) return void 0;
3030
- const valueType = typeof value === "number" ? "number" : "string";
3031
- if (primitive !== void 0 && primitive !== valueType) return void 0;
3032
- primitive = valueType;
3033
- names.add(member.title);
3034
- values.add(value);
3035
- namedEnumValues.push({
3036
- name: member.title,
3037
- value,
3038
- primitive: valueType,
3039
- description: member.description
3040
- });
3041
- }
3042
- return createNode(context, {
3043
- type: "enum",
3044
- primitive,
3045
- namedEnumValues
3092
+ /**
3093
+ * The examples of a media type or a parameter. Named `examples` win over a single `example`.
3094
+ */
3095
+ function getExamples({ example, examples }, refs) {
3096
+ const named = Object.entries(examples ?? {}).flatMap(([name, entry]) => {
3097
+ const resolved = refs.deref(entry);
3098
+ if (!resolved) return [];
3099
+ const { summary, description, dataValue, value, serializedValue } = resolved;
3100
+ const data = dataValue !== void 0 ? dataValue : value;
3101
+ return [{
3102
+ name,
3103
+ ...typeof summary === "string" && { summary },
3104
+ ...typeof description === "string" && { description },
3105
+ ...data !== void 0 && { value: data },
3106
+ ...typeof serializedValue === "string" && { serializedValue }
3107
+ }];
3046
3108
  });
3109
+ if (named.length) return { examples: named };
3110
+ return example !== void 0 ? { examples: [{ value: example }] } : {};
3047
3111
  }
3048
- // src/emit/converters/composition.ts
3049
3112
  /**
3050
- * Collects property schemas from all `allOf` members and outer schema properties,
3051
- * recursively resolving `$ref` pointers.
3113
+ * Returns the media type entry for `contentType`, resolving a `$ref` into `components.mediaTypes`. `null` when absent.
3052
3114
  */
3053
- function collectSiblingProperties(allOfMembers, refs, outerProperties) {
3054
- const properties = { ...outerProperties };
3055
- const visited = /* @__PURE__ */ new Set();
3056
- /** Adds the properties of one member, following its `$ref` and its own `allOf`. */
3057
- function collectFrom(item) {
3058
- if (!item) return;
3059
- if (isReference(item)) {
3060
- if (visited.has(item.$ref)) return;
3061
- visited.add(item.$ref);
3062
- collectFrom(refs.resolve(item.$ref, { report: false }) ?? void 0);
3063
- return;
3064
- }
3065
- if (item.properties) Object.assign(properties, item.properties);
3066
- if (Array.isArray(item.allOf)) for (const member of item.allOf) collectFrom(member);
3067
- }
3068
- for (const item of allOfMembers) collectFrom(item);
3069
- return properties;
3115
+ function getMediaType({ content, contentType, refs }) {
3116
+ return contentType ? refs.deref(content?.[contentType]) : null;
3070
3117
  }
3071
3118
  /**
3072
- * Enriches union members that declare `required` properties without declaring corresponding
3073
- * property schemas, populating the missing property definitions from available sibling schemas
3074
- * (or an empty schema falling back to the configured emptySchemaType).
3119
+ * Returns the schema for one media type of a `content` map, before its `$ref` is resolved, with the binary fallback
3120
+ * for an emptied non-JSON entry. For a stream this is the item schema, so `schema: string` next to `itemSchema` types one item.
3075
3121
  */
3076
- function resolveUnionMembers(members, siblingProperties) {
3077
- return members.map((member) => {
3078
- if (!member || typeof member !== "object" || isReference(member)) return member;
3079
- const obj = member;
3080
- if (!Array.isArray(obj.required) || obj.required.length === 0) return member;
3081
- const existingProps = obj.properties ?? {};
3082
- const missingKeys = obj.required.filter((key) => !Object.hasOwn(existingProps, key));
3083
- if (missingKeys.length === 0) return member;
3084
- const newProperties = { ...existingProps };
3085
- for (const key of missingKeys) {
3086
- const value = Object.hasOwn(siblingProperties, key) ? siblingProperties[key] : {};
3087
- Object.defineProperty(newProperties, key, {
3088
- value,
3089
- enumerable: true,
3090
- writable: true,
3091
- configurable: true
3092
- });
3093
- }
3094
- return {
3095
- type: obj.type ?? "object",
3096
- ...obj,
3097
- properties: newProperties
3098
- };
3122
+ function getDeclaredBodySchema({ content, contentType, refs, document }) {
3123
+ const entry = getMediaType({
3124
+ content,
3125
+ contentType,
3126
+ refs
3127
+ });
3128
+ if (!contentType || !entry) return null;
3129
+ const schema = getItemSchema({
3130
+ contentType,
3131
+ mediaType: entry,
3132
+ refs,
3133
+ document
3134
+ }) ?? entry.schema;
3135
+ return (entry.itemSchema ? void 0 : getBinaryFallbackSchema(contentType, schema)) ?? schema ?? null;
3136
+ }
3137
+ function getStreamField({ contentType, mediaType, refs, document, node }) {
3138
+ if (!isStream(contentType, mediaType)) return {};
3139
+ const raw = getItemSchema({
3140
+ contentType,
3141
+ mediaType,
3142
+ refs,
3143
+ document
3144
+ });
3145
+ return { stream: {
3146
+ ...raw ? { schema: node } : {},
3147
+ ...raw && isEventStream(contentType) ? { shape: getItemShape(raw, refs) } : {}
3148
+ } };
3149
+ }
3150
+ function schemaKeyword(mediaType) {
3151
+ return mediaType?.itemSchema ? "itemSchema" : "schema";
3152
+ }
3153
+ function mediaTypePointer(content, contentType, fallback) {
3154
+ const entry = content?.[contentType];
3155
+ return isReference(entry) ? entry.$ref : fallback;
3156
+ }
3157
+ function collectPropertyKeysByFlag({ schema, flag, refs }) {
3158
+ if (!schema) return null;
3159
+ const keys = Object.entries(collectSiblingProperties([schema], refs)).flatMap(([key, prop]) => hasFlag({
3160
+ prop,
3161
+ flag,
3162
+ refs
3163
+ }) ? [key] : []);
3164
+ return keys.length ? keys : null;
3165
+ }
3166
+ function hasFlag({ prop, flag, refs }) {
3167
+ if (!prop || typeof prop !== "object") return false;
3168
+ if (prop[flag]) return true;
3169
+ return !!(isReference(prop) ? refs.resolve(prop.$ref, { report: false }) : null)?.[flag];
3170
+ }
3171
+ function parseContentEntry({ content, contentType, contentPointer, omit, refs, document, parse }) {
3172
+ const declared = getDeclaredBodySchema({
3173
+ content,
3174
+ contentType,
3175
+ refs,
3176
+ document
3177
+ });
3178
+ const schema = declared ? refs.derefKeepingRef(declared) : null;
3179
+ const node = parse(schema);
3180
+ if (!node) return null;
3181
+ const mediaType = getMediaType({
3182
+ content,
3183
+ contentType,
3184
+ refs
3185
+ });
3186
+ if (schema && contentType) scanSchema(node, `${mediaTypePointer(content, contentType, `${contentPointer}/${escapePointerToken(contentType)}`)}/${schemaKeyword(mediaType)}`);
3187
+ return {
3188
+ schema: node,
3189
+ keysToOmit: collectPropertyKeysByFlag({
3190
+ schema: declared,
3191
+ flag: omit,
3192
+ refs
3193
+ }),
3194
+ ...mediaType && getEncodingFields(mediaType),
3195
+ ...mediaType && getExamples(mediaType, refs),
3196
+ ...contentType ? getStreamField({
3197
+ contentType,
3198
+ mediaType,
3199
+ refs,
3200
+ document,
3201
+ node
3202
+ }) : {},
3203
+ extensions: pickExtensions(mediaType)
3204
+ };
3205
+ }
3206
+ // src/model/parameters.ts
3207
+ function withEnumName({ schema, param, parentName, options }) {
3208
+ if (!parentName || !param.name) return schema;
3209
+ return _kubb_kit.ast.macro.apply(schema, [(0, _kubb_kit.macroEnumName)({
3210
+ parentName,
3211
+ propName: param.name,
3212
+ enumSuffix: options.enumSuffix
3213
+ })], { depth: "shallow" });
3214
+ }
3215
+ function parseParameterSchema(ctx) {
3216
+ const { param, pointer, parentName, options, parseSchema, contentType, mediaType } = ctx;
3217
+ const rawSchema = param.schema ?? mediaType?.schema;
3218
+ const schemaName = parentName && param.name ? (0, _kubb_core.pascalCase)(`${parentName} ${param.name}`) : void 0;
3219
+ const schema = withEnumName({
3220
+ schema: rawSchema ? parseSchema({
3221
+ schema: rawSchema,
3222
+ name: schemaName
3223
+ }) : _kubb_kit.ast.factory.createSchema({ type: options.unknownType }),
3224
+ param,
3225
+ parentName,
3226
+ options
3099
3227
  });
3228
+ if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`);
3229
+ return schema;
3100
3230
  }
3101
3231
  /**
3102
- * Enriches a schema object, and any `oneOf` or `anyOf` branches on it, with properties from sibling schemas.
3232
+ * Converts one parameter into a `ParameterNode`, naming an inline schema after the operation and the parameter.
3103
3233
  */
3104
- function resolveUnionSchema(schema, siblingProperties) {
3105
- const next = { ...resolveUnionMembers([schema], siblingProperties)[0] ?? schema };
3106
- if (schema.oneOf) next.oneOf = resolveUnionMembers(schema.oneOf, siblingProperties);
3107
- if (schema.anyOf) next.anyOf = resolveUnionMembers(schema.anyOf, siblingProperties);
3108
- return next;
3234
+ function parseParameter(ctx) {
3235
+ const { param, pointer, refs } = ctx;
3236
+ const contentType = param.schema ? void 0 : Object.keys(param.content ?? {})[0];
3237
+ const mediaType = getMediaType({
3238
+ content: param.content,
3239
+ contentType,
3240
+ refs
3241
+ });
3242
+ const schema = parseParameterSchema({
3243
+ ...ctx,
3244
+ contentType,
3245
+ mediaType
3246
+ });
3247
+ return _kubb_kit.ast.factory.createParameter({
3248
+ pointer,
3249
+ name: param.name,
3250
+ in: param.in,
3251
+ schema: {
3252
+ ...schema,
3253
+ description: param.description ?? schema.description
3254
+ },
3255
+ required: param.required ?? false,
3256
+ ...pickStyleFields(param),
3257
+ ...contentType !== void 0 ? { contentType } : {},
3258
+ ...mediaType?.encoding && { encoding: getEncodingFields({ encoding: mediaType.encoding }).encoding },
3259
+ ...getExamples(mediaType ?? param, refs),
3260
+ ...param.deprecated && { deprecated: true },
3261
+ ...param.allowEmptyValue && { allowEmptyValue: true },
3262
+ extensions: pickExtensions(param)
3263
+ });
3109
3264
  }
3110
3265
  /**
3111
- * Converts a `$ref` schema into a `RefSchemaNode`.
3112
- *
3113
- * The resolved schema is stored in `node.schema`. Usage-site sibling fields
3114
- * (description, readOnly, nullable, etc.) are stored directly on the ref node.
3115
- * Use `ast.ref.mergeSchema(node)` in printers to get a merged view of both.
3116
- * Circular refs are detected in `refs.resolveNode` and leave `schema` as `null`.
3266
+ * Spreads a form-encoded OpenAPI 3.2 `querystring` object into one query parameter per property. Another content type stays whole.
3117
3267
  */
3118
- function convertRef({ schema, name, nullable, defaultValue, document, parse, refs, renames }) {
3119
- const refPath = schema.$ref;
3120
- const resolvedSchema = refPath ? refs.resolveNode(refPath, parse) : null;
3121
- const ctx = {
3122
- schema,
3123
- name,
3124
- nullable,
3125
- defaultValue
3126
- };
3127
- if (refPath && document.components && !refs.resolve(refPath, { report: false })) return createNode(ctx, { type: _kubb_kit.ast.schema.types.unknown });
3128
- if (refPath && !refPath.startsWith("#/components/schemas/") && resolvedSchema) return _kubb_kit.ast.factory.createSchema({
3129
- ...resolvedSchema,
3130
- title: schema.title ?? resolvedSchema.title,
3131
- description: schema.description ?? resolvedSchema.description,
3132
- deprecated: schema.deprecated ?? resolvedSchema.deprecated,
3133
- readOnly: schema.readOnly ?? resolvedSchema.readOnly,
3134
- writeOnly: schema.writeOnly ?? resolvedSchema.writeOnly,
3135
- default: defaultValue ?? resolvedSchema.default,
3136
- name: name ?? resolvedSchema.name,
3137
- nullable: nullable ?? resolvedSchema.nullable,
3138
- extensions: pickExtensions({
3139
- ...resolvedSchema.extensions,
3140
- ...schema
3141
- })
3142
- });
3143
- const targetName = renames?.get(schema.$ref);
3144
- return createNode(ctx, {
3145
- type: _kubb_kit.ast.schema.types.ref,
3146
- name: _kubb_kit.ast.ref.getName(schema.$ref),
3147
- ref: schema.$ref,
3148
- ...targetName ? { targetName } : {},
3149
- schema: resolvedSchema
3268
+ function spreadQuerystring(param) {
3269
+ if (param.in !== "querystring") return [param];
3270
+ const schema = _kubb_kit.ast.ref.getSchema(param.schema);
3271
+ const formEncoded = !param.contentType || _kubb_kit.ast.mediaType.getBase(param.contentType) === "application/x-www-form-urlencoded";
3272
+ if (schema.type !== "object" || !formEncoded) return [param];
3273
+ return schema.properties.map((property) => {
3274
+ const { style, explode, allowReserved } = param.encoding?.[property.name] ?? {};
3275
+ return _kubb_kit.ast.factory.createParameter({
3276
+ ...param.pointer ? { pointer: param.pointer } : {},
3277
+ name: property.name,
3278
+ in: "query",
3279
+ schema: property.schema,
3280
+ required: param.required && property.required,
3281
+ ...style !== void 0 && { style },
3282
+ ...explode !== void 0 && { explode },
3283
+ ...allowReserved !== void 0 && { allowReserved },
3284
+ ...param.extensions && { extensions: param.extensions }
3285
+ });
3150
3286
  });
3151
3287
  }
3152
- /** Converts `{ ...rest, not: X }` into `intersection[rest, not[X]]`; a bare `required` inside `not` borrows the outer `properties`. */
3153
- function convertNot({ schema, name, nullable, defaultValue, parse }) {
3154
- const { not, ...rest } = schema;
3155
- const [subschema] = resolveUnionMembers([not], rest.properties ?? {});
3156
- const notNode = _kubb_kit.ast.factory.createSchema({
3157
- type: _kubb_kit.ast.schema.types.not,
3158
- members: [parse({ schema: subschema })]
3159
- });
3160
- return createNode({
3161
- schema,
3162
- name,
3163
- nullable,
3164
- defaultValue
3165
- }, {
3166
- type: _kubb_kit.ast.schema.types.intersection,
3167
- members: [parse({
3168
- schema: rest,
3169
- name
3170
- }), notNode]
3171
- });
3288
+ // src/operation.ts
3289
+ function slugify(value) {
3290
+ return value.replace(/[^a-zA-Z0-9]/g, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "");
3172
3291
  }
3173
3292
  /**
3174
- * Keywords that describe a schema or conditionally constrain it, but add no structure.
3293
+ * Returns the operation's JSON pointer, under `additionalOperations` for an OpenAPI 3.2 method outside the fixed fields.
3175
3294
  */
3176
- const annotationKeys = /* @__PURE__ */ new Set([
3177
- "description",
3178
- "title",
3179
- "example",
3180
- "examples",
3181
- "default",
3182
- "deprecated",
3183
- "readOnly",
3184
- "writeOnly",
3185
- "if",
3186
- "then",
3187
- "else"
3188
- ]);
3295
+ function getOperationPointer({ path, method }) {
3296
+ const pathPointer = `#/paths/${escapePointerToken(path)}`;
3297
+ return SUPPORTED_METHODS.has(method.toLowerCase()) ? `${pathPointer}/${method.toLowerCase()}` : `${pathPointer}/additionalOperations/${escapePointerToken(method)}`;
3298
+ }
3189
3299
  /**
3190
- * Moves `allOf` members that hold only annotations or `if`/`then`/`else` onto the parent, so they do
3191
- * not become `unknown`. The parent's own values win. The parser reads their `if`/`then`/`else` into `conditionals`.
3300
+ * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.
3192
3301
  */
3193
- function isAnnotationMember(member) {
3194
- return !!member && typeof member === "object" && !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key));
3302
+ function getOperationId({ path, method, schema }) {
3303
+ const { operationId } = schema;
3304
+ if (typeof operationId === "string" && operationId.length > 0) return operationId;
3305
+ return `${method}_${slugify(path).toLowerCase()}`;
3195
3306
  }
3196
- function mergeAnnotations(schema) {
3197
- const members = schema.allOf;
3198
- const annotations = members.filter(isAnnotationMember);
3199
- const rest = members.filter((member) => !isAnnotationMember(member));
3200
- return annotations.length && rest.length ? {
3201
- ...Object.assign({}, ...annotations),
3202
- ...schema,
3203
- allOf: rest
3204
- } : schema;
3307
+ /**
3308
+ * Returns the declared response status codes, skipping `x-` extensions and non-object entries.
3309
+ */
3310
+ function getResponseStatusCodes({ schema }) {
3311
+ const responses = schema.responses;
3312
+ if (!responses || isReference(responses)) return [];
3313
+ return Object.keys(responses).filter((key) => !key.startsWith("x-") && !!responses[key] && typeof responses[key] === "object");
3205
3314
  }
3206
3315
  /**
3207
- * Whether the parent's own keywords become an intersection member: always beside `properties`, and
3208
- * beside several patterns when the parent holds more than its type and annotations, such as `minLength`.
3316
+ * Returns the response object for a status code, resolving a `$ref` through `refs`. `null` when absent.
3209
3317
  */
3210
- function keepsOwnKeywords(schema) {
3211
- if (schema.properties) return true;
3212
- if (!hasSeveralPatterns(schema)) return false;
3213
- return Object.keys(schema).some((key) => key !== "allOf" && key !== "type" && key !== "nullable" && !annotationKeys.has(key));
3318
+ function getResponseByStatusCode({ operation, refs, statusCode }) {
3319
+ const responses = operation.schema.responses;
3320
+ if (!responses || isReference(responses)) return null;
3321
+ return refs.deref(responses[statusCode]);
3214
3322
  }
3215
3323
  /**
3216
- * Whether a one-member `allOf` adds nothing but annotations, so it parses as that member.
3324
+ * Resolves the operation's request body, dereferencing a `$ref` through `refs`. Returns `null`
3325
+ * when the operation has no request body or it cannot be resolved.
3217
3326
  */
3218
- function isSingleMemberAllOf(schema) {
3219
- return schema.allOf.length === 1 && !schema.properties && !(Array.isArray(schema.required) && schema.required.length) && schema.additionalProperties === void 0 && !hasSeveralPatterns(schema);
3327
+ function getRequestBody({ operation, refs }) {
3328
+ return refs.deref(operation.schema.requestBody);
3329
+ }
3330
+ /** Merges path-level and operation-level parameters; operation-level wins per `in:name`. */
3331
+ function getParameters({ operation, refs }) {
3332
+ const resolveParams = (params, pointer) => params.flatMap((entry, index) => {
3333
+ const param = refs.derefKeepingRef(entry);
3334
+ return param && typeof param === "object" && "in" in param && "name" in param ? [{
3335
+ param,
3336
+ pointer: `${pointer}/parameters/${index}`
3337
+ }] : [];
3338
+ });
3339
+ const pathPointer = `#/paths/${escapePointerToken(operation.path)}`;
3340
+ const operationParams = resolveParams(operation.schema?.parameters || [], getOperationPointer(operation));
3341
+ const pathLevelParams = resolveParams(operation.pathItem.parameters ?? [], pathPointer);
3342
+ const paramMap = /* @__PURE__ */ new Map();
3343
+ for (const entry of [...pathLevelParams, ...operationParams]) if (entry.param.name && entry.param.in) paramMap.set(`${entry.param.in}:${entry.param.name}`, entry);
3344
+ return Array.from(paramMap.values());
3345
+ }
3346
+ function getLinks(links, refs) {
3347
+ const entries = Object.entries(links ?? {}).flatMap(([name, value]) => {
3348
+ const link = refs.deref(value);
3349
+ if (!link) return [];
3350
+ const server = link.server ? toInputServers([link.server])[0] : void 0;
3351
+ return [[name, {
3352
+ ...pickStrings(link, [
3353
+ "operationId",
3354
+ "operationRef",
3355
+ "description"
3356
+ ]),
3357
+ ...link.parameters && { parameters: link.parameters },
3358
+ ..."requestBody" in link && { requestBody: link.requestBody },
3359
+ ...server && { server }
3360
+ }]];
3361
+ });
3362
+ return entries.length ? Object.fromEntries(entries) : void 0;
3220
3363
  }
3221
3364
  /**
3222
- * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.
3365
+ * Builds an `Operation` for every supported HTTP method and every OpenAPI 3.2 `additionalOperations` entry on
3366
+ * every path, in document order. `x-` path keys and unresolvable path-item `$ref`s are skipped.
3223
3367
  */
3224
- function convertAllOf({ schema: original, name, nullable, defaultValue, parse, refs }) {
3225
- const schema = mergeAnnotations(original);
3226
- if (isSingleMemberAllOf(schema)) {
3227
- const [memberSchema] = schema.allOf;
3228
- const memberNode = parse({
3229
- schema: memberSchema,
3230
- name
3231
- });
3232
- const { kind: _kind, ...memberNodeProps } = memberNode;
3233
- const mergedNullable = nullable || memberNode.nullable || void 0;
3234
- const mergedDefault = schema.default === null && mergedNullable ? void 0 : schema.default ?? memberNode.default;
3235
- return _kubb_kit.ast.factory.createSchema({
3236
- ...memberNodeProps,
3237
- name,
3238
- title: schema.title ?? memberNode.title,
3239
- description: schema.description ?? memberNode.description,
3240
- deprecated: schema.deprecated ?? memberNode.deprecated,
3241
- nullable: mergedNullable,
3242
- readOnly: schema.readOnly ?? memberNode.readOnly,
3243
- writeOnly: schema.writeOnly ?? memberNode.writeOnly,
3244
- default: mergedDefault,
3245
- examples: extractExamples(schema) ?? memberNode.examples,
3246
- pattern: schema.pattern ?? ("pattern" in memberNode ? memberNode.pattern : void 0),
3247
- format: schema.format ?? memberNode.format,
3248
- extensions: pickExtensions({
3249
- ...memberNode.extensions,
3250
- ...schema
3251
- }),
3252
- externalDocs: getExternalDocs(schema.externalDocs) ?? memberNode.externalDocs
3368
+ function getOperations(document, refs) {
3369
+ const operations = [];
3370
+ const paths = document.paths;
3371
+ if (!paths) return operations;
3372
+ for (const path of Object.keys(paths)) {
3373
+ if (path.startsWith("x-")) continue;
3374
+ const pathItem = refs.deref(paths[path]);
3375
+ if (!pathItem) continue;
3376
+ const item = pathItem;
3377
+ for (const method of Object.keys(item)) {
3378
+ if (!SUPPORTED_METHODS.has(method)) continue;
3379
+ const schema = item[method];
3380
+ if (!schema || typeof schema !== "object") continue;
3381
+ operations.push({
3382
+ path,
3383
+ method,
3384
+ schema,
3385
+ pathItem
3386
+ });
3387
+ }
3388
+ for (const [method, schema] of Object.entries(pathItem.additionalOperations ?? {})) if (schema && typeof schema === "object" && !SUPPORTED_METHODS.has(method.toLowerCase())) operations.push({
3389
+ path,
3390
+ method,
3391
+ schema,
3392
+ pathItem
3253
3393
  });
3254
3394
  }
3255
- const { members: discriminatedAllOf, discriminantValues } = extractDiscriminatedAllOfMembers({
3256
- allOfMembers: removeInheritedDiscriminator({
3257
- members: schema.allOf,
3258
- refs
3259
- }),
3260
- name,
3261
- refs
3262
- });
3263
- const siblingProperties = collectSiblingProperties(schema.allOf, refs, schema.properties);
3264
- const allOfMembers = discriminatedAllOf.map((s) => isReference(s) ? s : resolveUnionSchema(s, siblingProperties)).map((s) => parse({
3265
- schema: s,
3266
- name
3267
- }));
3268
- const syntheticStart = allOfMembers.length;
3269
- if (Array.isArray(schema.required) && schema.required.length) {
3270
- const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : /* @__PURE__ */ new Set();
3271
- const missingRequired = schema.required.filter((key) => !outerKeys.has(key));
3272
- if (missingRequired.length) {
3273
- const resolvedMembers = schema.allOf.flatMap((item) => {
3274
- if (!isReference(item)) return [item];
3275
- const seen = /* @__PURE__ */ new Set();
3276
- let deref = item;
3277
- while (deref && isReference(deref) && !seen.has(deref.$ref)) {
3278
- seen.add(deref.$ref);
3279
- deref = refs.resolve(deref.$ref);
3280
- }
3281
- return deref && !isReference(deref) ? [deref] : [];
3282
- });
3283
- for (const key of missingRequired) for (const resolved of resolvedMembers) {
3284
- const prop = resolved.properties?.[key];
3285
- if (prop) {
3286
- const memberSchema = {
3287
- properties: { [key]: prop },
3288
- required: [key]
3289
- };
3290
- allOfMembers.push(parse({
3291
- schema: memberSchema,
3292
- name
3293
- }));
3294
- break;
3295
- }
3395
+ return withUniqueOperationIds(operations);
3396
+ }
3397
+ function suffixed(id, taken, counts) {
3398
+ const count = (counts.get(id) ?? 1) + 1;
3399
+ counts.set(id, count);
3400
+ const candidate = `${id}_${count}`;
3401
+ return taken.has((0, _kubb_core.pascalCase)(candidate)) ? suffixed(id, taken, counts) : candidate;
3402
+ }
3403
+ function withUniqueOperationIds(operations) {
3404
+ const taken = new Set(operations.flatMap(({ schema }) => typeof schema.operationId === "string" && schema.operationId ? [(0, _kubb_core.pascalCase)(schema.operationId)] : []));
3405
+ const claimed = /* @__PURE__ */ new Set();
3406
+ const counts = /* @__PURE__ */ new Map();
3407
+ return operations.map((operation) => {
3408
+ const operationId = getOperationId(operation);
3409
+ const name = (0, _kubb_core.pascalCase)(operationId);
3410
+ if (!claimed.has(name)) {
3411
+ claimed.add(name);
3412
+ taken.add(name);
3413
+ return operation;
3414
+ }
3415
+ const unique = suffixed(operationId, taken, counts);
3416
+ taken.add((0, _kubb_core.pascalCase)(unique));
3417
+ claimed.add((0, _kubb_core.pascalCase)(unique));
3418
+ _kubb_kit.Diagnostics.report({
3419
+ code: _kubb_kit.Diagnostics.code.duplicateOperationId,
3420
+ severity: "warning",
3421
+ message: `operationId "${operationId}" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to "${unique}".`,
3422
+ help: "Give each operation its own `operationId`.",
3423
+ location: {
3424
+ kind: "operation",
3425
+ pointer: getOperationPointer(operation)
3296
3426
  }
3297
- }
3298
- }
3299
- if (keepsOwnKeywords(schema)) {
3300
- const { allOf: _allOf, ...schemaWithoutAllOf } = schema;
3301
- allOfMembers.push(parse({ schema: schemaWithoutAllOf }));
3302
- }
3303
- for (const { propertyName, values } of discriminantValues) allOfMembers.push(createDiscriminantNode({
3304
- propertyName,
3305
- values
3306
- }));
3307
- return createNode({
3308
- schema,
3309
- name,
3310
- nullable,
3311
- defaultValue
3312
- }, {
3313
- type: _kubb_kit.ast.schema.types.intersection,
3314
- members: [...(0, _kubb_kit.mergeAdjacentObjectsLazy)(allOfMembers.slice(0, syntheticStart)), ...(0, _kubb_kit.mergeAdjacentObjectsLazy)(allOfMembers.slice(syntheticStart))]
3315
- });
3316
- }
3317
- const scalarTypes = /* @__PURE__ */ new Set([
3318
- "string",
3319
- "number",
3320
- "integer",
3321
- "boolean"
3322
- ]);
3323
- /**
3324
- * Copies a scalar parent `type` and `format` onto inline members without a `type`. JSON Schema applies
3325
- * sibling keywords to every member, so `type: 'integer', anyOf: [{ minimum: 10 }]` keeps each member an integer.
3326
- */
3327
- function inheritScalarType(members, { schema, type }) {
3328
- if (!type || !scalarTypes.has(type)) return members;
3329
- if (Array.isArray(schema.type) && schema.type.filter((t) => t !== "null").length > 1) return members;
3330
- return members.map((member) => {
3331
- if (!member || typeof member !== "object" || isReference(member) || member.type !== void 0) return member;
3332
- const obj = member;
3427
+ });
3333
3428
  return {
3334
- type,
3335
- ...schema.format !== void 0 && obj.format === void 0 && { format: schema.format },
3336
- ...obj
3429
+ ...operation,
3430
+ schema: {
3431
+ ...operation.schema,
3432
+ operationId: unique
3433
+ }
3337
3434
  };
3338
3435
  });
3339
3436
  }
3340
- /**
3341
- * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.
3342
- */
3343
- function convertUnion(context) {
3344
- if (context.schema.enum?.length) {
3345
- const { enum: values, ...union } = context.schema;
3346
- const nullable = context.nullable || [...union.oneOf ?? [], ...union.anyOf ?? []].some((member) => {
3347
- const resolved = isReference(member) ? context.refs.resolve(member.$ref, { report: false }) : member;
3348
- return !!resolved && !isReference(resolved) && isNullable(resolved, context.document);
3349
- });
3350
- const enumSchema = {
3351
- type: union.type,
3352
- enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values
3353
- };
3354
- const members = [convertUnion({
3355
- ...context,
3356
- schema: union
3357
- }), context.parse({ schema: enumSchema })];
3358
- return createNode(context, {
3359
- type: _kubb_kit.ast.schema.types.intersection,
3360
- members
3437
+ function parseRequestBody({ operation, operationName, pointer, ctx }) {
3438
+ const { document, refs, contentType, parseSchema } = ctx;
3439
+ const body = getRequestBody({
3440
+ operation,
3441
+ refs
3442
+ });
3443
+ if (!body) return void 0;
3444
+ const bodyRequired = body.required === true;
3445
+ const requestBodyName = operationName ? `${operationName}Request` : void 0;
3446
+ const content = (contentType ? [contentType] : Object.keys(body.content ?? {})).flatMap((ct) => {
3447
+ const entry = parseContentEntry({
3448
+ content: body.content,
3449
+ contentType: ct,
3450
+ contentPointer: `${pointer}/requestBody/content`,
3451
+ omit: "readOnly",
3452
+ refs,
3453
+ document,
3454
+ parse: (schema) => schema ? _kubb_kit.ast.schema.applyOptionality(parseSchema({
3455
+ schema,
3456
+ name: requestBodyName
3457
+ }), bodyRequired) : null
3361
3458
  });
3362
- }
3363
- const annotatedEnum = convertAnnotatedEnum(context);
3364
- if (annotatedEnum) return annotatedEnum;
3365
- const { schema, name, nullable, defaultValue, parse, refs } = context;
3366
- const ctx = {
3367
- schema,
3368
- name,
3369
- nullable,
3370
- defaultValue
3459
+ return entry ? [_kubb_kit.ast.factory.createContent({
3460
+ contentType: ct,
3461
+ ...entry
3462
+ })] : [];
3463
+ });
3464
+ if (content.length === 0 && !body.description) return void 0;
3465
+ return {
3466
+ pointer: `${pointer}/requestBody`,
3467
+ description: body.description,
3468
+ required: bodyRequired || void 0,
3469
+ content: content.length > 0 ? content : void 0,
3470
+ extensions: pickExtensions(body)
3371
3471
  };
3372
- const discriminator = isDiscriminator(schema) ? schema.discriminator : void 0;
3373
- const declaredMembers = [...schema.oneOf ?? [], ...schema.anyOf ?? []];
3374
- const defaultRef = getDefaultMappingRef(typeof schema.discriminator === "object" ? schema.discriminator : void 0);
3375
- const unionMembers = resolveUnionMembers(inheritScalarType(defaultRef && !declaredMembers.some((member) => isReference(member) && member.$ref === defaultRef) ? [...declaredMembers, { $ref: defaultRef }] : declaredMembers, context), schema.properties ?? {});
3376
- const strategy = schema.oneOf ? "one" : "any";
3377
- const explicitDiscriminatorPropertyName = discriminator?.propertyName;
3378
- const { oneOf: _o, anyOf: _a, discriminator: _d, ...memberBaseSchema } = schema;
3379
- const sharedPropertiesNode = schema.properties ? parse({
3380
- schema: memberBaseSchema,
3381
- name
3382
- }) : void 0;
3383
- const missingRequired = (Array.isArray(schema.required) ? schema.required : []).filter((key) => !Object.hasOwn(schema.properties ?? {}, key));
3384
- if (sharedPropertiesNode || discriminator || missingRequired.length) {
3385
- const members = narrowUnionMembers({
3386
- unionMembers,
3387
- discriminator,
3388
- sharedPropertiesNode,
3389
- parentType: discriminator && propertyTypeOf({
3390
- schema,
3391
- propertyName: discriminator.propertyName,
3392
- refs
3393
- }),
3394
- parse,
3395
- name,
3472
+ }
3473
+ function pickDoc({ operation, key }) {
3474
+ const own = operation.schema[key];
3475
+ if (typeof own === "string") return own;
3476
+ const fallback = operation.pathItem[key];
3477
+ return typeof fallback === "string" ? fallback : void 0;
3478
+ }
3479
+ function parseResponseHeaders({ response, responsePointer, responseName, ctx: { options, parseSchema, refs } }) {
3480
+ return Object.entries(response?.headers ?? {}).flatMap(([name, value]) => {
3481
+ const header = name.toLowerCase() === "content-type" ? null : refs.deref(value);
3482
+ if (!header) return [];
3483
+ return [parseParameter({
3484
+ param: {
3485
+ ...header,
3486
+ name,
3487
+ in: "header"
3488
+ },
3489
+ pointer: `${responsePointer}/headers/${escapePointerToken(name)}`,
3490
+ parentName: responseName,
3491
+ options,
3492
+ parseSchema,
3396
3493
  refs
3397
- });
3398
- const unionNode = createNode(ctx, {
3399
- type: _kubb_kit.ast.schema.types.union,
3400
- strategy,
3401
- members,
3402
- discriminatorPropertyName: explicitDiscriminatorPropertyName ?? _kubb_kit.ast.schema.inferDiscriminator(members)
3403
- });
3404
- const requiredProperties = missingRequired.map((name) => _kubb_kit.ast.factory.createProperty({
3405
- name,
3406
- required: true,
3407
- schema: _kubb_kit.ast.factory.createSchema({ type: _kubb_kit.ast.schema.types.unknown })
3408
- }));
3409
- const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : [];
3410
- if (requiredProperties.length) siblings.push(_kubb_kit.ast.factory.createSchema({
3411
- type: _kubb_kit.ast.schema.types.object,
3412
- properties: requiredProperties
3413
- }));
3414
- if (!siblings.length) return unionNode;
3415
- return createNode(ctx, {
3416
- type: _kubb_kit.ast.schema.types.intersection,
3417
- members: [unionNode, ...siblings]
3418
- });
3419
- }
3420
- const members = unionMembers.map((s) => parse({
3421
- schema: s,
3422
- name
3494
+ })];
3495
+ });
3496
+ }
3497
+ function parseResponse({ operation, key, operationName, pointer, ctx }) {
3498
+ const { document, refs, contentType, options, parseSchema } = ctx;
3499
+ const response = getResponseByStatusCode({
3500
+ operation,
3501
+ refs,
3502
+ statusCode: key
3503
+ });
3504
+ const { content, summary, description, links: rawLinks } = response ?? {};
3505
+ const statusCode = key.toLowerCase();
3506
+ const responseName = operationName ? `${operationName}Status${statusCode}` : void 0;
3507
+ const responsePointer = `${pointer}/responses/${key}`;
3508
+ const parseEntrySchema = (ct) => parseContentEntry({
3509
+ content,
3510
+ contentType: ct,
3511
+ contentPointer: `${responsePointer}/content`,
3512
+ omit: "writeOnly",
3513
+ refs,
3514
+ document,
3515
+ parse: (schema) => schema && Object.keys(schema).length > 0 ? parseSchema({
3516
+ schema,
3517
+ name: responseName
3518
+ }) : _kubb_kit.ast.factory.createSchema({ type: options.emptySchemaType })
3519
+ });
3520
+ const declaredContentTypes = Object.keys(content ?? {});
3521
+ const responseContent = (contentType && declaredContentTypes.length ? [contentType] : declaredContentTypes).map((ct) => _kubb_kit.ast.factory.createContent({
3522
+ contentType: ct,
3523
+ ...parseEntrySchema(ct)
3423
3524
  }));
3424
- const unionNode = createNode(ctx, {
3425
- type: _kubb_kit.ast.schema.types.union,
3426
- strategy,
3427
- members,
3428
- discriminatorPropertyName: explicitDiscriminatorPropertyName ?? _kubb_kit.ast.schema.inferDiscriminator(members)
3525
+ if (responseContent.length === 0) responseContent.push(_kubb_kit.ast.factory.createContent({
3526
+ contentType: "",
3527
+ ...parseEntrySchema(contentType)
3528
+ }));
3529
+ const headers = parseResponseHeaders({
3530
+ response,
3531
+ responsePointer,
3532
+ responseName,
3533
+ ctx
3534
+ });
3535
+ const links = getLinks(rawLinks, refs);
3536
+ return _kubb_kit.ast.factory.createResponse({
3537
+ pointer: responsePointer,
3538
+ statusCode,
3539
+ summary,
3540
+ description,
3541
+ content: responseContent,
3542
+ ...headers.length && { headers },
3543
+ ...links && { links },
3544
+ extensions: pickExtensions(response)
3429
3545
  });
3430
- return _kubb_kit.ast.macro.apply(unionNode, [_kubb_kit.macroDedupeUnion], { depth: "shallow" });
3431
3546
  }
3432
3547
  /**
3433
- * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.
3434
- * Only called once the multi-type rule's `match` has confirmed more than one non-`null` type
3435
- * remains; a single remaining type (e.g. `['string', 'null']`) is handled as that type instead,
3436
- * with nullability already folded in.
3548
+ * Converts an OAS `Operation` into an `OperationNode`.
3437
3549
  */
3438
- function convertMultiType({ schema, name, nullable, defaultValue, parse }) {
3439
- const nonNullTypes = schema.type.filter((t) => t !== "null");
3440
- return createNode({
3441
- schema,
3442
- name,
3443
- nullable,
3444
- defaultValue
3445
- }, {
3446
- type: _kubb_kit.ast.schema.types.union,
3447
- members: nonNullTypes.map((t) => {
3448
- return parse({
3449
- schema: {
3450
- ...Object.fromEntries(Object.entries(schema).filter(([key]) => !key.startsWith("x-"))),
3451
- type: t
3452
- },
3453
- name
3454
- });
3455
- })
3550
+ function parseOperation({ operation, ...ctx }) {
3551
+ const { document, refs, options, parseSchema } = ctx;
3552
+ const operationId = getOperationId(operation);
3553
+ const operationName = operationId ? (0, _kubb_core.pascalCase)(operationId) : void 0;
3554
+ const pointer = getOperationPointer(operation);
3555
+ const parameters = getParameters({
3556
+ operation,
3557
+ refs
3558
+ }).map((entry) => parseParameter({
3559
+ options,
3560
+ parseSchema,
3561
+ refs,
3562
+ ...entry,
3563
+ parentName: operationName
3564
+ })).flatMap(spreadQuerystring);
3565
+ const requestBody = parseRequestBody({
3566
+ operation,
3567
+ operationName,
3568
+ pointer,
3569
+ ctx
3570
+ });
3571
+ const responses = getResponseStatusCodes(operation).map((key) => parseResponse({
3572
+ operation,
3573
+ key,
3574
+ operationName,
3575
+ pointer,
3576
+ ctx
3577
+ }));
3578
+ const servers = operation.schema.servers?.length ? operation.schema.servers : operation.pathItem.servers;
3579
+ const auth = toAuthRequirements(operation.schema.security ?? document.security, document);
3580
+ return _kubb_kit.ast.factory.createOperation({
3581
+ pointer,
3582
+ operationId,
3583
+ protocol: "http",
3584
+ method: SUPPORTED_METHODS.has(operation.method) ? operation.method.toUpperCase() : operation.method,
3585
+ path: operation.path,
3586
+ tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],
3587
+ summary: pickDoc({
3588
+ operation,
3589
+ key: "summary"
3590
+ }) || void 0,
3591
+ description: pickDoc({
3592
+ operation,
3593
+ key: "description"
3594
+ }) || void 0,
3595
+ deprecated: operation.schema.deprecated || void 0,
3596
+ externalDocs: getExternalDocs(operation.schema.externalDocs),
3597
+ parameters,
3598
+ requestBody,
3599
+ responses,
3600
+ extensions: pickExtensions(operation.schema),
3601
+ ...servers && { servers: toInputServers(servers) },
3602
+ ...auth && { auth }
3456
3603
  });
3457
3604
  }
3605
+ /** Renames path parameters and their `{placeholder}` to the camelCase names from {@link Url.toParamNames}. */
3606
+ function camelCasePathParams(node) {
3607
+ if (!node.path || node.parameters.some((param) => param.in === "path" && param.style === "matrix")) return node;
3608
+ const names = _kubb_kit.Url.toParamNames(node.path);
3609
+ return {
3610
+ ...node,
3611
+ path: node.path.replace(/\{([^}]+)\}/g, (_match, name) => `{${names.get(name) ?? name}}`),
3612
+ parameters: node.parameters.map((param) => param.in === "path" && names.has(param.name) ? {
3613
+ ...param,
3614
+ name: names.get(param.name)
3615
+ } : param)
3616
+ };
3617
+ }
3458
3618
  // src/emit/converters/scalar.ts
3459
3619
  /**
3460
3620
  * Normalizes malformed `{ type: 'array', enum: [...] }` schemas by moving enum values into items.
@@ -3582,7 +3742,7 @@ function convertFormat(context) {
3582
3742
  representation: value === "date" ? "date" : "string"
3583
3743
  });
3584
3744
  }
3585
- const specialType = formatMap[schema.format];
3745
+ const specialType = getFormatType(schema.format);
3586
3746
  if (specialType === "blob") return convertBlob(context);
3587
3747
  if (specialType === "string") {
3588
3748
  if (type === "integer" || type === "number") return convertNumeric(context, type);
@@ -3903,7 +4063,7 @@ function formatPrintsPlainType({ schema, options, type }) {
3903
4063
  const format = schema.format;
3904
4064
  if (format === "date-time" || format === "date" || format === "time") return resolveDateTypeValue(options.dateType, format) !== "date";
3905
4065
  if ((format === "int64" || format === "uint64") && type !== "string") return options.integerType !== "bigint";
3906
- return formatMap[format] !== "blob";
4066
+ return getFormatType(format) !== "blob";
3907
4067
  }
3908
4068
  /**
3909
4069
  * Ordered schema rule table. Order is significant: composition keywords (`not`, `$ref`, `allOf`,
@@ -4239,9 +4399,15 @@ var Adapter = class {
4239
4399
  };
4240
4400
  this.#parserOptions = parserOptions;
4241
4401
  }
4402
+ /**
4403
+ * @deprecated Read `document` from the result of `parse`. It follows the last parse. Removed in Kubb v6.
4404
+ */
4242
4405
  get document() {
4243
4406
  return this.#document;
4244
4407
  }
4408
+ /**
4409
+ * @deprecated Read `sources` from the result of `parse`. It follows the last parse. Removed in Kubb v6.
4410
+ */
4245
4411
  get sources() {
4246
4412
  return this.#sources;
4247
4413
  }
@@ -4249,30 +4415,46 @@ var Adapter = class {
4249
4415
  const document = await parseFromConfig({
4250
4416
  type: "path",
4251
4417
  path: input
4252
- }, [], { fileRefs: options?.fileRefs });
4418
+ }, [], { harness: options?.harness });
4253
4419
  assertDocument(document);
4254
4420
  await validateDocument(document, options);
4255
4421
  };
4256
4422
  settle = async () => {
4257
4423
  await Promise.all(this.#pendingValidations.splice(0));
4258
4424
  };
4259
- parse = async (source, { signal, fileRefs } = {}) => {
4425
+ /**
4426
+ * Returns the AST with the document and the files this call read, so two overlapping parses on one instance each
4427
+ * get their own.
4428
+ */
4429
+ parse = async (source, options) => {
4430
+ const entry = this.#start(source, options);
4431
+ return {
4432
+ node: await entry.promise,
4433
+ document: entry.document,
4434
+ sources: entry.sources
4435
+ };
4436
+ };
4437
+ #start(source, { signal, harness } = {}) {
4260
4438
  signal?.throwIfAborted();
4261
- const cached = this.#inputCache.get(source);
4439
+ const cached = this.#cached({
4440
+ source,
4441
+ harness
4442
+ });
4262
4443
  if (cached) {
4263
4444
  this.#sources = cached.sources;
4264
4445
  this.#document = cached.document;
4265
- return cached.promise;
4446
+ return cached;
4266
4447
  }
4267
4448
  const read = [];
4268
4449
  this.#sources = read;
4269
4450
  const entry = {
4270
4451
  sources: read,
4271
- document: null
4452
+ document: null,
4453
+ harness
4272
4454
  };
4273
4455
  const promise = (async () => {
4274
4456
  const document = await parseFromConfig(source, read, {
4275
- fileRefs,
4457
+ harness,
4276
4458
  signal
4277
4459
  });
4278
4460
  signal?.throwIfAborted();
@@ -4295,13 +4477,18 @@ var Adapter = class {
4295
4477
  pointers,
4296
4478
  parseSchema
4297
4479
  }));
4298
- })();
4299
- this.#inputCache.set(source, Object.assign(entry, { promise }));
4300
- return promise.catch((error) => {
4480
+ })().catch((error) => {
4301
4481
  if (signal?.aborted) this.#inputCache.delete(source);
4302
4482
  throw error;
4303
4483
  });
4304
- };
4484
+ const started = Object.assign(entry, { promise });
4485
+ this.#inputCache.set(source, started);
4486
+ return started;
4487
+ }
4488
+ #cached({ source, harness }) {
4489
+ const cached = this.#inputCache.get(source);
4490
+ return cached?.harness === harness ? cached : void 0;
4491
+ }
4305
4492
  /**
4306
4493
  * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.
4307
4494
  */