use std::cell::RefCell;
use wasm_bindgen::prelude::*;
thread_local! {
static COMPOSE_WASM_CACHE: RefCell<std::collections::HashMap<String, Vec<u8>>> =
RefCell::new(std::collections::HashMap::new());
}
pub(crate) async fn do_compose_spawn(worker: web_sys::Worker, uid: i32, name: String) {
let cached = COMPOSE_WASM_CACHE.with(|c| c.borrow().get(&name).cloned());
let bytes = match cached {
Some(b) => Some(b),
None => {
let fetched = crate::app::compose_module_wasm(&name).await;
if let Some(ref b) = fetched {
COMPOSE_WASM_CACHE.with(|c| {
c.borrow_mut().insert(name.clone(), b.clone());
});
}
fetched
}
};
if let Some(ref b) = bytes {
super::receipts::note_module(uid, &name, b);
}
post_compose_bytes(&worker, uid, bytes.as_deref());
}
fn post_compose_bytes(worker: &web_sys::Worker, uid: i32, bytes: Option<&[u8]>) {
use js_sys::{Object, Reflect, Uint8Array};
let msg = Object::new();
let _ = Reflect::set(&msg, &JsValue::from_str("type"), &JsValue::from_str("compose_bytes"));
let _ = Reflect::set(&msg, &JsValue::from_str("uid"), &JsValue::from_f64(uid as f64));
match bytes {
Some(b) => {
let arr = Uint8Array::from(b);
let buf = arr.buffer();
let _ = Reflect::set(&msg, &JsValue::from_str("wasm"), &buf);
let transfer = js_sys::Array::new();
transfer.push(&buf);
let _ = worker.post_message_with_transfer(&msg, &transfer);
}
None => {
let _ = Reflect::set(&msg, &JsValue::from_str("wasm"), &JsValue::NULL);
let _ = worker.post_message(&msg);
}
}
}