|
1 | | -import { createWasiImports } from "./automate_packed/host_shim.mjs"; |
| 1 | +function createImportValue(entry, memoryRef, outputCallback) { |
| 2 | + if (entry.kind === "function") { |
| 3 | + return () => 0; |
| 4 | + } |
| 5 | + if (entry.kind === "memory") { |
| 6 | + const memory = new WebAssembly.Memory({ initial: 16 }); |
| 7 | + memoryRef.current = memory; |
| 8 | + return memory; |
| 9 | + } |
| 10 | + if (entry.kind === "table") { |
| 11 | + return new WebAssembly.Table({ initial: 0, element: "anyfunc" }); |
| 12 | + } |
| 13 | + if (entry.kind === "global") { |
| 14 | + return new WebAssembly.Global({ value: "i32", mutable: true }, 0); |
| 15 | + } |
| 16 | + outputCallback(`Unsupported WASM import kind: ${entry.kind}`); |
| 17 | + return undefined; |
| 18 | +} |
| 19 | + |
| 20 | +function createImportObject(module, memoryRef, outputCallback) { |
| 21 | + const imports = {}; |
| 22 | + for (const entry of WebAssembly.Module.imports(module)) { |
| 23 | + if (!imports[entry.module]) { |
| 24 | + imports[entry.module] = {}; |
| 25 | + } |
| 26 | + imports[entry.module][entry.name] = createImportValue(entry, memoryRef, outputCallback); |
| 27 | + } |
| 28 | + return imports; |
| 29 | +} |
2 | 30 |
|
3 | 31 | export async function loadAutomaginariumPacked(options = {}) { |
4 | 32 | const wasmUrl = options.wasmUrl || new URL("./automate_packed/module.wasm", import.meta.url); |
5 | 33 | const memoryRef = { current: null }; |
6 | | - const imports = { |
7 | | - ...createWasiImports(memoryRef, options.outputCallback || (() => {})), |
8 | | - }; |
| 34 | + const outputCallback = options.outputCallback || (() => {}); |
9 | 35 |
|
10 | | - let instance; |
| 36 | + let module; |
11 | 37 | if (options.bytes) { |
12 | | - const result = await WebAssembly.instantiate(options.bytes, imports); |
13 | | - instance = result.instance; |
14 | | - } else if (typeof WebAssembly.instantiateStreaming === "function") { |
15 | | - const result = await WebAssembly.instantiateStreaming(fetch(wasmUrl), imports); |
16 | | - instance = result.instance; |
| 38 | + module = await WebAssembly.compile(options.bytes); |
17 | 39 | } else { |
18 | 40 | const response = await fetch(wasmUrl); |
19 | 41 | const bytes = await response.arrayBuffer(); |
20 | | - const result = await WebAssembly.instantiate(bytes, imports); |
21 | | - instance = result.instance; |
| 42 | + module = await WebAssembly.compile(bytes); |
22 | 43 | } |
23 | 44 |
|
| 45 | + const imports = createImportObject(module, memoryRef, outputCallback); |
| 46 | + const instance = await WebAssembly.instantiate(module, imports); |
24 | 47 | memoryRef.current = instance.exports.memory || memoryRef.current; |
25 | 48 | return instance.exports; |
26 | 49 | } |
|
0 commit comments