| 9 | const ERR_RUNTIME = 2; // wasm-abi/src/lib.rs error_kind::RUNTIME |
| 10 | |
| 11 | export function makeCompilerEnv({ getExports, onLine, fetchedSources, lockfile, integrityActive, rt, captureHostCall }) { |
| 12 | const readStr = (ptr, len) => TD.decode(new Uint8Array(getExports().memory.buffer, ptr, len)); |
| 13 | const setU32 = (ptr, v) => new DataView(getExports().memory.buffer).setUint32(ptr, v, true); |
| 14 | |
| 15 | return { |
| 16 | host_print: (ptr, len) => onLine(readStr(ptr, len)), |
| 17 | |
| 18 | /* wasmpdk stages argv in guest memory; capability calls a JS handler directly. */ |
| 19 | host_call_native: (id, call_id, argv_ptr, argc, out_ptr) => { |
| 20 | const fn = nativeTable[id]; |
| 21 | if (!fn) { |
| 22 | stashError(getExports(), `native id ${id} not registered`); |
| 23 | return 1; |
| 24 | } |
| 25 | |
| 26 | const exports = getExports(); |
| 27 | |
| 28 | if (fn.__edge_kind === 'capability') { |
| 29 | /* Host appends a trailing kwargs handle (0 = no kwargs); JS capabilities don't model kwargs so drop it. */ |
| 30 | const handles = Array.from(new Uint32Array(exports.memory.buffer, argv_ptr, Math.max(0, argc - 1))); |
| 31 | /* Marked main-thread: decode args to JS, defer via captureHostCall; driver wakes us with set_host_result_by_id. */ |
| 32 | if (fn.__edge_main_thread) { |
| 33 | if (!captureHostCall || !rt) { |
| 34 | stashError(exports, `native '${fn.__edge_module}.${fn.__edge_name}' marked main-thread but no host-call delegate wired`); |
| 35 | return 1; |
| 36 | } |
| 37 | try { |
| 38 | const args = handles.map((h) => rt.decodeAny(h)); |
| 39 | captureHostCall(call_id, { module: fn.__edge_module, name: fn.__edge_name, args }); |
| 40 | return 2; |
| 41 | } catch (e) { |
| 42 | stashError(exports, e?.message ?? String(e)); |
| 43 | return 1; |
| 44 | } |
| 45 | } |
| 46 | try { |
| 47 | const resultHandle = fn(handles); |
| 48 | new DataView(exports.memory.buffer).setUint32(out_ptr, resultHandle, true); |
| 49 | return 0; |
| 50 | } catch (e) { |
| 51 | stashError(exports, e?.message ?? String(e)); |
| 52 | return 1; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // wasmpdk: stage argv, call, copy back. Views as fns because `fn(...)` can re-enter `wasm_alloc` and detach a cached view. |
| 57 | const guestView = () => new DataView(fn.__edge_memory.buffer); |
| 58 | const compView = () => new DataView(exports.memory.buffer); |
| 59 | |
| 60 | const g_argv = fn.__edge_alloc(Math.max(4, argc * 4)); |
| 61 | const g_out = fn.__edge_alloc(4); |
| 62 | for (let i = 0; i < argc; i++) { |
| 63 | guestView().setUint32(g_argv + i * 4, compView().getUint32(argv_ptr + i * 4, true), true); |
| 64 | } |
| 65 | |
| 66 | const status = fn(g_argv, argc, g_out); |
| 67 | if (status === 0) { |
| 68 | compView().setUint32(out_ptr, guestView().getUint32(g_out, true), true); |