#post-message #object #message #enums #video-frame #derive #url #struct #javascript-object #convert

web-message

A macro that converts Rust structs to/from JavaScript objects via postMessage

2 releases

Uses new Rust 2024

0.0.2 May 9, 2025
0.0.1 Apr 8, 2025

#465 in WebAssembly

Download history 7/week @ 2025-04-02 108/week @ 2025-04-09 7/week @ 2025-04-16 146/week @ 2025-05-07 45/week @ 2025-05-14 56/week @ 2025-05-21 36/week @ 2025-05-28 8/week @ 2025-06-04 38/week @ 2025-06-11 20/week @ 2025-06-18 37/week @ 2025-06-25

115 downloads per month
Used in hang-wasm

MIT/Apache

13KB
244 lines

A crate for sending and receiving messages via postMessage.

Any type that implements [Message] can be serialized and unserialized. Unlike using Serde for JSON encoding, this approach preserves Transferable Objects and can avoid expensive allocations and copying. Unlike using #[wasm-bindgen], this approach works outside of the wasm-bindgen ABI, supporting more types (ex. named enum variants).

For example, the main thread can send a js_sys::ArrayBuffer or a Web Worker without copying the data. If the WASM worker only needs to process a few header bytes, it can use the js_sys::ArrayBuffer instead of copying into a [Vec]. The resulting bytes can then be passed to VideoDecoder and the resulting VideoFrame (transferable) can be posted back to the main thread. You can even pass around a web_sys::MessagePort!

This crate is designed to be used in conjunction with the web-message-derive crate. We currently attempt parity with ts-rs so the resulting types can use postMessage directly from Typescript.

// NOTE: This is not possible with `wasm-bindgen` or `wasm-bindgen-serde`
#[derive(Message)]
#[msg(tag = "command")]
enum Command {
    Connect {
        url: String,
    },
    Frame {
        keyframe: bool,
        payload: js_sys::ArrayBuffer,
    },
    Close,
}

Some transferable types are gated behind feature flags:

Dependencies

~7–10MB
~187K SLoC