From ba7d210dc2d5a91ac1dd4ded294d3d1e4a7b5314 Mon Sep 17 00:00:00 2001 From: "joey.ren.huang" Date: Thu, 28 Dec 2023 12:00:26 +0800 Subject: [PATCH] fetch wasm file should append baseUrl base on currenScript running env --- src/wasm-helper.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/wasm-helper.ts b/src/wasm-helper.ts index d94db79..07a7685 100644 --- a/src/wasm-helper.ts +++ b/src/wasm-helper.ts @@ -30,7 +30,22 @@ const wasmHelper = async (opts = {}, url: string) => { // a lot of static file servers, so we just work around it by getting the // raw buffer. // @ts-ignore - const response = await fetch(url); + const getBaseUrl = () => { + const currentScriptUrl = getRunningScript()() + if (!currentScriptUrl) return '' + let baseUrl = '' + try { + baseUrl = new URL(currentScriptUrl).origin + } catch(err){} + return baseUrl + } + const getRunningScript = ()=>{ + return ()=>{ + return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)?.[0] + } + } + const baseUrl = typeof window !== 'undefined' ? getBaseUrl() : '' + const response = await fetch(baseUrl + url); const contentType = response.headers.get("Content-Type") || ""; if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) { result = await WebAssembly.instantiateStreaming(response, opts);