Skip to content

Latest commit

 

History

History
190 lines (136 loc) · 8.77 KB

wasm.md

File metadata and controls

190 lines (136 loc) · 8.77 KB

🌐 WebAssembly

The engine compiled for the browser is two files, and any page can load them and run Lua. This is the same build the playground uses, so what runs there runs in your site.

File What it is
varn-wasm.js An ES module whose default export is a factory that instantiates the engine.
varn-wasm.wasm The engine itself, fetched by the factory at runtime.

Take them from the varn-wasm.tar.gz asset of a release, or build them yourself with python3 varn.py wasm (they land in build/wasm/bin).

Running a script

Serve both files from the same directory and point the factory at it:

<script type="module">
  import createVarnWasm from "/varn/varn-wasm.js";

  const varn = await createVarnWasm({
    locateFile: (path) => `/varn/${path}`,
  });

  const result = await varn.varnRunChunk(`
    local n = 0
    for i = 1, 10 do n = n + i end
    print("sum:", n)
  `);

  console.log(result.ok, result.output);   // Logs true and "sum:\t55\n".
</script>

The option locateFile is how the module finds varn-wasm.wasm. Without it the factory looks beside the page rather than beside the module, which is the usual cause of a 404 on first load. The factory takes two options, locateFile and wasmBinary, which hands it the bytes of varn-wasm.wasm where nothing can fetch them, such as in Node.js.

The call

The function varnRunChunk(source) runs one chunk and answers a promise of a plain object:

Field What it holds
ok Holds true when the chunk itself ran without raising.
output Everything the chunk printed, joined in order, with a trailing newline per print.
error The Lua error message when ok is false, otherwise empty.

The promise settles once nothing the chunk started can still make progress, so the output of a task that sleeps, awaits a fetch or reads a file is in it. The engine never blocks the page while it waits. It runs the chunk, then pumps its runtime from the event loop of the page in slices of a few milliseconds, and between slices it waits for its next timer or for the callback of the page that brings work, such as the end of a fetch. A failure inside a task the chunk started is logged to the console and leaves ok alone, since the chunk that started it had already returned.

Output as it happens

The call varnRunChunk(source, { onPrint }) also hands every line to the function onPrint at the moment Lua prints it, with its trailing newline, so a page shows the progress of a chunk that sleeps or awaits instead of waiting for the promise. The lines it receives joined in order are exactly the field output of the result. Any other option is refused with a TypeError. A listener that throws does not interrupt the chunk, and its error is reported once the engine has returned.

const result = await varn.varnRunChunk(`
  local async = require("async")
  print("Start.")
  async.run(function()
    async.sleep(1500):await()
    print("Done.")
  end)
`, {
  onPrint: (line) => console.log(line.trimEnd()),   // Logs "Start." at once and "Done." 1.5 seconds later.
});

On the page the browser draws only between slices, so a line printed inside a long loop that never awaits shows once the loop ends. In a worker the line is posted to the page as it is printed, which shows it even while such a loop holds the worker.

State survives between calls. One engine is created on the first call and reused, so a global set by one chunk is still there for the next. Create a second module instance when you want a clean slate.

Getting a value back

The call returns what the chunk printed, not what it returned. To hand a value to JavaScript, print it as JSON and parse that:

const result = await varn.varnRunChunk(`
  local json = require("json")
  local report = { total = 128, items = { "a", "b" } }
  print(json.encode(report))
`);

if (!result.ok) {
  throw new Error(result.error);
}

const report = JSON.parse(result.output);
console.log(report.total);   // Logs 128.

When the chunk prints more than the payload, give the value a marker and pick that line out rather than parsing the whole output.

Passing data in

There is no argument list, so the data has to travel inside the chunk. Encode it to base64 and decode it on the Lua side:

function toBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = "";
  for (const byte of bytes) {
    binary += String.fromCharCode(byte);
  }
  return btoa(binary);
}

function runWith(varn, source, data) {
  const payload = toBase64(JSON.stringify(data));
  return varn.varnRunChunk(
    `local input = require("json").decode(require("crypto").base64Decode("${payload}"))\n${source}`
  );
}

const result = await runWith(varn, `print(input.name:upper())`, { name: "varn" });

Base64 is what makes this safe. The payload becomes plain ASCII with no quote, no backslash and no newline, so it cannot close the string literal or run as code. Interpolating the JSON directly would not be safe — JSON.stringify escapes control characters as \u0000 sequences, which Lua does not accept, so such a payload would break the chunk rather than load it.

Keeping the page responsive

The pump hands the thread back between slices, but Lua code that runs a long loop without awaiting holds the thread for as long as the loop runs, and that freezes the tab. Put the engine in a worker and talk to it by message:

// In varn-worker.js.
import createVarnWasm from "/varn/varn-wasm.js";

const varn = await createVarnWasm({ locateFile: (path) => `/varn/${path}` });
self.postMessage({ type: "ready" });

self.onmessage = async (event) => {
  const result = await varn.varnRunChunk(event.data.source, {
    onPrint: (line) => self.postMessage({ type: "output", line }),
  });
  self.postMessage({ type: "done", result });
};
// On the page.
const worker = new Worker("/varn-worker.js", { type: "module" });

worker.onmessage = (event) => {
  if (event.data.type === "output") {
    console.log(event.data.line.trimEnd());
  }

  if (event.data.type === "done" && !event.data.result.ok) {
    console.error(event.data.result.error);
  }
};

worker.postMessage({ source: 'print("hello from a worker")' });

The worker is also the only way to abort a runaway script. Terminate it and start another. There is no way to interrupt a chunk in place.

Serving the files

  • The file varn-wasm.wasm must be served as application/wasm. A server that sends application/octet-stream makes the module fall back to a slower path or fail outright.
  • Both files must be reachable from the page's origin, or served with CORS headers that allow it.
  • The engine grows its own memory, so no SharedArrayBuffer and no cross-origin isolation headers are needed.
  • The engine uses the native exceptions of WebAssembly for the errors and the yields of Lua, which every current browser runs, Chrome and Edge from version 95, Firefox from 100 and Safari from 15.2. An older browser refuses to instantiate the module.

With a bundler

The module is loaded at runtime rather than bundled, because it fetches its own .wasm beside itself. Copy both files into the directory your build serves as static assets, and import by URL:

const varn = await (await import(/* @vite-ignore */ `${location.origin}/varn/varn-wasm.js`)).default({
  locateFile: (path) => `${location.origin}/varn/${path}`,
});

In Vite that directory is public/, which is copied to dist/ untouched. The @vite-ignore comment stops the bundler from trying to resolve the URL at build time.

What runs in the browser

Most of the engine does. The modules async, dataview, datetime, json, xml, log, zip and fs all work, with fs running against an in-memory filesystem that starts empty and does not survive a reload. The http client works, backed by the page's own fetch, which means it obeys CORS like any other request the page makes. It streams, reading the body as it arrives, and it hands over the headers CORS exposes to the page.

Two modules are narrower than their native form:

  • The module crypto carries the essentials — base64 and hex, UUIDs, SHA digests, HMAC and secure random. AES-GCM, scrypt, PBKDF2 and HKDF stay native-only rather than pull OpenSSL into the bundle.
  • The module http has no server. A page cannot host a listener.

The modules socket, process and ffi are absent for the same reason. A browser has no raw TCP, no process model, and no native calling convention for FFI to target. A script that reaches for one of those raises instead of running.

The page docs/platform-availability.md has the full table, module by module. A script can also ask at runtime:

if require("platform").os() == "wasm" then
    print("running in the browser")
end