@apifn/core 0.1.0 → 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/README.md +12 -1
- package/dist/chunk-NWH3AIKS.js +68 -0
- package/dist/chunk-NWH3AIKS.js.map +1 -0
- package/dist/index.cjs +432 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -2
- package/dist/index.d.ts +19 -2
- package/dist/index.js +368 -5
- package/dist/index.js.map +1 -1
- package/dist/openapi-reference-context.cjs +92 -0
- package/dist/openapi-reference-context.cjs.map +1 -0
- package/dist/openapi-reference-context.d.cts +24 -0
- package/dist/openapi-reference-context.d.ts +24 -0
- package/dist/openapi-reference-context.js +8 -0
- package/dist/openapi-reference-context.js.map +1 -0
- package/dist/testfn.cjs +85 -25
- package/dist/testfn.cjs.map +1 -1
- package/dist/testfn.d.cts +9 -1
- package/dist/testfn.d.ts +9 -1
- package/dist/testfn.js +85 -25
- package/dist/testfn.js.map +1 -1
- package/package.json +12 -2
package/dist/index.d.cts
CHANGED
|
@@ -33,7 +33,24 @@ declare function fromRouter(router: Router<unknown>, options: FromRouterOptions)
|
|
|
33
33
|
|
|
34
34
|
declare function parseOpenAPI(input: string | Record<string, unknown>): OpenAPIDocument;
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
interface OpenAPIValidationOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Preloaded JSON or YAML for external documents, keyed by the resolved URI or
|
|
39
|
+
* absolute file path, without a fragment. Escape literal `%`, `?`, and `\\`
|
|
40
|
+
* within path segments as `%25`, `%3F`, and `%5C`. Within preloaded documents, use slash-delimited
|
|
41
|
+
* `#/` pointers. Validation never reads files or URLs.
|
|
42
|
+
*/
|
|
43
|
+
externalReferences?: ReadonlyMap<string, string>;
|
|
44
|
+
}
|
|
45
|
+
declare function validateOpenAPI(document: OpenAPIDocument, options?: OpenAPIValidationOptions): Promise<ValidationError[]>;
|
|
46
|
+
/** Validates and returns a dereferenced copy for callers that compare or store it. */
|
|
47
|
+
declare function validateAndDereferenceOpenAPI(document: OpenAPIDocument, options?: OpenAPIValidationOptions): Promise<{
|
|
48
|
+
document: OpenAPIDocument;
|
|
49
|
+
errors: [];
|
|
50
|
+
} | {
|
|
51
|
+
document: null;
|
|
52
|
+
errors: ValidationError[];
|
|
53
|
+
}>;
|
|
37
54
|
|
|
38
55
|
declare function upconvertFrom3_0(document: unknown): OpenAPIDocument;
|
|
39
56
|
|
|
@@ -260,4 +277,4 @@ interface CliLoggerOptions {
|
|
|
260
277
|
*/
|
|
261
278
|
declare function createCliLogger(options?: CliLoggerOptions): LogFnClient;
|
|
262
279
|
|
|
263
|
-
export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
|
|
280
|
+
export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, type OpenAPIValidationOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateAndDereferenceOpenAPI, validateOpenAPI };
|
package/dist/index.d.ts
CHANGED
|
@@ -33,7 +33,24 @@ declare function fromRouter(router: Router<unknown>, options: FromRouterOptions)
|
|
|
33
33
|
|
|
34
34
|
declare function parseOpenAPI(input: string | Record<string, unknown>): OpenAPIDocument;
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
interface OpenAPIValidationOptions {
|
|
37
|
+
/**
|
|
38
|
+
* Preloaded JSON or YAML for external documents, keyed by the resolved URI or
|
|
39
|
+
* absolute file path, without a fragment. Escape literal `%`, `?`, and `\\`
|
|
40
|
+
* within path segments as `%25`, `%3F`, and `%5C`. Within preloaded documents, use slash-delimited
|
|
41
|
+
* `#/` pointers. Validation never reads files or URLs.
|
|
42
|
+
*/
|
|
43
|
+
externalReferences?: ReadonlyMap<string, string>;
|
|
44
|
+
}
|
|
45
|
+
declare function validateOpenAPI(document: OpenAPIDocument, options?: OpenAPIValidationOptions): Promise<ValidationError[]>;
|
|
46
|
+
/** Validates and returns a dereferenced copy for callers that compare or store it. */
|
|
47
|
+
declare function validateAndDereferenceOpenAPI(document: OpenAPIDocument, options?: OpenAPIValidationOptions): Promise<{
|
|
48
|
+
document: OpenAPIDocument;
|
|
49
|
+
errors: [];
|
|
50
|
+
} | {
|
|
51
|
+
document: null;
|
|
52
|
+
errors: ValidationError[];
|
|
53
|
+
}>;
|
|
37
54
|
|
|
38
55
|
declare function upconvertFrom3_0(document: unknown): OpenAPIDocument;
|
|
39
56
|
|
|
@@ -260,4 +277,4 @@ interface CliLoggerOptions {
|
|
|
260
277
|
*/
|
|
261
278
|
declare function createCliLogger(options?: CliLoggerOptions): LogFnClient;
|
|
262
279
|
|
|
263
|
-
export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
|
|
280
|
+
export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, type OpenAPIValidationOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateAndDereferenceOpenAPI, validateOpenAPI };
|
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
|
|
@@ -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
|
-
|
|
698
|
-
|
|
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
|
|
|
@@ -1459,6 +1821,7 @@ export {
|
|
|
1459
1821
|
mintTestToken,
|
|
1460
1822
|
parseOpenAPI,
|
|
1461
1823
|
upconvertFrom3_0,
|
|
1824
|
+
validateAndDereferenceOpenAPI,
|
|
1462
1825
|
validateOpenAPI
|
|
1463
1826
|
};
|
|
1464
1827
|
//# sourceMappingURL=index.js.map
|