jsaddle-wasm: Run JSaddle JSM with the GHC WASM backend

[ javascript, library, web ] [ Propose Tags ] [ Report a vulnerability ]

Run JSaddle JSM with the GHC WASM backend.


[Skip to Readme]

library jsaddle-wasm

Modules

[Index] [Quick Jump]

library jsaddle-wasm:js

Modules

[Index] [Quick Jump]

  • Language
    • Javascript
      • JSaddle
        • Wasm
          • Language.Javascript.JSaddle.Wasm.JS

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

Versions [RSS] 0.0.0.0, 0.0.1.0
Change log CHANGELOG.md
Dependencies aeson (>=2 && <2.3), base (>=4.16 && <5), bytestring (>=0.11 && <0.13), ghc-experimental (>=0.1 && <0.2), jsaddle (>=0.9 && <0.10), jsaddle-wasm, stm (>=2.5 && <2.6) [details]
License CC0-1.0
Author amesgen
Maintainer amesgen@amesgen.de
Category Web, Javascript
Home page https://github.com/amesgen/jsaddle-wasm
Bug tracker https://github.com/amesgen/jsaddle-wasm/issues
Source repo head: git clone https://github.com/amesgen/jsaddle-wasm
Uploaded by amesgen at 2024-10-26T13:20:54Z
Distributions NixOS:0.0.0.0
Reverse Dependencies 1 direct, 11 indirect [details]
Downloads 88 total (29 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs uploaded by user
Build status unknown [no reports yet]

Readme for jsaddle-wasm-0.0.1.0

[back to package description]

jsaddle-wasm

CI Hackage Haddocks

Run JSaddle JSM actions with the GHC WASM backend.

This can for example be used to compile and run Miso or Reflex apps in the browser.

[!IMPORTANT] This project is in an early stage.

Examples

How to use

Install a WASM-enabled GHC with support for the WASM JSFFI from ghc-wasm-meta (GHC 9.10 or newer).

Assuming you built your application as an app :: JSM ():

import Language.Javascript.JSaddle.Wasm qualified as JSaddle.Wasm

foreign export javascript "hs_start" main :: IO ()

main :: IO ()
main = JSaddle.Wasm.run app

Build the WASM binary with the following GHC options:

ghc-options: -no-hs-main -optl-mexec-model=reactor "-optl-Wl,--export=hs_start"

Now, run the post-linker script as described in the GHC User's Guide; we will call the resulting JavaScript file ghc_wasm_jsffi.js.

Then, following the GHC User's Guide, you can run the WASM binary in the browser via e.g. browser_wasi_shim:

import { WASI, OpenFile, File, ConsoleStdout } from "@bjorn3/browser_wasi_shim";
import ghc_wasm_jsffi from "./ghc_wasm_jsffi.js";

const fds = [
  new OpenFile(new File([])), // stdin
  ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),
  ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),
];
const options = { debug: false };
const wasi = new WASI([], [], fds, options);

const instance_exports = {};
const { instance } = await WebAssembly.instantiateStreaming(fetch("app.wasm"), {
  wasi_snapshot_preview1: wasi.wasiImport,
  ghc_wasm_jsffi: ghc_wasm_jsffi(instance_exports),
});
Object.assign(instance_exports, instance.exports);

wasi.initialize(instance);
await instance.exports.hs_start();

Separating execution environments

It is also possible to run the WASM worker in a different execution environment (e.g. a web worker) than the JSaddle JavaScript code that dispatches the JSaddle command messages.

An advantage of this approach is that computationally expensive operations in WASM do not block the UI thread. A disadvantage is that there is some overhead for copying the data back and forth, and everything relying on synchronous callbacks (e.g. stopPropagation/preventDefault) definitely no longer works.

  • Instead of the run function above, you need to use runWorker:

    import Language.Javascript.JSaddle.Wasm qualified as JSaddle.Wasm
    
    foreign export javascript "hs_runWorker" runWorker :: JSVal -> IO ()
    
    runWorker :: JSVal -> IO ()
    runWorker = JSaddle.Wasm.runWorker Ormolu.Live.app
    

    The argument to runWorker here can be any message port in the sense of the Channel Messaging API. In particular, it must provide a postMessage function and a message event.

    For example, in a web worker, you can initialize the WASM module as above, and then run

    await instance.exports.hs_runWorker(globalThis);
    

    as globalThis (or self) in a web worker is a message port.

  • Additionally, you need to run the JSaddle command dispatching logic on the other end of the message port.

    The necessary chunk of JavaScript is available as jsaddleScript both from Language.Javascript.JSaddle.Wasm from the main library, and also from Language.Javascript.JSaddle.Wasm.JS from the js public sublibrary, where the latter has the advantage to not depend on any JSFFI, so you can build a normal WASI command module or even a native executable while still depending on it.

    It provides a function runJSaddle taking a single argument, a message port.

    One way to invoke it is to save jsaddleScript to some file, include it via a script tag in your HTML file, and then run

    const worker = new Worker("my-worker.js");
    runJSaddle(worker);
    

Potential future work

  • Take a closer look at synchronous callbacks. We have no special handling currently, but basic things like stopPropagation/preventDefault already seem to work fine with run (but not with runWorker, as expected).
  • Testing (e.g. via Selenium).
  • Add logging/stats.
  • Performance/benchmarking (not clear that this is actually a bottleneck for most applications).
    • Optimize existing command-based implementation.

      • Reuse buffers
      • Use a serialization format more efficient than JSON.
    • Patch jsaddle to not go through commands, by using the WASM JS FFI.

    • Implement ghcjs-dom API directly via the WASM JS FFI.

      This would involve creating a ghcjs-dom-wasm package by adapting the FFI import syntax from ghcjs-dom-jsffi/ghcjs-dom-javascript appropriately.

      Currently, the generic ghcjs-dom-jsaddle seems to work fine, so it seems sensible to wait with this until benchmarks or other concerns motivate this.