@apifn/core 0.0.4 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import {
2
+ openAPIReferenceContext
3
+ } from "./chunk-NWH3AIKS.js";
1
4
  import "./chunk-VUNV25KB.js";
2
5
 
3
6
  // src/introspect.ts
@@ -23,14 +26,14 @@ function hasSchemaDescriptor(meta) {
23
26
  }
24
27
  return KNOWN_DESCRIPTOR_KEYS.some((key) => key in meta);
25
28
  }
26
- function normalizePathSegment(path2) {
27
- if (!path2.startsWith("/")) {
28
- return `/${path2}`;
29
+ function normalizePathSegment(path) {
30
+ if (!path.startsWith("/")) {
31
+ return `/${path}`;
29
32
  }
30
- return path2;
33
+ return path;
31
34
  }
32
- function withBasePath(path2, basePath) {
33
- const routePath = normalizePathSegment(path2);
35
+ function withBasePath(path, basePath) {
36
+ const routePath = normalizePathSegment(path);
34
37
  if (!basePath) {
35
38
  return routePath;
36
39
  }
@@ -44,19 +47,19 @@ function withBasePath(path2, basePath) {
44
47
  }
45
48
  return `${normalizedBasePath}/${normalizedRoutePath}`;
46
49
  }
47
- function toOpenApiPath(path2) {
50
+ function toOpenApiPath(path) {
48
51
  const params = [];
49
52
  let openApiPath = "";
50
53
  let index = 0;
51
- while (index < path2.length) {
52
- const char = path2[index];
54
+ while (index < path.length) {
55
+ const char = path[index];
53
56
  if (char !== ":") {
54
57
  openApiPath += char;
55
58
  index += 1;
56
59
  continue;
57
60
  }
58
61
  let end = index + 1;
59
- while (end < path2.length && /[A-Za-z0-9_]/.test(path2[end])) {
62
+ while (end < path.length && /[A-Za-z0-9_]/.test(path[end])) {
60
63
  end += 1;
61
64
  }
62
65
  if (end === index + 1) {
@@ -64,7 +67,7 @@ function toOpenApiPath(path2) {
64
67
  index += 1;
65
68
  continue;
66
69
  }
67
- const param = path2.slice(index + 1, end);
70
+ const param = path.slice(index + 1, end);
68
71
  params.push(param);
69
72
  openApiPath += `{${param}}`;
70
73
  index = end;
@@ -146,17 +149,17 @@ function toResponses(descriptor) {
146
149
  }
147
150
  return responses;
148
151
  }
149
- function shouldIncludePath(path2, prefixes) {
152
+ function shouldIncludePath(path, prefixes) {
150
153
  if (!prefixes || prefixes.length === 0) {
151
154
  return true;
152
155
  }
153
- return prefixes.some((prefix) => path2.startsWith(prefix));
156
+ return prefixes.some((prefix) => path.startsWith(prefix));
154
157
  }
155
- function shouldExcludePath(path2, prefixes) {
158
+ function shouldExcludePath(path, prefixes) {
156
159
  if (!prefixes || prefixes.length === 0) {
157
160
  return false;
158
161
  }
159
- return prefixes.some((prefix) => path2.startsWith(prefix));
162
+ return prefixes.some((prefix) => path.startsWith(prefix));
160
163
  }
161
164
  function toIntrospectedRoute(route, options) {
162
165
  const fullPath = withBasePath(route.path, options.basePath);
@@ -166,7 +169,7 @@ function toIntrospectedRoute(route, options) {
166
169
  if (shouldExcludePath(fullPath, options.exclude)) {
167
170
  return null;
168
171
  }
169
- const { path: path2, pathParams } = toOpenApiPath(fullPath);
172
+ const { path, pathParams } = toOpenApiPath(fullPath);
170
173
  const rawMeta = route.meta;
171
174
  const meta = isObject(rawMeta) ? rawMeta : {};
172
175
  const descriptor = hasSchemaDescriptor(rawMeta) ? rawMeta : void 0;
@@ -178,7 +181,7 @@ function toIntrospectedRoute(route, options) {
178
181
  }
179
182
  return {
180
183
  method: route.method,
181
- path: path2,
184
+ path,
182
185
  operationId: descriptor?.operationId,
183
186
  summary: descriptor?.summary,
184
187
  description: descriptor?.description,
@@ -503,7 +506,7 @@ function toPaths(routes) {
503
506
  ([a], [b]) => a.localeCompare(b)
504
507
  );
505
508
  const paths = {};
506
- for (const [path2, pathRoutes] of sortedPaths) {
509
+ for (const [path, pathRoutes] of sortedPaths) {
507
510
  const item = {};
508
511
  const sortedRoutes = [...pathRoutes].sort(
509
512
  (a, b) => METHOD_ORDER.indexOf(methodKey(a.method)) - METHOD_ORDER.indexOf(methodKey(b.method))
@@ -512,7 +515,7 @@ function toPaths(routes) {
512
515
  const key = methodKey(route.method);
513
516
  item[key] = toOperation(route);
514
517
  }
515
- paths[path2] = item;
518
+ paths[path] = item;
516
519
  }
517
520
  return paths;
518
521
  }
@@ -674,6 +677,354 @@ function parseOpenAPI(input) {
674
677
 
675
678
  // src/openapi/validate.ts
676
679
  import SwaggerParser from "@apidevtools/swagger-parser";
680
+ import { isAlias, isPair, isScalar, parseDocument, visit } from "yaml";
681
+ var EXTERNAL_REF_ERROR = "External OpenAPI $ref requires an explicit allowlist entry";
682
+ function referenceChildMode(parent, mode, key, child) {
683
+ const { childMode, entryMode, arrayItemMode } = openAPIReferenceContext;
684
+ if (Array.isArray(parent)) return arrayItemMode(mode);
685
+ if (mode === "literal" || mode === "example") return "literal";
686
+ return entryMode(mode, key, child) ?? childMode(key, child);
687
+ }
688
+ var ReferencePreparationError = class extends Error {
689
+ path;
690
+ constructor(site, cause) {
691
+ super(cause instanceof Error ? cause.message : "OpenAPI ref could not be prepared", { cause });
692
+ this.path = [...pathKeys(site), "$ref"].join(".");
693
+ }
694
+ };
695
+ function pathKeys(path) {
696
+ const segments = [];
697
+ for (let cursor = path; cursor; cursor = cursor.parent) segments.push(cursor.key);
698
+ return segments.reverse();
699
+ }
700
+ function parsePreloadedDocument(contents) {
701
+ const parsed = parseDocument(contents);
702
+ if (parsed.errors.length) throw new Error(parsed.errors[0].message);
703
+ const mergeTag = "tag:yaml.org,2002:merge";
704
+ const implicitMerge = parsed.schema.tags.some((tag) => tag.tag === mergeTag && tag.default);
705
+ let hasAliases = false;
706
+ let sourceNodes = 0;
707
+ visit(parsed, (_key, node) => {
708
+ sourceNodes += 1;
709
+ hasAliases ||= isAlias(node);
710
+ if (isPair(node) && isScalar(node.key)) {
711
+ const { tag, type, value: value2 } = node.key;
712
+ const mergeKey = value2 === "<<" || typeof value2 === "symbol" && value2.description === "<<";
713
+ if (tag === mergeTag || implicitMerge && (!type || type === "PLAIN") && mergeKey) {
714
+ throw new Error("YAML merge keys are unsupported in preloaded OpenAPI documents");
715
+ }
716
+ }
717
+ });
718
+ const value = parsed.toJS({ maxAliasCount: -1 });
719
+ if (!hasAliases) return value;
720
+ const limit = sourceNodes * 100;
721
+ const weights = /* @__PURE__ */ new WeakMap();
722
+ function count(node) {
723
+ if (typeof node !== "object" || node === null) return 1;
724
+ const cached = weights.get(node);
725
+ if (cached !== void 0) return cached;
726
+ weights.set(node, limit + 1);
727
+ let size = 1;
728
+ for (const child of Object.values(node)) {
729
+ size += count(child);
730
+ if (size > limit) throw new Error("Excessive YAML alias expansion in preloaded OpenAPI document");
731
+ }
732
+ weights.set(node, size);
733
+ return size;
734
+ }
735
+ count(value);
736
+ return value;
737
+ }
738
+ function decodeFragment(fragment) {
739
+ try {
740
+ return decodeURIComponent(fragment);
741
+ } catch {
742
+ return fragment;
743
+ }
744
+ }
745
+ function unescapePointerToken(token) {
746
+ return token.replaceAll("~1", "/").replaceAll("~0", "~");
747
+ }
748
+ function encodePointer(tokens) {
749
+ return "#" + tokens.map(
750
+ (token) => "/" + encodeURIComponent(token.replaceAll("~", "~0").replaceAll("/", "~1"))
751
+ ).join("");
752
+ }
753
+ function pointerMember(parent, tokens, index) {
754
+ const key = tokens[index];
755
+ if (!Object.hasOwn(parent, key) || Reflect.get(parent, key) === void 0 || index === tokens.length - 1 && Reflect.get(parent, key) === null) {
756
+ for (let end = tokens.length; end > index + 1; end -= 1) {
757
+ const joined = tokens.slice(index, end).join("/");
758
+ if (Object.hasOwn(parent, joined) && Reflect.get(parent, joined) !== void 0) {
759
+ return { key: joined, index: end - 1 };
760
+ }
761
+ }
762
+ }
763
+ return Object.hasOwn(parent, key) ? { key, index } : void 0;
764
+ }
765
+ var LOCAL_PATH_ORIGIN = "https://apifn-local-path.invalid";
766
+ var WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
767
+ var WINDOWS_SHARE_PATH = /^\\\\([^\\/]+)[\\/]([^\\/]+)(?:[\\/]|$)/;
768
+ function workingDirectoryLocation() {
769
+ const cwd = typeof process !== "undefined" && process.cwd ? process.cwd() : "/";
770
+ const share = WINDOWS_SHARE_PATH.exec(cwd);
771
+ const windowsPath = share ? "C:\\" + cwd.slice(share[0].length) : cwd;
772
+ const isWindowsPath = WINDOWS_DRIVE_PATH.test(windowsPath);
773
+ if (isWindowsPath) {
774
+ const [drive, ...segments] = windowsPath.replaceAll("\\", "/").split("/");
775
+ const directory = segments.map(encodeURIComponent).join("/").replace(/\/$/, "");
776
+ const url2 = new URL("file:///" + drive + "/" + (directory ? directory + "/" : ""));
777
+ const shareRoot = share ? absolutePathKey("//" + [share[1], share[2]].map(encodeURIComponent).join("/")) : void 0;
778
+ return { url: url2, isPath: true, isWindowsPath, shareRoot };
779
+ }
780
+ const path = (cwd.startsWith("/") ? cwd : "/" + cwd).replace(/\/$/, "") + "/";
781
+ const url = new URL(LOCAL_PATH_ORIGIN);
782
+ url.pathname = path.split("/").map(encodeURIComponent).join("/");
783
+ return { url, isPath: true, isWindowsPath };
784
+ }
785
+ function absolutePathKey(pathname) {
786
+ return pathname.split("/").map(
787
+ (segment) => decodeURIComponent(segment).replaceAll("%", "%25").replaceAll("?", "%3F").replaceAll("/", "%2F").replaceAll("\\", "%5C")
788
+ ).join("/");
789
+ }
790
+ function resolveDocumentURI(base, ref) {
791
+ const pathEnd = ref.search(/[?#]/);
792
+ const refPath = pathEnd < 0 ? ref : ref.slice(0, pathEnd);
793
+ const normalized = refPath.replaceAll("\\", "/") + ref.slice(refPath.length);
794
+ const windowsDrive = WINDOWS_DRIVE_PATH.test(normalized);
795
+ const share = WINDOWS_SHARE_PATH.exec(refPath);
796
+ const windowsPath = share ? "C:/" + normalized.slice(share[0].length) : normalized;
797
+ const isAbsoluteWindowsPath = windowsDrive || share !== null;
798
+ const url = isAbsoluteWindowsPath ? new URL("file:///" + windowsPath) : new URL(normalized, base.url);
799
+ const absolute = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(normalized.trimStart());
800
+ const fragment = url.hash.slice(1);
801
+ url.hash = "";
802
+ const isPath = isAbsoluteWindowsPath || base.isPath && !absolute && url.origin === base.url.origin;
803
+ const queryStart = url.href.indexOf("?");
804
+ const query = queryStart < 0 ? "" : url.href.slice(queryStart);
805
+ const pathname = isPath ? absolutePathKey(url.pathname) : void 0;
806
+ const uri = pathname === void 0 ? url.href : pathname + query;
807
+ const pathWithoutLeadingSlash = pathname?.slice(1);
808
+ const drivePath = pathWithoutLeadingSlash !== void 0 && (isAbsoluteWindowsPath || base.isWindowsPath) && WINDOWS_DRIVE_PATH.test(pathWithoutLeadingSlash) ? pathWithoutLeadingSlash : void 0;
809
+ const shareRoot = share ? absolutePathKey("//" + share[1] + "/" + share[2]) : drivePath !== void 0 && !windowsDrive ? base.shareRoot : void 0;
810
+ const resolvedPath = shareRoot && drivePath ? shareRoot + drivePath.slice(2) : drivePath;
811
+ const keys = resolvedPath === void 0 ? [uri] : [resolvedPath + query, resolvedPath.replaceAll("/", "\\") + query];
812
+ return { uri: keys[0], fragment, keys, location: { url, isPath, isWindowsPath: drivePath !== void 0, shareRoot } };
813
+ }
814
+ var EXAMPLE_FIELDS = /* @__PURE__ */ new Set(["value", "externalValue", "summary", "description"]);
815
+ function isStandaloneExample(value) {
816
+ return typeof value === "object" && value !== null && !Array.isArray(value) && (Object.hasOwn(value, "value") || Object.hasOwn(value, "externalValue")) && Object.keys(value).every((key) => EXAMPLE_FIELDS.has(key) || key.startsWith("x-"));
817
+ }
818
+ function restoreReferenceCopies(document, { field, targets, originals }) {
819
+ if (!originals.size) return;
820
+ const seen = /* @__PURE__ */ new WeakSet();
821
+ const pending = [document];
822
+ while (pending.length) {
823
+ const value = pending.pop();
824
+ if (typeof value !== "object" || value === null || seen.has(value)) continue;
825
+ seen.add(value);
826
+ if (Reflect.get(value, field) === targets) Reflect.deleteProperty(value, field);
827
+ if ("$ref" in value && typeof value.$ref === "string") {
828
+ const original = originals.get(value.$ref);
829
+ if (original !== void 0) value.$ref = original;
830
+ }
831
+ for (const child of Object.values(value)) pending.push(child);
832
+ }
833
+ }
834
+ function prepareReferences(document, externalReferences) {
835
+ const root = { value: document, location: workingDirectoryLocation() };
836
+ const supplied = /* @__PURE__ */ new Map();
837
+ const literalReferences = /* @__PURE__ */ new Map();
838
+ const seen = /* @__PURE__ */ new WeakMap();
839
+ const pending = [];
840
+ let field = "x-apifn-reference-copies";
841
+ while (Object.hasOwn(document, field)) field += "-";
842
+ const referenceCopies = { field, targets: [], originals: /* @__PURE__ */ new Map() };
843
+ const copiedPointers = /* @__PURE__ */ new Map();
844
+ const aliasTargets = /* @__PURE__ */ new WeakMap();
845
+ function errorAtReference(site, error) {
846
+ if (error instanceof ReferencePreparationError) return error;
847
+ return new ReferencePreparationError(site, error);
848
+ }
849
+ function enqueue(target) {
850
+ const { value, mode } = target;
851
+ if (typeof value !== "object" || value === null) return value;
852
+ const contexts = seen.get(value) ?? /* @__PURE__ */ new Map();
853
+ const existing = contexts.get(mode);
854
+ if (existing) return existing;
855
+ const prototype = Object.getPrototypeOf(value);
856
+ const copy2 = Array.isArray(value) ? [...value] : prototype === Object.prototype || prototype === null ? { ...value } : value;
857
+ contexts.set(mode, copy2);
858
+ seen.set(value, contexts);
859
+ pending.push({ ...target, value, copy: copy2 });
860
+ return copy2;
861
+ }
862
+ function location(source, ref) {
863
+ if (ref.startsWith("#") || source !== root && ref === "") return { source, fragment: ref.slice(1) };
864
+ if (!externalReferences?.size) throw new Error(EXTERNAL_REF_ERROR);
865
+ const { uri: key, fragment, keys, location: targetLocation } = resolveDocumentURI(source.location, ref);
866
+ let external = supplied.get(key);
867
+ if (!external) {
868
+ const contents = keys.map((candidate) => externalReferences.get(candidate)).find((value) => value !== void 0);
869
+ if (contents === void 0) throw new Error(EXTERNAL_REF_ERROR);
870
+ external = { value: parsePreloadedDocument(contents), location: targetLocation };
871
+ supplied.set(key, external);
872
+ }
873
+ return { source: external, fragment };
874
+ }
875
+ function pointerTarget(source, tokens, { aliases = /* @__PURE__ */ new Set(), directAlias, importSite: outerSite }) {
876
+ let value = source.value;
877
+ let mode = "node";
878
+ let path;
879
+ let importSite;
880
+ let throughLiteralAlias = false;
881
+ const matched = [];
882
+ const unresolved = (index, target) => ({ tokens: [...matched, ...tokens.slice(index)], target });
883
+ for (let index = 0; index < tokens.length; index += 1) {
884
+ const chain = new Set(aliases);
885
+ const overrides = /* @__PURE__ */ new Map();
886
+ while (typeof value === "object" && value !== null && "$ref" in value && typeof value.$ref === "string" && (value.$ref || source !== root)) {
887
+ if (mode === "literal") {
888
+ if (source !== root || !value.$ref.startsWith("#") || pointerMember(value, tokens, index)) break;
889
+ throughLiteralAlias = true;
890
+ }
891
+ if (chain.has(value)) {
892
+ if (value === directAlias || Object.hasOwn(value, tokens[index])) break;
893
+ throw new Error("Circular OpenAPI $ref aliases cannot be traversed");
894
+ }
895
+ chain.add(value);
896
+ let target = aliasTargets.get(value);
897
+ if (!target) {
898
+ const site = source === root ? { path } : importSite ?? outerSite;
899
+ let lookup;
900
+ try {
901
+ const alias = location(source, value.$ref);
902
+ lookup = lookupPointer(alias.source, alias.fragment, { aliases: chain, directAlias: value, importSite: site });
903
+ } catch (error) {
904
+ throw errorAtReference(site?.path, error);
905
+ }
906
+ if (!lookup.target || lookup.target === "reference") return unresolved(index, "reference");
907
+ target = lookup.target;
908
+ aliasTargets.set(value, target);
909
+ }
910
+ if (target.value === value) break;
911
+ for (const [key2, sibling2] of Object.entries(value)) {
912
+ if (key2 !== "$ref" && !overrides.has(key2)) {
913
+ overrides.set(key2, { value: sibling2, mode: referenceChildMode(value, mode, key2, sibling2), source, path, importSite });
914
+ }
915
+ }
916
+ if ((mode === "node" || mode === "literal") && target.mode !== "literal") mode = target.mode;
917
+ const aliasSite = source === root ? { path } : importSite;
918
+ source = target.source;
919
+ importSite = source === root ? void 0 : target.importSite ?? aliasSite;
920
+ path = target.path;
921
+ value = target.value;
922
+ }
923
+ if (typeof value !== "object" || value === null) return unresolved(index);
924
+ const parent = overrides.size ? { ...value, ...Object.fromEntries([...overrides].map(([key2, entry]) => [key2, entry.value])) } : value;
925
+ if (source !== root && mode === "node" && isStandaloneExample(parent)) mode = "example";
926
+ const member = pointerMember(parent, tokens, index);
927
+ if (!member) {
928
+ if (value === root.value && tokens[index] === field) throw new Error("OpenAPI $ref target does not exist");
929
+ return unresolved(index);
930
+ }
931
+ const { key } = member;
932
+ index = member.index;
933
+ matched.push(key);
934
+ const child = Reflect.get(parent, key);
935
+ const sibling = overrides.get(key);
936
+ if (sibling) {
937
+ source = sibling.source;
938
+ importSite = sibling.importSite;
939
+ }
940
+ path = { key, parent: sibling ? sibling.path : path };
941
+ mode = sibling?.mode ?? referenceChildMode(parent, mode, key, child);
942
+ value = child;
943
+ }
944
+ return { tokens: matched, target: { value, mode, source, path, importSite }, throughLiteralAlias };
945
+ }
946
+ function lookupPointer(source, fragment, options = {}) {
947
+ if (fragment === "") return { tokens: [], target: { value: source.value, mode: "node", source } };
948
+ if (fragment.startsWith("/")) {
949
+ const legacy = fragment.split("/").slice(1).map((token) => source === root ? decodeFragment(unescapePointerToken(token)) : unescapePointerToken(decodeFragment(token)));
950
+ const legacyLookup = pointerTarget(source, legacy, options);
951
+ if (legacyLookup.target || !/%2f/i.test(fragment)) return legacyLookup;
952
+ const decoded2 = decodeFragment(fragment).split("/").slice(1).map(unescapePointerToken);
953
+ const decodedLookup = pointerTarget(source, decoded2, options);
954
+ return decodedLookup.target ? decodedLookup : legacyLookup;
955
+ }
956
+ const decoded = decodeFragment(fragment);
957
+ if (!decoded.startsWith("/") || source !== root && !fragment.startsWith("/")) {
958
+ throw new Error("OpenAPI $ref fragments must be slash-delimited JSON pointers");
959
+ }
960
+ const tokens = decoded.split("/").slice(1).map(unescapePointerToken);
961
+ return pointerTarget(source, tokens, options);
962
+ }
963
+ function rewriteReference(ref, { source, mode, value }, site) {
964
+ const destination = location(source, ref);
965
+ const { tokens, target, throughLiteralAlias } = lookupPointer(destination.source, destination.fragment, { importSite: site });
966
+ const canonical = encodePointer(tokens);
967
+ const isLocal = destination.source === root;
968
+ if (!target || target === "reference") {
969
+ if (isLocal) return canonical;
970
+ throw new Error("OpenAPI $ref target does not exist");
971
+ }
972
+ if (source !== root && target.source === source && target.value === value) {
973
+ throw new Error("Preloaded OpenAPI $ref must point to a different location");
974
+ }
975
+ if (isLocal && target.source === root && (target.mode !== "literal" || typeof target.value !== "object" || target.value === null)) {
976
+ return throughLiteralAlias ? encodePointer(pathKeys(target.path)) : canonical;
977
+ }
978
+ const pointers = copiedPointers.get(destination.source) ?? /* @__PURE__ */ new Map();
979
+ const key = mode + canonical;
980
+ let preparedRef = pointers.get(key);
981
+ if (!preparedRef) {
982
+ const targetIndex = String(referenceCopies.targets.length);
983
+ preparedRef = "#/" + field + "/" + targetIndex;
984
+ pointers.set(key, preparedRef);
985
+ copiedPointers.set(destination.source, pointers);
986
+ referenceCopies.originals.set(preparedRef, isLocal ? canonical : ref);
987
+ referenceCopies.targets.push(enqueue({ ...target, mode, importSite: target.importSite ?? site }));
988
+ }
989
+ if (target.source !== root && Object.keys(value).length > 1) {
990
+ const alias = "#/" + field + "/" + referenceCopies.targets.length;
991
+ referenceCopies.targets.push({ $ref: preparedRef });
992
+ referenceCopies.originals.set(alias, isLocal ? canonical : ref);
993
+ return alias;
994
+ }
995
+ return preparedRef;
996
+ }
997
+ const copy = enqueue({ value: root.value, mode: "node", source: root });
998
+ while (pending.length) {
999
+ const current = pending.pop();
1000
+ const { value, copy: copy2, mode, source, path, importSite } = current;
1001
+ if ("$ref" in value && typeof value.$ref === "string") {
1002
+ if (mode === "literal") {
1003
+ literalReferences.set(copy2, value.$ref);
1004
+ Reflect.deleteProperty(copy2, "$ref");
1005
+ } else if (value.$ref || source !== root) {
1006
+ const site = source === root ? { path } : importSite;
1007
+ try {
1008
+ Reflect.set(copy2, "$ref", rewriteReference(value.$ref, current, site));
1009
+ } catch (error) {
1010
+ throw errorAtReference(site?.path, error);
1011
+ }
1012
+ }
1013
+ }
1014
+ for (const [key, child] of Object.entries(value)) {
1015
+ if (key === "$ref" && typeof child === "string") continue;
1016
+ Reflect.set(copy2, key, enqueue({
1017
+ value: child,
1018
+ mode: referenceChildMode(value, mode, key, child),
1019
+ source,
1020
+ path: { key, parent: path },
1021
+ importSite
1022
+ }));
1023
+ }
1024
+ }
1025
+ if (referenceCopies.targets.length) Reflect.set(copy, field, referenceCopies.targets);
1026
+ return { copy, referenceCopies, literalReferences };
1027
+ }
677
1028
  function toValidationErrors(error) {
678
1029
  const details = error?.details;
679
1030
  if (Array.isArray(details) && details.length > 0) {
@@ -686,18 +1037,29 @@ function toValidationErrors(error) {
686
1037
  const message = error instanceof Error ? error.message : "Validation error";
687
1038
  return [
688
1039
  {
689
- path: "openapi",
1040
+ path: error instanceof ReferencePreparationError ? error.path : "openapi",
690
1041
  message,
691
1042
  severity: "error"
692
1043
  }
693
1044
  ];
694
1045
  }
695
- async function validateOpenAPI(document) {
1046
+ async function validateOpenAPI(document, options) {
1047
+ return (await validateAndDereferenceOpenAPI(document, options)).errors;
1048
+ }
1049
+ async function validateAndDereferenceOpenAPI(document, options) {
696
1050
  try {
697
- await SwaggerParser.validate(document);
698
- return [];
1051
+ const { copy, referenceCopies, literalReferences } = prepareReferences(
1052
+ structuredClone(document),
1053
+ options?.externalReferences
1054
+ );
1055
+ const validated = await SwaggerParser.validate("/apifn-validation/openapi.json", copy, {
1056
+ resolve: { external: false, file: false, http: false }
1057
+ });
1058
+ restoreReferenceCopies(validated, referenceCopies);
1059
+ for (const [literal, ref] of literalReferences) Reflect.set(literal, "$ref", ref);
1060
+ return { document: validated, errors: [] };
699
1061
  } catch (error) {
700
- return toValidationErrors(error);
1062
+ return { document: null, errors: toValidationErrors(error) };
701
1063
  }
702
1064
  }
703
1065
 
@@ -1279,11 +1641,11 @@ function apifnWatchMiddleware(options) {
1279
1641
  const r = req;
1280
1642
  const s = res;
1281
1643
  const method = r.method ?? "UNKNOWN";
1282
- const path2 = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1644
+ const path = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1283
1645
  const statusCode = s.statusCode ?? 200;
1284
1646
  const event = {
1285
1647
  method,
1286
- path: path2,
1648
+ path,
1287
1649
  status_code: statusCode,
1288
1650
  duration_ms: durationMs,
1289
1651
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -1436,172 +1798,7 @@ function createCliLogger(options = {}) {
1436
1798
  }
1437
1799
  };
1438
1800
  }
1439
-
1440
- // src/integrations/testfn.ts
1441
- import * as path from "path";
1442
- import * as fs from "fs";
1443
- import { BaseAdapter } from "@testfn/core";
1444
- var ApifnTestAdapter = class extends BaseAdapter {
1445
- name = "apifn";
1446
- supports(framework) {
1447
- return framework.toLowerCase() === "apifn";
1448
- }
1449
- async discover(patterns) {
1450
- let glob;
1451
- try {
1452
- const fg = await import("./out-X7U3YPXW.js");
1453
- glob = fg.default ?? fg;
1454
- } catch {
1455
- console.warn("[apifn/testfn] fast-glob not found, using basic fs discovery");
1456
- }
1457
- const { readCollection } = await import("@apifn/collections");
1458
- const testCases = [];
1459
- const discoveredDirs = /* @__PURE__ */ new Set();
1460
- for (const pattern of patterns) {
1461
- if (glob) {
1462
- const files = await glob(
1463
- pattern.endsWith(".yml") || pattern.endsWith(".yaml") ? pattern : `${pattern}/**/opencollection.yml`,
1464
- { absolute: true }
1465
- );
1466
- for (const f of files) {
1467
- discoveredDirs.add(path.dirname(f));
1468
- }
1469
- } else {
1470
- try {
1471
- if (fs.existsSync(pattern)) {
1472
- const stat = fs.statSync(pattern);
1473
- if (stat.isDirectory()) {
1474
- if (fs.existsSync(path.join(pattern, "opencollection.yml"))) {
1475
- discoveredDirs.add(pattern);
1476
- }
1477
- } else if (pattern.endsWith("opencollection.yml")) {
1478
- discoveredDirs.add(path.dirname(pattern));
1479
- }
1480
- }
1481
- } catch {
1482
- }
1483
- }
1484
- }
1485
- for (const dir of discoveredDirs) {
1486
- try {
1487
- const collection = await readCollection(dir);
1488
- const walk = (items, suitePath) => {
1489
- for (const item of items) {
1490
- if (item.kind === "request") {
1491
- const suiteName = suitePath.length > 0 ? suitePath.join(" > ") : collection.info.name;
1492
- testCases.push({
1493
- id: this.generateTestId(dir, item.name, suiteName),
1494
- file: dir,
1495
- name: item.name,
1496
- suite: suiteName,
1497
- tags: ["api"]
1498
- });
1499
- } else if (item.kind === "folder" && item.children) {
1500
- walk(item.children, [...suitePath, item.name]);
1501
- }
1502
- }
1503
- };
1504
- walk(collection.items, []);
1505
- } catch (err) {
1506
- console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);
1507
- }
1508
- }
1509
- return testCases;
1510
- }
1511
- async run(tests, options) {
1512
- const { runCollection, readCollection } = await import("@apifn/collections");
1513
- const results = [];
1514
- const collectionsToRun = /* @__PURE__ */ new Map();
1515
- for (const t of tests) {
1516
- const list = collectionsToRun.get(t.file) || [];
1517
- list.push(t);
1518
- collectionsToRun.set(t.file, list);
1519
- }
1520
- let completedCount = 0;
1521
- const updateProgress = (tc) => {
1522
- completedCount++;
1523
- options.onProgress?.({
1524
- completed: completedCount,
1525
- total: tests.length,
1526
- current: tc
1527
- });
1528
- };
1529
- for (const [dir, testsInCollection] of collectionsToRun.entries()) {
1530
- try {
1531
- const collection = await readCollection(dir);
1532
- const report = await runCollection(collection, {
1533
- // Default to the first environment or a dummy one if none exists
1534
- environment: Object.keys(collection.environments)[0] ?? "default",
1535
- parallel: options.parallel !== void 0 && options.parallel > 1,
1536
- concurrency: typeof options.parallel === "number" ? options.parallel : void 0,
1537
- timeout: options.timeout,
1538
- retries: options.retries,
1539
- overrides: options.env
1540
- });
1541
- for (const reqRes of report.results) {
1542
- const matchedTests = testsInCollection.filter((t) => t.name === reqRes.name);
1543
- for (const tc of matchedTests) {
1544
- let status = "passed";
1545
- let testError;
1546
- if (reqRes.status === "failed" || reqRes.status === "error") {
1547
- status = "failed";
1548
- if (reqRes.status === "failed") {
1549
- const failedAsserts = reqRes.assertions.filter((a) => !a.passed);
1550
- const msg = failedAsserts.map((a) => `- ${a.name}`).join("\n");
1551
- testError = {
1552
- message: `Assertions failed:
1553
- ${msg}`
1554
- };
1555
- } else if (reqRes.status === "error") {
1556
- testError = {
1557
- message: reqRes.error || "Unknown Request Error",
1558
- actual: reqRes.statusCode
1559
- };
1560
- }
1561
- } else if (reqRes.status === "skipped") {
1562
- status = "skipped";
1563
- }
1564
- results.push({
1565
- id: tc.id,
1566
- status,
1567
- duration: reqRes.duration,
1568
- error: testError
1569
- });
1570
- updateProgress(tc);
1571
- }
1572
- }
1573
- const runTestNames = new Set(report.results.map((r) => r.name));
1574
- for (const tc of testsInCollection) {
1575
- if (!runTestNames.has(tc.name)) {
1576
- results.push({
1577
- id: tc.id,
1578
- status: "skipped",
1579
- duration: 0,
1580
- error: { message: "Test not found or excluded in collection run" }
1581
- });
1582
- updateProgress(tc);
1583
- }
1584
- }
1585
- } catch (err) {
1586
- for (const tc of testsInCollection) {
1587
- results.push({
1588
- id: tc.id,
1589
- status: "failed",
1590
- duration: 0,
1591
- error: {
1592
- message: err instanceof Error ? err.message : String(err),
1593
- stack: err instanceof Error ? err.stack : void 0
1594
- }
1595
- });
1596
- updateProgress(tc);
1597
- }
1598
- }
1599
- }
1600
- return results;
1601
- }
1602
- };
1603
1801
  export {
1604
- ApifnTestAdapter,
1605
1802
  apiSchema,
1606
1803
  apifnWatchMiddleware,
1607
1804
  convertSchema,
@@ -1624,6 +1821,7 @@ export {
1624
1821
  mintTestToken,
1625
1822
  parseOpenAPI,
1626
1823
  upconvertFrom3_0,
1824
+ validateAndDereferenceOpenAPI,
1627
1825
  validateOpenAPI
1628
1826
  };
1629
1827
  //# sourceMappingURL=index.js.map