import { readFile } from "node:fs/promises"; import { runModule } from "../../javascript/src/run-module/index.js"; export const did = "did:plc:lpfuqerea3deuoyrn7ojser4"; export const now = "2026-11-06T12:34:56.789Z"; /** A build at `url`; with `json` (its module.json's URL), handle() holds it to that file's calls and anyRecords. */ export async function load(url, json) { const module = new WebAssembly.Module(await readFile(url)); const { calls, anyRecords } = json ? JSON.parse(await readFile(json, "utf8")) : {}; const { exports } = new WebAssembly.Instance(module, {}); function run(entry, input) { const data = new TextEncoder().encode(JSON.stringify(input ?? null)); const ptr = exports.alloc(data.length); new Uint8Array(exports.memory.buffer, ptr, data.length).set(data); const packed = BigInt.asUintN(64, exports[entry](ptr, data.length)); const outPtr = Number(packed >> 32n); const outLen = Number(packed & 0xffffffffn); return JSON.parse(new TextDecoder().decode(new Uint8Array(exports.memory.buffer, outPtr, outLen))); } // The real host loop (runModule) over this module, with did and now fixed. // respond({ nsid, params, input, proxy, service, subscribe }) returns { ok, output } or { ok: false, error } // for a request; for a subscribe, the messages (an array, or any async iterable), after which the // subscription closes. Resolves to runModule's result plus sends: [{ nsid, data }] written up subscriptions. async function handle(entry, input, { respond, inputs, budget, signal } = {}) { const sends = []; const ctx = { wasm: { run: async ({ entry, input }) => run(entry, { ...input, now }) } }; const call = async (nsid, request) => { const answer = await respond({ nsid, ...request }); if (!request.subscribe) { if (answer?.ok === false) throw new Error(answer.error ?? "call failed"); return answer?.output; } return { [Symbol.asyncIterator]: async function* () { yield* answer; }, send: async (data) => void sends.push({ nsid, data }) }; }; const ran = await runModule(ctx, { module, calls, anyRecords }, entry, { did, ...input }, call, { inputs, budget, signal }); return { ...ran, sends }; } return { module, run, handle }; }