Skip to content

Commit d0a43d4

Browse files
fix: enhance WASM loading logic to support multiple paths and improve error handling
1 parent 6cf6d10 commit d0a43d4

1 file changed

Lines changed: 28 additions & 23 deletions

File tree

examples/react-demo/src/wasmLoader.ts

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -77,45 +77,50 @@ export async function loadWasm(): Promise<WasmExports> {
7777
}
7878

7979
loadingPromise = (async () => {
80-
// Use relative path that works in both local dev and StackBlitz
81-
// Try multiple paths to handle different environments
80+
// Try multiple paths to handle different environments (local dev, StackBlitz, production)
8281
const possiblePaths = [
83-
new URL('/compute.wasm', import.meta.url).href,
84-
new URL('../public/compute.wasm', import.meta.url).href,
8582
'/compute.wasm',
83+
'./compute.wasm',
84+
new URL('/compute.wasm', import.meta.url).href,
8685
];
8786

88-
let response: Response | null = null;
89-
let lastError: Error | null = null;
87+
let arrayBuffer: ArrayBuffer | null = null;
88+
let lastError: string = '';
9089

9190
for (const wasmUrl of possiblePaths) {
9291
try {
9392
const res = await fetch(wasmUrl);
94-
// Check if we got a valid WASM response (not an HTML fallback)
95-
const contentType = res.headers.get('content-type') || '';
96-
if (res.ok && !contentType.includes('text/html')) {
97-
response = res;
93+
if (!res.ok) {
94+
lastError = `${wasmUrl}: ${res.status} ${res.statusText}`;
95+
continue;
96+
}
97+
98+
const buffer = await res.arrayBuffer();
99+
// Check for WASM magic number (0x00 0x61 0x73 0x6D = "\0asm")
100+
const magic = new Uint8Array(buffer.slice(0, 4));
101+
if (
102+
magic[0] === 0x00 &&
103+
magic[1] === 0x61 &&
104+
magic[2] === 0x73 &&
105+
magic[3] === 0x6d
106+
) {
107+
arrayBuffer = buffer;
98108
break;
109+
} else {
110+
lastError = `${wasmUrl}: Invalid WASM (got ${Array.from(magic)
111+
.map((b) => b.toString(16))
112+
.join(' ')})`;
99113
}
100114
} catch (e) {
101-
lastError = e as Error;
115+
lastError = `${wasmUrl}: ${(e as Error).message}`;
102116
}
103117
}
104118

105-
if (!response) {
106-
throw new Error(
107-
`Failed to fetch WASM from any path. Last error: ${lastError?.message}`
108-
);
119+
if (!arrayBuffer) {
120+
throw new Error(`Failed to fetch WASM from any path. Last error: ${lastError}`);
109121
}
110122

111-
const module = await WebAssembly.compileStreaming(
112-
// Create a new Response with the correct MIME type if needed
113-
response.headers.get('content-type')?.includes('application/wasm')
114-
? response
115-
: new Response(await response.arrayBuffer(), {
116-
headers: { 'Content-Type': 'application/wasm' },
117-
})
118-
);
123+
const module = await WebAssembly.compile(arrayBuffer);
119124
cachedExports = await instantiate(module, {});
120125
return cachedExports;
121126
})();

0 commit comments

Comments
 (0)