1use crate::host::{with_host, IoTask, JsObj};
76use fusevm::Value;
77use indexmap::IndexMap;
78use std::cell::RefCell;
79use std::collections::{HashMap, HashSet, VecDeque};
80use std::sync::atomic::{AtomicU64, Ordering};
81use std::sync::mpsc::{Receiver, Sender};
82use std::sync::{Mutex, OnceLock};
83
84pub const METHODS: &[&str] = &[
88 "getEnvironmentData",
89 "setEnvironmentData",
90 "receiveMessageOnPort",
91 "markAsUntransferable",
92 "isMarkedAsUntransferable",
93 "markAsUncloneable",
94 "moveMessagePortToContext",
95];
96
97pub const BROADCAST_CHANNEL_METHODS: &[&str] = &[
99 "postMessage",
100 "close",
101 "ref",
102 "unref",
103 "addEventListener",
104 "removeEventListener",
105];
106
107pub const WORKER_METHODS: &[&str] = &["postMessage", "terminate", "ref", "unref"];
110
111pub const PORT_METHODS: &[&str] = &["postMessage", "close", "start", "ref", "unref"];
114
115static NEXT_THREAD_ID: AtomicU64 = AtomicU64::new(1);
118
119enum WorkerMsg {
122 Data(String),
123 Terminate,
124}
125
126enum MainEvent {
129 Online,
130 Message(String),
131 Error(String),
132 Exit(i32),
133}
134
135struct WorkerRec {
137 emitter: Value,
139 to_worker: Sender<WorkerMsg>,
141}
142
143thread_local! {
144 static WORKERS: RefCell<HashMap<u64, WorkerRec>> = RefCell::new(HashMap::new());
147}
148
149struct WorkerCtx {
153 thread_id: u64,
154 worker_data_json: String,
157 main_tx: Sender<IoTask>,
159 self_id: u64,
161 rx: Option<Receiver<WorkerMsg>>,
163 bridge_started: bool,
165 port_released: bool,
168 port_closed: bool,
170 port_close_emitted: bool,
172}
173
174thread_local! {
175 static WORKER_CTX: RefCell<Option<WorkerCtx>> = const { RefCell::new(None) };
176 static PARENT_PORT: RefCell<Option<Value>> = const { RefCell::new(None) };
179
180 static CHANNEL_PORTS: RefCell<HashMap<u64, Value>> = RefCell::new(HashMap::new());
183 static CH_PEER: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
185 static CH_QUEUE: RefCell<HashMap<u64, VecDeque<String>>> = RefCell::new(HashMap::new());
188 static CH_STARTED: RefCell<HashSet<u64>> = RefCell::new(HashSet::new());
191
192 static BCAST: RefCell<HashMap<String, Vec<(u64, Value)>>> = RefCell::new(HashMap::new());
195
196 static UNTRANSFERABLE: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
198 static UNCLONEABLE: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
199}
200
201fn env_data() -> &'static Mutex<HashMap<String, String>> {
205 static ENV_DATA: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
206 ENV_DATA.get_or_init(|| Mutex::new(HashMap::new()))
207}
208
209static NEXT_PORT_ID: AtomicU64 = AtomicU64::new(1);
212
213fn serialize(v: &Value) -> Result<String, String> {
219 let arr = with_host(|h| h.new_array(vec![v.clone()]));
220 let json = crate::builtins::call_builtin_function("JSON.stringify", vec![arr])?;
221 Ok(with_host(|h| h.str_of(&json)))
222}
223
224fn deserialize(json: &str) -> Result<Value, String> {
227 let sv = with_host(|h| h.new_str(json.to_string()));
228 let arr = crate::builtins::call_builtin_function("JSON.parse", vec![sv])?;
229 Ok(with_host(|h| match h.get(&arr) {
230 Some(JsObj::Array(items)) => items.first().cloned().unwrap_or(Value::Undef),
231 _ => Value::Undef,
232 }))
233}
234
235fn arg0(args: &[Value]) -> Value {
238 args.first().cloned().unwrap_or(Value::Undef)
239}
240
241fn get_prop(recv: &Value, key: &str) -> Option<Value> {
242 with_host(|h| match h.get(recv) {
243 Some(JsObj::Object(p)) => p.get(key).cloned(),
244 _ => None,
245 })
246}
247
248fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
249 get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
250}
251
252fn emit_event(emitter: &Value, name: &str, mut args: Vec<Value>) -> Result<(), String> {
255 let mut a = vec![with_host(|h| h.new_str(name))];
256 a.append(&mut args);
257 super::events::instance_call(emitter, "emit", a).map(|_| ())
258}
259
260fn is_worker_thread() -> bool {
263 WORKER_CTX.with(|c| c.borrow().is_some())
264}
265
266fn current_thread_id() -> u64 {
267 WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| x.thread_id).unwrap_or(0))
268}
269
270fn current_worker_data() -> Value {
273 let json = WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| x.worker_data_json.clone()));
274 match json {
275 Some(j) => deserialize(&j).unwrap_or(Value::Undef),
276 None => Value::Undef,
277 }
278}
279
280fn ensure_parent_port() -> Value {
283 if let Some(p) = PARENT_PORT.with(|p| p.borrow().clone()) {
284 return p;
285 }
286 let port = super::net::new_emitter_object("MessagePort", IndexMap::new());
287 PARENT_PORT.with(|p| *p.borrow_mut() = Some(port.clone()));
288 port
289}
290
291pub fn constant(name: &str) -> Option<Value> {
298 match name {
299 "isMainThread" => Some(Value::Bool(!is_worker_thread())),
300 "threadId" => Some(Value::Float(current_thread_id() as f64)),
301 "parentPort" => Some(if is_worker_thread() {
302 ensure_parent_port()
303 } else {
304 with_host(|h| h.null())
306 }),
307 "workerData" => Some(current_worker_data()),
308 "Worker" | "MessageChannel" | "BroadcastChannel" => {
309 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
310 }
311 _ => None,
312 }
313}
314
315pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
318 Some(match method {
319 "setEnvironmentData" => {
320 let key = super::arg_str(args, 0);
321 match args.get(1) {
322 Some(v) if !matches!(v, Value::Undef) => match serialize(v) {
324 Ok(json) => {
325 if let Ok(mut m) = env_data().lock() {
326 m.insert(key, json);
327 }
328 Ok(Value::Undef)
329 }
330 Err(e) => Err(e),
331 },
332 _ => {
333 if let Ok(mut m) = env_data().lock() {
334 m.remove(&key);
335 }
336 Ok(Value::Undef)
337 }
338 }
339 }
340 "getEnvironmentData" => {
341 let key = super::arg_str(args, 0);
342 let json = env_data().lock().ok().and_then(|m| m.get(&key).cloned());
343 match json {
344 Some(j) => deserialize(&j),
345 None => Ok(Value::Undef),
346 }
347 }
348 "receiveMessageOnPort" => Ok(receive_message_on_port(args.first())),
349 "markAsUntransferable" => {
353 if let Some(Value::Obj(id)) = args.first() {
354 UNTRANSFERABLE.with(|s| s.borrow_mut().insert(*id));
355 }
356 Ok(Value::Undef)
357 }
358 "isMarkedAsUntransferable" => Ok(Value::Bool(matches!(
359 args.first(),
360 Some(Value::Obj(id)) if UNTRANSFERABLE.with(|s| s.borrow().contains(id))
361 ))),
362 "markAsUncloneable" => {
363 if let Some(Value::Obj(id)) = args.first() {
364 UNCLONEABLE.with(|s| s.borrow_mut().insert(*id));
365 }
366 Ok(Value::Undef)
367 }
368 "moveMessagePortToContext" => Ok(arg0(args)),
371 _ => return None,
372 })
373}
374
375pub fn construct_worker(args: &[Value]) -> Result<Value, String> {
381 let filename = with_host(|h| h.str_of(&arg0(args)));
382 let opts = args.get(1).cloned();
383 let is_eval = opts
384 .as_ref()
385 .and_then(|o| get_prop(o, "eval"))
386 .map(|v| with_host(|h| h.truthy(&v)))
387 .unwrap_or(false);
388 let worker_data_json = match opts.as_ref().and_then(|o| get_prop(o, "workerData")) {
390 Some(v) => serialize(&v)?,
391 None => serialize(&Value::Undef)?, };
393
394 let id = NEXT_THREAD_ID.fetch_add(1, Ordering::SeqCst);
395 let (to_worker_tx, to_worker_rx) = std::sync::mpsc::channel::<WorkerMsg>();
396 let main_tx = with_host(|h| h.io_sender());
397
398 let mut extra = IndexMap::new();
399 extra.insert("@@wtid".into(), Value::Float(id as f64));
400 extra.insert("threadId".into(), Value::Float(id as f64));
401 let emitter = super::net::new_emitter_object("Worker", extra);
402
403 WORKERS.with(|w| {
404 w.borrow_mut().insert(
405 id,
406 WorkerRec {
407 emitter: emitter.clone(),
408 to_worker: to_worker_tx,
409 },
410 );
411 });
412 with_host(|h| h.incr_handle());
414
415 let spawn_tx = main_tx.clone();
416 std::thread::spawn(move || {
417 worker_thread_main(
418 id,
419 filename,
420 is_eval,
421 worker_data_json,
422 spawn_tx,
423 to_worker_rx,
424 );
425 });
426
427 Ok(emitter)
428}
429
430fn worker_thread_main(
433 id: u64,
434 filename: String,
435 is_eval: bool,
436 worker_data_json: String,
437 main_tx: Sender<IoTask>,
438 rx: Receiver<WorkerMsg>,
439) {
440 WORKER_CTX.with(|c| {
441 *c.borrow_mut() = Some(WorkerCtx {
442 thread_id: id,
443 worker_data_json,
444 main_tx: main_tx.clone(),
445 self_id: id,
446 rx: Some(rx),
447 bridge_started: false,
448 port_released: false,
449 port_closed: false,
450 port_close_emitted: false,
451 });
452 });
453
454 post_to_main(&main_tx, id, MainEvent::Online);
456
457 let outcome = if is_eval {
462 crate::eval_str(&filename)
463 } else {
464 crate::eval_file(&filename)
465 };
466
467 match outcome {
468 Ok(_) => {
470 let code = with_host(|h| h.exit_code).unwrap_or(0);
471 post_to_main(&main_tx, id, MainEvent::Exit(code));
472 }
473 Err(e) => {
474 post_to_main(&main_tx, id, MainEvent::Error(e));
475 post_to_main(&main_tx, id, MainEvent::Exit(1));
476 }
477 }
478}
479
480fn post_to_main(main_tx: &Sender<IoTask>, id: u64, ev: MainEvent) {
484 let _ = main_tx.send(Box::new(move || dispatch_main(id, ev)));
485}
486
487fn dispatch_main(id: u64, ev: MainEvent) -> Result<(), String> {
489 let emitter = WORKERS.with(|w| w.borrow().get(&id).map(|r| r.emitter.clone()));
490 let Some(emitter) = emitter else {
491 return Ok(());
492 };
493 match ev {
494 MainEvent::Online => emit_event(&emitter, "online", vec![]),
495 MainEvent::Message(json) => {
496 let v = deserialize(&json)?;
497 emit_event(&emitter, "message", vec![v])
498 }
499 MainEvent::Error(msg) => {
500 let err =
501 crate::builtins::construct_builtin("Error", vec![with_host(|h| h.new_str(msg))])?;
502 emit_event(&emitter, "error", vec![err])
503 }
504 MainEvent::Exit(code) => {
505 emit_event(&emitter, "exit", vec![Value::Float(code as f64)])?;
506 WORKERS.with(|w| {
507 w.borrow_mut().remove(&id);
508 });
509 with_host(|h| h.decr_handle());
510 let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
512 Ok(())
513 }
514 }
515}
516
517fn start_parent_bridge() {
524 let worker_io: Option<Sender<IoTask>> = WORKER_CTX.with(|c| {
526 let mut cb = c.borrow_mut();
527 let ctx = cb.as_mut()?;
528 if ctx.bridge_started {
529 return None;
530 }
531 let rx = ctx.rx.take()?;
532 ctx.bridge_started = true;
533 let io = with_host(|h| h.io_sender());
534 with_host(|h| h.incr_handle());
535 let io_for_thread = io.clone();
537 std::thread::spawn(move || {
538 while let Ok(msg) = rx.recv() {
539 match msg {
540 WorkerMsg::Data(json) => {
541 let _ = io_for_thread.send(Box::new(move || parent_deliver(json)));
542 }
543 WorkerMsg::Terminate => {
544 let _ = io_for_thread.send(Box::new(|| {
546 release_parent_port();
547 Ok(())
548 }));
549 break;
550 }
551 }
552 }
553 });
554 Some(io)
555 });
556 let _ = worker_io;
557}
558
559fn release_parent_port() {
562 let release = WORKER_CTX.with(|c| {
563 let mut cb = c.borrow_mut();
564 match cb.as_mut() {
565 Some(ctx) if ctx.bridge_started && !ctx.port_released => {
566 ctx.port_released = true;
567 true
568 }
569 _ => false,
570 }
571 });
572 if release {
573 with_host(|h| h.decr_handle());
574 }
575}
576
577fn close_parent_port() {
582 let first = WORKER_CTX.with(|c| {
583 let mut cb = c.borrow_mut();
584 match cb.as_mut() {
585 Some(ctx) if !ctx.port_closed => {
586 ctx.port_closed = true;
587 true
588 }
589 _ => false,
590 }
591 });
592 if !first {
593 return;
594 }
595 with_host(|h| h.incr_handle());
598 let task: IoTask = Box::new(|| {
599 WORKER_CTX.with(|c| {
600 if let Some(ctx) = c.borrow_mut().as_mut() {
601 ctx.port_close_emitted = true;
602 }
603 });
604 release_parent_port();
605 with_host(|h| h.decr_handle());
606 emit_event(&ensure_parent_port(), "close", vec![])
607 });
608 let _ = with_host(|h| h.io_sender()).send(task);
609}
610
611pub fn exit_if_worker(code: i32) {
618 let target = WORKER_CTX.with(|c| c.borrow().as_ref().map(|x| (x.main_tx.clone(), x.self_id)));
619 let Some((main_tx, id)) = target else {
620 return;
621 };
622 post_to_main(&main_tx, id, MainEvent::Exit(code));
623 loop {
624 std::thread::park();
625 }
626}
627
628fn parent_deliver(json: String) -> Result<(), String> {
632 if WORKER_CTX.with(|c| c.borrow().as_ref().is_some_and(|x| x.port_close_emitted)) {
633 return Ok(());
634 }
635 let port = ensure_parent_port();
636 let v = deserialize(&json)?;
637 emit_event(&port, "message", vec![v])
638}
639
640const EMITTER_METHODS: &[&str] = super::events::METHODS;
645
646pub fn instance_call(
647 tag: &str,
648 recv: &Value,
649 method: &str,
650 args: Vec<Value>,
651) -> Result<Value, String> {
652 match tag {
653 "Worker" => worker_call(recv, method, args),
654 "MessagePort" => port_call(recv, method, args),
655 "BroadcastChannel" => broadcast_call(recv, method, args),
656 _ => Err(crate::host::type_error(&format!(
657 "{method} is not a function"
658 ))),
659 }
660}
661
662fn worker_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
664 if EMITTER_METHODS.contains(&method) {
665 return super::events::instance_call(recv, method, args);
666 }
667 match method {
668 "postMessage" => {
669 let json = serialize(&arg0(&args))?;
670 if let Some(id) = u64_prop(recv, "@@wtid") {
671 WORKERS.with(|w| {
672 if let Some(r) = w.borrow().get(&id) {
673 let _ = r.to_worker.send(WorkerMsg::Data(json));
674 }
675 });
676 }
677 Ok(Value::Undef)
678 }
679 "terminate" => {
680 if let Some(id) = u64_prop(recv, "@@wtid") {
683 WORKERS.with(|w| {
684 if let Some(r) = w.borrow().get(&id) {
685 let _ = r.to_worker.send(WorkerMsg::Terminate);
686 }
687 });
688 }
689 Ok(Value::Undef)
690 }
691 "ref" | "unref" => Ok(recv.clone()),
692 _ => Err(crate::host::type_error(&format!(
693 "worker.{method} is not a function"
694 ))),
695 }
696}
697
698fn port_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
700 if let Some(pid) = u64_prop(recv, "@@portid") {
703 return channel_port_call(recv, pid, method, args);
704 }
705 if EMITTER_METHODS.contains(&method) {
706 let r = super::events::instance_call(recv, method, args.clone());
707 if matches!(
709 method,
710 "on" | "addListener" | "prependListener" | "once" | "prependOnceListener"
711 ) {
712 let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
713 if ev == "message" {
714 start_parent_bridge();
715 }
716 }
717 return r;
718 }
719 match method {
720 "postMessage" => {
721 let json = serialize(&arg0(&args))?;
722 WORKER_CTX.with(|c| {
723 if let Some(ctx) = c.borrow().as_ref().filter(|x| !x.port_closed) {
724 post_to_main(&ctx.main_tx, ctx.self_id, MainEvent::Message(json));
725 }
726 });
727 Ok(Value::Undef)
728 }
729 "start" => {
730 start_parent_bridge();
731 Ok(Value::Undef)
732 }
733 "close" => {
734 close_parent_port();
735 Ok(Value::Undef)
736 }
737 "ref" | "unref" => Ok(recv.clone()),
738 _ => Err(crate::host::type_error(&format!(
739 "port.{method} is not a function"
740 ))),
741 }
742}
743
744pub fn construct_message_channel(_args: &[Value]) -> Result<Value, String> {
753 let id1 = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
754 let id2 = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
755 let mut e1 = IndexMap::new();
756 e1.insert("@@portid".into(), Value::Float(id1 as f64));
757 let port1 = super::net::new_emitter_object("MessagePort", e1);
758 let mut e2 = IndexMap::new();
759 e2.insert("@@portid".into(), Value::Float(id2 as f64));
760 let port2 = super::net::new_emitter_object("MessagePort", e2);
761
762 CHANNEL_PORTS.with(|m| {
763 let mut m = m.borrow_mut();
764 m.insert(id1, port1.clone());
765 m.insert(id2, port2.clone());
766 });
767 CH_PEER.with(|m| {
768 let mut m = m.borrow_mut();
769 m.insert(id1, id2);
770 m.insert(id2, id1);
771 });
772
773 Ok(with_host(|h| {
774 let mut m = IndexMap::new();
775 m.insert("port1".into(), port1);
776 m.insert("port2".into(), port2);
777 h.new_object(m)
778 }))
779}
780
781fn channel_port_call(
783 recv: &Value,
784 pid: u64,
785 method: &str,
786 args: Vec<Value>,
787) -> Result<Value, String> {
788 if EMITTER_METHODS.contains(&method) {
789 let r = super::events::instance_call(recv, method, args.clone());
790 if matches!(
792 method,
793 "on" | "addListener" | "prependListener" | "once" | "prependOnceListener"
794 ) {
795 let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
796 if ev == "message" {
797 start_channel_port(pid);
798 }
799 }
800 return r;
801 }
802 match method {
803 "postMessage" => {
804 let json = serialize(&arg0(&args))?;
805 channel_post(pid, json);
806 Ok(Value::Undef)
807 }
808 "start" => {
809 start_channel_port(pid);
810 Ok(Value::Undef)
811 }
812 "close" => {
813 CH_STARTED.with(|s| {
814 s.borrow_mut().remove(&pid);
815 });
816 Ok(Value::Undef)
817 }
818 "ref" | "unref" => Ok(recv.clone()),
819 _ => Err(crate::host::type_error(&format!(
820 "port.{method} is not a function"
821 ))),
822 }
823}
824
825fn channel_post(from: u64, json: String) {
828 let Some(peer) = CH_PEER.with(|m| m.borrow().get(&from).copied()) else {
829 return;
830 };
831 CH_QUEUE.with(|q| q.borrow_mut().entry(peer).or_default().push_back(json));
832 if CH_STARTED.with(|s| s.borrow().contains(&peer)) {
833 schedule_channel_delivery(peer);
834 }
835}
836
837fn start_channel_port(pid: u64) {
839 let newly = CH_STARTED.with(|s| s.borrow_mut().insert(pid));
840 if !newly {
841 return;
842 }
843 let pending = CH_QUEUE.with(|q| q.borrow().get(&pid).map_or(0, |d| d.len()));
844 for _ in 0..pending {
845 schedule_channel_delivery(pid);
846 }
847}
848
849fn schedule_channel_delivery(pid: u64) {
852 with_host(|h| h.incr_handle());
853 let io = with_host(|h| h.io_sender());
854 let _ = io.send(Box::new(move || channel_deliver(pid)));
855}
856
857fn channel_deliver(pid: u64) -> Result<(), String> {
861 let json = CH_QUEUE.with(|q| q.borrow_mut().get_mut(&pid).and_then(|d| d.pop_front()));
862 if let Some(json) = json {
863 if let Some(port) = CHANNEL_PORTS.with(|m| m.borrow().get(&pid).cloned()) {
864 match deserialize(&json) {
865 Ok(v) => {
866 if let Err(e) = emit_event(&port, "message", vec![v]) {
867 eprintln!("{e}");
868 }
869 }
870 Err(e) => eprintln!("{e}"),
871 }
872 }
873 }
874 with_host(|h| h.decr_handle());
875 Ok(())
876}
877
878fn receive_message_on_port(port: Option<&Value>) -> Value {
881 let Some(port) = port else {
882 return Value::Undef;
883 };
884 let Some(pid) = u64_prop(port, "@@portid") else {
885 return Value::Undef;
886 };
887 let json = CH_QUEUE.with(|q| q.borrow_mut().get_mut(&pid).and_then(|d| d.pop_front()));
888 match json {
889 Some(j) => match deserialize(&j) {
890 Ok(v) => with_host(|h| {
891 let mut m = IndexMap::new();
892 m.insert("message".into(), v);
893 h.new_object(m)
894 }),
895 Err(_) => Value::Undef,
896 },
897 None => Value::Undef,
898 }
899}
900
901pub fn construct_broadcast_channel(args: &[Value]) -> Result<Value, String> {
912 let name = with_host(|h| h.str_of(&arg0(args)));
913 let id = NEXT_PORT_ID.fetch_add(1, Ordering::SeqCst);
914 let obj = with_host(|h| {
915 let listeners = h.new_array(Vec::new());
916 let mut m = IndexMap::new();
917 m.insert("@@native".into(), h.new_str("BroadcastChannel"));
918 m.insert("@@bcid".into(), Value::Float(id as f64));
919 m.insert("@@bcname".into(), h.new_str(name.clone()));
920 m.insert("@@listeners".into(), listeners);
921 m.insert("@@refed".into(), Value::Bool(true));
922 m.insert("name".into(), h.new_str(name.clone()));
923 m.insert("onmessage".into(), h.null());
924 m.insert("onmessageerror".into(), h.null());
925 h.new_object(m)
926 });
927 BCAST.with(|b| {
928 b.borrow_mut()
929 .entry(name)
930 .or_default()
931 .push((id, obj.clone()))
932 });
933 with_host(|h| h.incr_handle());
934 Ok(obj)
935}
936
937fn broadcast_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
939 match method {
940 "postMessage" => {
941 let json = serialize(&arg0(&args))?;
942 let name = str_prop(recv, "@@bcname");
943 let self_id = u64_prop(recv, "@@bcid");
944 let targets: Vec<Value> = BCAST.with(|b| match b.borrow().get(&name) {
945 Some(list) => list
946 .iter()
947 .filter(|(id, _)| Some(*id) != self_id)
948 .map(|(_, v)| v.clone())
949 .collect(),
950 None => Vec::new(),
951 });
952 for t in targets {
953 schedule_broadcast_delivery(t, json.clone());
954 }
955 Ok(Value::Undef)
956 }
957 "close" => {
958 let name = str_prop(recv, "@@bcname");
959 let self_id = u64_prop(recv, "@@bcid");
960 BCAST.with(|b| {
961 if let Some(list) = b.borrow_mut().get_mut(&name) {
962 list.retain(|(id, _)| Some(*id) != self_id);
963 }
964 });
965 release_broadcast_ref(recv);
966 Ok(Value::Undef)
967 }
968 "addEventListener" => {
969 let ev = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
971 if ev == "message" {
972 if let Some(cb) = args.get(1) {
973 if let Some(arr) = get_prop(recv, "@@listeners") {
974 with_host(|h| {
975 if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
976 items.push(cb.clone());
977 }
978 });
979 }
980 }
981 }
982 Ok(Value::Undef)
983 }
984 "removeEventListener" => Ok(Value::Undef),
985 "ref" => {
986 let refed = matches!(get_prop(recv, "@@refed"), Some(Value::Bool(true)));
987 if !refed {
988 with_host(|h| h.incr_handle());
989 set_bool(recv, "@@refed", true);
990 }
991 Ok(recv.clone())
992 }
993 "unref" => {
994 release_broadcast_ref(recv);
995 Ok(recv.clone())
996 }
997 _ => Err(crate::host::type_error(&format!(
998 "BroadcastChannel.{method} is not a function"
999 ))),
1000 }
1001}
1002
1003fn release_broadcast_ref(recv: &Value) {
1005 if matches!(get_prop(recv, "@@refed"), Some(Value::Bool(true))) {
1006 with_host(|h| h.decr_handle());
1007 set_bool(recv, "@@refed", false);
1008 }
1009}
1010
1011fn schedule_broadcast_delivery(target: Value, json: String) {
1013 with_host(|h| h.incr_handle());
1014 let io = with_host(|h| h.io_sender());
1015 let _ = io.send(Box::new(move || broadcast_deliver(target, json)));
1016}
1017
1018fn broadcast_deliver(target: Value, json: String) -> Result<(), String> {
1022 let value = match deserialize(&json) {
1023 Ok(v) => v,
1024 Err(e) => {
1025 eprintln!("{e}");
1026 with_host(|h| h.decr_handle());
1027 return Ok(());
1028 }
1029 };
1030 let event = with_host(|h| {
1031 let mut m = IndexMap::new();
1032 m.insert("data".into(), value);
1033 m.insert("type".into(), h.new_str("message"));
1034 h.new_object(m)
1035 });
1036 let onmessage = get_prop(&target, "onmessage");
1037 let mut handlers: Vec<Value> = Vec::new();
1038 if let Some(cb) = onmessage {
1039 if with_host(|h| crate::host::is_callable(h, &cb)) {
1040 handlers.push(cb);
1041 }
1042 }
1043 if let Some(arr) = get_prop(&target, "@@listeners") {
1044 let listeners: Vec<Value> = with_host(|h| match h.get(&arr) {
1045 Some(JsObj::Array(items)) => items.clone(),
1046 _ => Vec::new(),
1047 });
1048 handlers.extend(listeners);
1049 }
1050 for cb in handlers {
1051 if let Err(e) = crate::host::invoke(&cb, vec![event.clone()], None) {
1052 eprintln!("{e}");
1053 }
1054 }
1055 with_host(|h| h.decr_handle());
1056 Ok(())
1057}
1058
1059fn str_prop(recv: &Value, key: &str) -> String {
1061 get_prop(recv, key)
1062 .map(|v| with_host(|h| h.str_of(&v)))
1063 .unwrap_or_default()
1064}
1065
1066fn set_bool(recv: &Value, key: &str, val: bool) {
1068 with_host(|h| {
1069 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1070 p.insert(key.to_string(), Value::Bool(val));
1071 }
1072 });
1073}