diff --git a/sdk/src/polyfill/fetch.ts b/sdk/src/polyfill/fetch.ts index 76ab149b2..8a26d272a 100644 --- a/sdk/src/polyfill/fetch.ts +++ b/sdk/src/polyfill/fetch.ts @@ -5,7 +5,9 @@ import $mime from "mime/lite"; const oldFetch = globalThis.fetch; -async function supportsFetch() { +let supports: Promise | null = null; + +async function checkFetch() { try { await oldFetch(new URL("file:")); return true; @@ -15,33 +17,39 @@ async function supportsFetch() { } } +async function supportsFetch(): Promise { + if (supports === null) { + supports = checkFetch(); + } -if (!(await supportsFetch())) { - // We always polyfill fetch because Node's fetch doesn't support file URLs. - (globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise { - const request = new Request(resource, options); + return await supports; +} - const url = new URL(request.url); - if (url.protocol === "file:") { - const readStream = $fs.createReadStream(url); +// We always polyfill fetch because Node's fetch doesn't support file URLs. +(globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise { + const request = new Request(resource, options); - const headers: HeadersInit = {}; + const url = new URL(request.url); - const type = $mime.getType(url.pathname); + if (!(await supportsFetch()) && url.protocol === "file:") { + const readStream = $fs.createReadStream(url); - if (type) { - headers["Content-Type"] = type; - } + const headers: HeadersInit = {}; - return new Response(readStream as any, { - status: 200, - statusText: "OK", - headers, - }); + const type = $mime.getType(url.pathname); - } else { - return await oldFetch(request); + if (type) { + headers["Content-Type"] = type; } - }; -} + + return new Response(readStream as any, { + status: 200, + statusText: "OK", + headers, + }); + + } else { + return await oldFetch(request); + } +};