muxio_wasm_rpc_client/static_lib/
static_transport_bridge.rs

1use crate::static_lib::get_static_client;
2
3use super::MUXIO_STATIC_RPC_CLIENT_REF;
4use js_sys::Uint8Array;
5use wasm_bindgen::prelude::*;
6
7#[wasm_bindgen]
8extern "C" {
9    /// External JS function to send bytes from WASM to the network.
10    fn static_muxio_write_bytes_uint8(data: Uint8Array);
11}
12
13/// Helper to convert Rust bytes to JS Uint8Array and send via the bridge.
14pub(crate) fn static_muxio_write_bytes(bytes: &[u8]) {
15    static_muxio_write_bytes_uint8(Uint8Array::from(bytes));
16}
17
18/// Entry point from JavaScript when binary data arrives from the network.
19#[wasm_bindgen]
20pub async fn static_muxio_read_bytes_uint8(inbound_data: Uint8Array) -> Result<(), JsValue> {
21    let inbound_bytes = inbound_data.to_vec();
22
23    // TODO: Use `get_static_client` for easier use
24    let client_arc = MUXIO_STATIC_RPC_CLIENT_REF
25        .with(|cell| cell.borrow().clone())
26        .ok_or_else(|| JsValue::from_str("RPC client not initialized"))?;
27
28    client_arc.read_bytes(&inbound_bytes).await;
29
30    Ok(())
31}
32
33/// Call this from your JavaScript glue code when the WebSocket `onopen` event fires.
34#[wasm_bindgen]
35pub async fn static_muxio_handle_connect() -> Result<(), JsValue> {
36    match get_static_client() {
37        Some(static_client) => {
38            static_client.handle_connect().await;
39            Ok(())
40        }
41        None => Err("No registered static `RpcWasmClient`".into()),
42    }
43}
44
45/// Call this from your JavaScript glue code when the WebSocket's `onclose` or `onerror` event fires.
46#[wasm_bindgen]
47pub async fn static_muxio_handle_disconnect() -> Result<(), JsValue> {
48    match get_static_client() {
49        Some(static_client) => {
50            static_client.handle_disconnect().await;
51            Ok(())
52        }
53        None => Err("No registered static `RpcWasmClient`".into()),
54    }
55}