|
1 | | -import { createDomImports, createWasiImports } from "./automate_packed/host_shim.mjs"; |
| 1 | +import * as hostShim from "./automate_packed/host_shim.mjs"; |
| 2 | + |
| 3 | +function createFallbackWasiImports(memoryRef = { current: null }, outputCallback = () => {}) { |
| 4 | + const textDecoder = new TextDecoder("utf-8"); |
| 5 | + let stdoutBuffer = ""; |
| 6 | + const writeOutput = () => { |
| 7 | + let newlineIndex; |
| 8 | + while ((newlineIndex = stdoutBuffer.indexOf("\n")) !== -1) { |
| 9 | + outputCallback(stdoutBuffer.slice(0, newlineIndex)); |
| 10 | + stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1); |
| 11 | + } |
| 12 | + }; |
| 13 | + |
| 14 | + return { |
| 15 | + wasi_snapshot_preview1: { |
| 16 | + fd_write(fd, iovsPtr, iovsLen, nwrittenPtr) { |
| 17 | + if (fd !== 1 && fd !== 2) return 8; |
| 18 | + const memory = memoryRef.current; |
| 19 | + if (!memory) return 8; |
| 20 | + const view = new DataView(memory.buffer); |
| 21 | + let written = 0; |
| 22 | + for (let index = 0; index < iovsLen; index += 1) { |
| 23 | + const ptr = view.getUint32(iovsPtr + index * 8, true); |
| 24 | + const len = view.getUint32(iovsPtr + index * 8 + 4, true); |
| 25 | + stdoutBuffer += textDecoder.decode(new Uint8Array(memory.buffer, ptr, len)); |
| 26 | + written += len; |
| 27 | + } |
| 28 | + writeOutput(); |
| 29 | + view.setUint32(nwrittenPtr, written, true); |
| 30 | + return 0; |
| 31 | + }, |
| 32 | + fd_read(_fd, _iovsPtr, _iovsLen, nreadPtr) { |
| 33 | + const memory = memoryRef.current; |
| 34 | + if (memory) { |
| 35 | + new DataView(memory.buffer).setUint32(nreadPtr, 0, true); |
| 36 | + } |
| 37 | + return 0; |
| 38 | + }, |
| 39 | + args_sizes_get(argcPtr, argvBufSizePtr) { |
| 40 | + const memory = memoryRef.current; |
| 41 | + if (!memory) return 8; |
| 42 | + const view = new DataView(memory.buffer); |
| 43 | + view.setUint32(argcPtr, 0, true); |
| 44 | + view.setUint32(argvBufSizePtr, 0, true); |
| 45 | + return 0; |
| 46 | + }, |
| 47 | + args_get() { |
| 48 | + return 0; |
| 49 | + }, |
| 50 | + }, |
| 51 | + memoryRef, |
| 52 | + }; |
| 53 | +} |
| 54 | + |
| 55 | +function createFallbackDomImports() { |
| 56 | + return { env: {} }; |
| 57 | +} |
2 | 58 |
|
3 | 59 | export async function loadAutomaginariumPacked(options = {}) { |
4 | 60 | const wasmUrl = options.wasmUrl || new URL("./automate_packed/module.wasm", import.meta.url); |
5 | 61 | const memoryRef = { current: null }; |
6 | 62 | const exportsRef = { current: null }; |
| 63 | + const createWasiImports = hostShim.createWasiImports || createFallbackWasiImports; |
| 64 | + const createDomImports = hostShim.createDomImports || createFallbackDomImports; |
7 | 65 | const imports = { |
8 | 66 | ...createWasiImports(memoryRef, options.outputCallback || (() => {})), |
9 | 67 | ...createDomImports(memoryRef, exportsRef), |
|
0 commit comments