use std::{
cell::{Cell, RefCell},
rc::Rc,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use nsh_core::{
EventKind, EventPayload, NodeId, Op, PayloadValue, TouchPhase, js::Limits,
platform::Environment, time::Instant,
};
use rquickjs::{
AsyncRuntime, CatchResultExt, Ctx, Function, Module, Persistent, Promise, Value, function::Opt,
qjs,
};
use crate::{
console,
error::JsError,
net::{FetchEvent, NetworkQueue, RequestId},
protocol::Warnings,
rejections::Rejections,
sandbox::{self, Budget, Phase},
standard::scheduler::{Context, Scheduler},
timers::Timers,
web,
};
pub type ErrorHandler = Box<dyn Fn(&JsError)>;
type ExitHandler = Rc<dyn Fn(i32)>;
#[derive(Default)]
pub(crate) struct Shared {
pub(crate) ops: RefCell<Vec<Op>>,
pub(crate) releases: RefCell<Vec<NodeId>>,
pub(crate) animation_releases: RefCell<Vec<nsh_core::animation::AnimationOp>>,
timers: RefCell<Timers>,
pub(crate) system_exit_handler: RefCell<Option<ExitHandler>>,
pub(crate) system_websocket:
RefCell<Option<std::sync::Arc<dyn nsh_core::websocket::WebSocketTransport>>>,
pub(crate) system_access: RefCell<nsh_core::access::Access>,
pub(crate) system_filesystem:
RefCell<Option<std::sync::Arc<dyn nsh_core::filesystem::FileSystem>>>,
pub(crate) system_data_dir: RefCell<Option<std::path::PathBuf>>,
pub(crate) system_paths: RefCell<nsh_core::access::TrustedPaths>,
pub(crate) system_quotas: nsh_core::ui::Quotas,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) scheduler: std::rc::Weak<Scheduler>,
pub(crate) system_locals: nsh_core::ui::Locals,
pub(crate) lazy_globals: Cell<u8>,
pub(crate) system_wake: RefCell<Option<Arc<dyn Fn() + Send + Sync>>>,
pub(crate) warnings: RefCell<Warnings>,
pub(crate) net: RefCell<NetworkQueue>,
pub(crate) dropped_fetches: RefCell<Vec<RequestId>>,
pub(crate) fonts: RefCell<Vec<String>>,
frames: RefCell<Vec<(u32, Persistent<Function<'static>>)>>,
next_frame_id: std::cell::Cell<u32>,
pub(crate) measurer: RefCell<Option<TextMeasurer>>,
pub(crate) limits: Limits,
pub(crate) fatal: RefCell<Option<String>>,
rejections: RefCell<Rejections>,
}
impl Shared {
pub(crate) fn stop(&self, reason: String) {
self.fatal.borrow_mut().get_or_insert(reason);
}
}
pub type TextMeasurer =
Box<dyn Fn(&nsh_core::canvas::CanvasFont, &str) -> nsh_core::geometry::Points>;
pub struct Host {
cx: Context,
rt: RefCell<Option<AsyncRuntime>>,
scheduler: Rc<Scheduler>,
exhausted: Arc<AtomicBool>,
shared: Rc<Shared>,
on_error: Option<ErrorHandler>,
on_rejection: Option<ErrorHandler>,
budget: Budget,
evaluations: RefCell<Vec<Persistent<Promise<'static>>>>,
entry_depth: Cell<usize>,
}
fn new_context(rt: &AsyncRuntime, scheduler: Rc<Scheduler>) -> rquickjs::Result<Context> {
#[cfg(test)]
if tests::SOURCELESS.get() {
return sourceless_context(rt, scheduler);
}
#[cfg(not(feature = "bytecode-only"))]
{
Context::full(rt, scheduler)
}
#[cfg(feature = "bytecode-only")]
{
sourceless_context(rt, scheduler)
}
}
#[cfg(any(feature = "bytecode-only", test))]
fn sourceless_context(rt: &AsyncRuntime, scheduler: Rc<Scheduler>) -> rquickjs::Result<Context> {
use rquickjs::context::intrinsic::{
Date, Json, MapSet, Performance, Promise, Proxy, RegExp, TypedArrays, WeakRef,
};
let cx = Context::custom::<(
Date,
RegExp,
Json,
Proxy,
MapSet,
TypedArrays,
Promise,
WeakRef,
Performance,
)>(rt, scheduler)?;
cx.with(|cx| unsafe { rquickjs::qjs::JS_AddIntrinsicAToB(cx.as_raw().as_ptr()) });
Ok(cx)
}
#[derive(Debug, Clone, Default)]
pub struct HostOptions {
pub limits: Limits,
pub harden: bool,
pub harden_bytecode: Option<std::sync::Arc<Vec<u8>>>,
pub ui_sets: Vec<nsh_core::ui::Registry>,
pub posts: nsh_core::ui::Posts,
pub base_url: Option<String>,
}
impl Host {
pub fn new() -> Result<Host, JsError> {
Self::with_options(HostOptions::default())
}
pub fn with_options(options: HostOptions) -> Result<Host, JsError> {
let limits = options.limits;
let (allocator, exhausted) = sandbox::HeapAllocator::new(limits.memory_bytes);
let scheduler = Scheduler::new();
let rt = AsyncRuntime::new_with_alloc(allocator)?;
scheduler.ready(rt.set_loader(crate::modules::Resolver, crate::modules::Loader));
scheduler.ready(rt.set_max_stack_size(limits.stack_bytes));
let budget = Budget::new(limits);
scheduler.ready(rt.set_interrupt_handler(Some(budget.interrupt_handler(None))));
let cx = new_context(&rt, scheduler.clone())?;
let shared = Rc::new(Shared {
limits,
scheduler: Rc::downgrade(&scheduler),
..Shared::default()
});
let tracked = shared.clone();
scheduler.ready(rt.set_host_promise_rejection_tracker(Some(Box::new(
move |cx, promise, reason, handled| {
tracked
.rejections
.borrow_mut()
.track(&cx, promise, reason, handled);
},
))));
cx.with(|cx| {
crate::state::install(&cx, shared.clone(), &options.ui_sets, options.posts.clone());
web::web(cx.as_raw().as_ptr()).base_url = options
.base_url
.as_deref()
.and_then(|u| url::Url::parse(u).ok());
install(&cx, &shared)?;
crate::standard::install(&cx)?;
crate::clock::install(&cx)?;
if options.harden {
match &options.harden_bytecode {
Some(bytecode) => unsafe { sandbox::harden_from(&cx, bytecode)? },
None => sandbox::harden(&cx)?,
}
}
Ok(())
})
.map_err(|e| cx.with(|cx| JsError::from_engine(&cx, e)))?;
Ok(Host {
cx,
rt: RefCell::new(Some(rt)),
scheduler,
exhausted,
shared,
on_error: None,
on_rejection: None,
budget,
evaluations: RefCell::new(Vec::new()),
entry_depth: Cell::new(0),
})
}
pub fn set_stop_flag(&self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
if let Some(rt) = self.rt.borrow().as_ref() {
self.scheduler
.ready(rt.set_interrupt_handler(Some(self.budget.interrupt_handler(Some(stop)))));
}
}
pub fn fatal(&self) -> Option<String> {
self.shared.fatal.borrow().clone()
}
pub fn stop(&self, reason: String) {
self.shared.stop(reason);
if self.entry_depth.get() == 0 {
self.stop_work();
}
}
pub fn limits(&self) -> &Limits {
self.budget.limits()
}
fn guarded<R>(&self, phase: Phase, f: impl FnOnce() -> R) -> Option<R> {
if self.shared.fatal.borrow().is_some() {
if self.entry_depth.get() == 0 {
self.stop_work();
}
return None;
}
self.entry_depth.set(self.entry_depth.get() + 1);
let running = self.budget.run(phase);
let result = f();
drop(running);
if self.exhausted.load(Ordering::Relaxed) && self.shared.fatal.borrow().is_none() {
self.uncaught(&JsError::new("out of memory".to_owned()));
}
self.entry_depth.set(self.entry_depth.get() - 1);
if self.entry_depth.get() == 0 && self.fatal().is_some() {
self.stop_work();
}
Some(result)
}
fn stop_work(&self) {
self.scheduler.disable();
self.shared.system_wake.borrow_mut().take();
self.shared.system_exit_handler.borrow_mut().take();
self.evaluations.borrow_mut().clear();
self.shared.timers.borrow_mut().clear();
self.shared.frames.borrow_mut().clear();
if self.cx.is_live() {
self.cx.with(|cx| crate::state::uninstall(&cx));
self.cx.retire();
}
if let Some(rt) = self.rt.borrow().as_ref() {
self.scheduler
.ready(rt.set_host_promise_rejection_tracker(None));
}
self.shared.rejections.borrow_mut().clear();
self.rt.borrow_mut().take();
}
fn classify(&self, mut err: JsError) -> JsError {
if let Some(trip) = self.budget.take_trip() {
err.message = format!("{trip}\n{}", err.message);
} else if self.exhausted.load(Ordering::Relaxed) {
let reason = format!(
"the script ran out of memory (the JS heap is limited to {} MB) and was stopped. \
Keep large data out of JS: load it in pages, or keep it on the native side \
(a server, a native module) and hand JS only what it shows.",
self.budget.limits().memory_bytes >> 20
);
self.shared.stop(reason.clone());
err.message = format!("{reason}\n{}", err.message);
}
err
}
fn stopped(&self) -> JsError {
JsError::new(self.fatal().unwrap_or_default())
}
pub fn set_text_measurer(&mut self, measurer: TextMeasurer) {
*self.shared.measurer.borrow_mut() = Some(measurer);
}
pub fn set_error_handler(&mut self, handler: ErrorHandler) {
self.on_error = Some(handler);
}
#[cfg(not(feature = "bytecode-only"))]
pub(crate) fn standard_exports(&self) -> Result<Vec<(String, Vec<String>)>, JsError> {
self.guarded(Phase::Load, || {
self.cx
.with(|cx| {
crate::standard::NAMES
.iter()
.map(|name| {
let module = crate::modules::load_module(&cx, name)
.catch(&cx)
.map_err(JsError::caught)?;
let (module, promise) =
module.eval().catch(&cx).map_err(JsError::caught)?;
if let Some(result) = promise.result::<()>() {
result.catch(&cx).map_err(JsError::caught)?;
}
let namespace =
module.namespace().catch(&cx).map_err(JsError::caught)?;
let mut exports = namespace
.keys::<String>()
.collect::<rquickjs::Result<Vec<_>>>()
.catch(&cx)
.map_err(JsError::caught)?;
exports.sort();
Ok(((*name).to_owned(), exports))
})
.collect::<Result<Vec<(String, Vec<String>)>, JsError>>()
})
.map_err(|error| self.classify(error))
})
.unwrap_or_else(|| Err(self.stopped()))
}
#[cfg(feature = "bytecode-only")]
pub(crate) fn standard_exports(&self) -> Result<Vec<(String, Vec<String>)>, JsError> {
Ok(Vec::new())
}
pub fn set_rejection_handler(&mut self, handler: ErrorHandler) {
self.on_rejection = Some(handler);
}
pub fn eval_source(&self, source: &str) -> Result<(), JsError> {
self.guarded(Phase::Load, || {
let promise = self
.cx
.with(|cx| -> Result<_, JsError> {
let module = Module::declare(cx.clone(), crate::BUNDLE_NAME, source)
.catch(&cx)
.map_err(JsError::caught)?;
let (_, promise) = module.eval().catch(&cx).map_err(JsError::caught)?;
mark_handled(&cx, &promise);
Ok(Persistent::save(&cx, promise))
})
.map_err(|e| self.classify(e))?;
self.finish_evaluation(promise)
})
.unwrap_or_else(|| Err(self.stopped()))
}
fn finish_evaluation(&self, promise: Persistent<Promise<'static>>) -> Result<(), JsError> {
self.run_jobs();
let result = self.cx.with(|cx| {
let restored = promise
.clone()
.restore(&cx)
.map_err(|e| JsError::from_engine(&cx, e))?;
Ok::<_, JsError>(
restored
.result::<()>()
.map(|r| r.catch(&cx).map_err(JsError::caught)),
)
})?;
match result {
Some(result) => result.map_err(|e| self.classify(e)),
None => {
self.evaluations.borrow_mut().push(promise);
Ok(())
}
}
}
fn settle_evaluations(&self) {
let pending = self.evaluations.take();
for promise in pending {
let result = self.cx.with(|cx| match promise.clone().restore(&cx) {
Ok(promise) => promise
.result::<()>()
.map(|r| r.catch(&cx).map_err(JsError::caught)),
Err(error) => Some(Err(JsError::from_engine(&cx, error))),
});
match result {
Some(Err(error)) => self.uncaught(&error),
Some(Ok(())) => {}
None => self.evaluations.borrow_mut().push(promise),
}
}
}
pub fn eval_script(&self, name: &str, source: &str) -> Result<bool, JsError> {
self.guarded(Phase::Load, || self.eval_script_unguarded(name, source))
.unwrap_or_else(|| Err(self.stopped()))
}
fn eval_script_unguarded(&self, name: &str, source: &str) -> Result<bool, JsError> {
let applied = self.cx.with(|cx| -> Result<bool, JsError> {
let mut options = rquickjs::context::EvalOptions::default();
options.global = true;
options.strict = false;
options.filename = Some(name.to_owned());
let value: rquickjs::Value<'_> = cx
.eval_with_options(source, options)
.catch(&cx)
.map_err(JsError::caught)?;
Ok(value.as_bool() == Some(true))
});
let applied = applied.map_err(|e| self.classify(e))?;
self.run_jobs();
Ok(applied)
}
pub fn eval_bytecode(&self, bytecode: &[u8]) -> Result<(), JsError> {
self.guarded(Phase::Load, || {
let promise = self
.cx
.with(|cx| -> Result<_, JsError> {
let module = unsafe { Module::load(cx.clone(), bytecode) }
.catch(&cx)
.map_err(JsError::caught)?;
let (_, promise) = module.eval().catch(&cx).map_err(JsError::caught)?;
mark_handled(&cx, &promise);
Ok(Persistent::save(&cx, promise))
})
.map_err(|e| self.classify(e))?;
self.finish_evaluation(promise)
})
.unwrap_or_else(|| Err(self.stopped()))
}
pub fn add_chunk_source(&self, id: &str, source: String) {
self.add_chunk(id, crate::modules::ChunkCode::Source(source));
}
pub unsafe fn add_chunk_bytecode(&self, id: &str, bytecode: Vec<u8>) {
self.add_chunk(id, crate::modules::ChunkCode::Bytecode(bytecode));
}
fn add_chunk(&self, id: &str, code: crate::modules::ChunkCode) {
self.guarded(Phase::Call, || {
self.cx
.with(|cx| crate::chunks::add(cx.as_raw().as_ptr(), id, code));
self.run_jobs();
});
}
pub fn chunk_failed(&self, id: &str, message: &str) {
self.guarded(Phase::Call, || {
self.cx
.with(|cx| crate::chunks::failed(cx.as_raw().as_ptr(), id, message));
self.run_jobs();
});
}
pub fn take_chunk_requests(&self, out: &mut Vec<String>) {
if !self.cx.is_live() {
return;
}
self.cx.with(|cx| {
unsafe { &(*crate::state::state(cx.as_raw().as_ptr())).chunks }.take_requests(out)
});
}
pub fn deliver(&self, event: nsh_core::ui::JsEvent) {
if let nsh_core::ui::JsEvent::Event(id, kind, payload) = &event {
self.dispatch_event(*id, *kind, payload);
return;
}
let delivered = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
let raw = cx.as_raw().as_ptr();
if crate::components::deliver(raw, event).is_err() {
self.report::<()>(&cx, Err(rquickjs::Error::Exception));
}
});
self.run_jobs();
})
}));
if delivered.is_err() {
log::error!(target: "js", "a value for JS panicked as it dropped");
}
}
pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: &EventPayload) {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
if let (EventKind::Touch, EventPayload::Touch(touch)) = (event, payload) {
if crate::touch::dispatch(cx.as_raw().as_ptr(), touch).is_err() {
self.report::<()>(&cx, Err(rquickjs::Error::Exception));
}
return;
}
let payload = match (event, payload) {
(EventKind::ChangeText, EventPayload::Text { text, .. }) => {
rquickjs::String::from_str(cx.clone(), text).map(|s| s.into_value())
}
(_, EventPayload::Value(value)) => payload_value(&cx, value),
(EventKind::Load, EventPayload::Map(fields))
if fields.iter().any(|(k, _)| *k == "duration") =>
{
video_load(&cx, fields)
}
_ => payload_object(&cx, payload),
};
let raw = cx.as_raw().as_ptr();
let result = payload.and_then(|payload| {
let Some(handler) = crate::dom::handler(raw, id, event) else {
return Ok(());
};
let handler = unsafe { Value::from_raw(cx.clone(), handler) };
match handler.into_function() {
Some(f) => f.call::<_, ()>((payload,)),
None => Ok(()),
}
});
self.report(&cx, result);
});
self.run_jobs();
});
}
pub fn bind_list(&self, list: NodeId, binds: &[(u32, u32)]) {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
if let Some(Err(_)) = crate::list::bind(cx.as_raw().as_ptr(), list, binds) {
self.report::<()>(&cx, Err(rquickjs::Error::Exception));
}
});
self.run_jobs();
});
}
pub fn animations_finished(&self, finished: &[nsh_core::animation::Finished]) {
self.guarded(Phase::Call, || {
if finished.is_empty() {
return;
}
self.cx.with(|cx| {
let raw = cx.as_raw().as_ptr();
for f in finished {
if crate::animated::finished(raw, f).is_err() {
self.report::<()>(&cx, Err(rquickjs::Error::Exception));
}
}
});
self.run_jobs();
});
}
pub fn take_ops(&self, out: &mut Vec<Op>) {
let mut ops = self.shared.ops.borrow_mut();
if out.is_empty() {
std::mem::swap(out, &mut ops);
} else {
out.append(&mut ops);
}
drop(ops);
let mut releases = self.shared.releases.borrow_mut();
out.extend(releases.drain(..).map(|id| Op::Release { id }));
drop(releases);
out.extend(
self.shared
.animation_releases
.borrow_mut()
.drain(..)
.map(Op::Animation),
);
}
pub fn set_system_access(
&self,
access: nsh_core::access::Access,
data_dir: Option<std::path::PathBuf>,
) {
*self.shared.system_access.borrow_mut() = access;
*self.shared.system_data_dir.borrow_mut() = data_dir;
}
pub fn set_system_paths(&self, paths: nsh_core::access::TrustedPaths) {
*self.shared.system_paths.borrow_mut() = paths;
}
pub fn set_filesystem(
&self,
filesystem: Option<std::sync::Arc<dyn nsh_core::filesystem::FileSystem>>,
) {
*self.shared.system_filesystem.borrow_mut() = filesystem;
}
pub fn set_websocket_transport(
&self,
transport: Option<std::sync::Arc<dyn nsh_core::websocket::WebSocketTransport>>,
) {
*self.shared.system_websocket.borrow_mut() = transport;
}
pub fn set_exit_handler(&self, handler: Rc<dyn Fn(i32)>) {
if self.fatal().is_some() {
return;
}
*self.shared.system_exit_handler.borrow_mut() = Some(handler);
}
pub fn set_system_wake(&self, wake: Arc<dyn Fn() + Send + Sync>) {
if self.fatal().is_some() {
return;
}
self.scheduler.set_wake(wake.clone());
*self.shared.system_wake.borrow_mut() = Some(wake);
}
pub fn run_system(&self) {
self.guarded(Phase::Call, || self.run_jobs());
}
pub fn has_system_tasks(&self) -> bool {
if self.fatal().is_some() {
return false;
}
!self.evaluations.borrow().is_empty()
|| self
.scheduler
.ready(self.rt.borrow().as_ref().expect("live VM").is_job_pending())
}
pub fn next_timer(&self) -> Option<Instant> {
self.shared.timers.borrow_mut().next_deadline()
}
pub fn run_timers(&self, now: Instant) {
loop {
let Some(callback) = self.shared.timers.borrow_mut().pop_due(now) else {
break;
};
let ran = self.guarded(Phase::Call, || {
self.cx.with(|cx| {
let result = callback.restore(&cx).and_then(|f| f.call::<_, ()>(()));
self.report(&cx, result);
});
self.run_jobs();
});
if ran.is_none() {
break;
}
}
}
pub fn run_jobs(&self) {
self.guarded(Phase::Call, || {
loop {
loop {
match self
.scheduler
.poll_job(self.rt.borrow().as_ref().expect("live VM"))
{
std::task::Poll::Ready(Ok(true)) => {}
std::task::Poll::Ready(Ok(false)) | std::task::Poll::Pending => break,
std::task::Poll::Ready(Err(err)) => {
let err = self.scheduler.ready(err.with(|cx| {
let caught = cx.catch();
let mut err = JsError::new(describe(caught.clone()));
err.null = caught.is_null();
err
}));
self.uncaught(&err);
if self.fatal().is_some() {
break;
}
}
}
}
if self.fatal().is_some() {
break;
}
self.settle_evaluations();
if !self.report_rejections() {
break;
}
}
});
}
fn report_rejections(&self) -> bool {
let rejections = self.shared.rejections.borrow_mut().take();
if rejections.is_empty() {
return false;
}
if self.exhausted.load(Ordering::Relaxed) || self.shared.fatal.borrow().is_some() {
return false;
}
self.cx.with(|cx| {
for rejection in rejections {
let mut text = String::new();
if let Ok(reason) = rejection.reason(&cx) {
console::format_value(&reason, &mut text);
}
text.truncate(text.trim_end().len());
let err = JsError::new(text);
match &self.on_rejection {
Some(handler) => handler(&err),
None => log::error!(target: "js", "unhandled rejection: {err}"),
}
}
});
true
}
#[cfg(test)]
pub(crate) fn pending_rejections(&self) -> usize {
self.shared.rejections.borrow().len()
}
#[cfg(test)]
pub(crate) fn warned(&self, message: &str) -> bool {
self.shared.warnings.borrow().reported(message)
}
#[cfg(test)]
pub(crate) fn with_raw<R>(&self, f: impl FnOnce(*mut qjs::JSContext) -> R) -> R {
self.cx.with(|cx| f(cx.as_raw().as_ptr()))
}
#[cfg(test)]
pub(crate) fn has_exception(&self) -> bool {
if !self.cx.is_live() {
return false;
}
self.cx
.with(|cx| unsafe { qjs::JS_HasException(cx.as_raw().as_ptr()) })
}
pub fn run_posted(&self) {
if self.fatal().is_some() {
if self.cx.is_live() {
self.cx
.with(|cx| crate::classes::close(cx.as_raw().as_ptr()));
}
return;
}
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
let ran = crate::classes::run_posted(cx.as_raw().as_ptr());
self.report(&cx, ran.map_err(|_| rquickjs::Error::Exception));
});
self.run_jobs();
});
}
#[cfg(test)]
pub(crate) fn run_posted_without_core(&self) {
let mut ops = Vec::new();
self.take_ops(&mut ops);
self.apply_posts(&mut ops);
self.run_posted();
}
#[cfg(test)]
pub(crate) fn apply_posts(&self, ops: &mut Vec<Op>) {
ops.retain(|op| {
!matches!(
op,
Op::Rust(nsh_core::ui::RustOp {
run: nsh_core::ui::RustCall::Post(_),
..
})
)
});
}
pub fn has_posted(&self) -> bool {
if !self.cx.is_live() {
return false;
}
self.cx
.with(|cx| crate::classes::has_posted(cx.as_raw().as_ptr()))
}
pub fn take_network(&self, out: &mut NetworkQueue) {
if self.cx.is_live() && !self.shared.dropped_fetches.borrow().is_empty() {
self.cx
.with(|cx| crate::web::forget_dropped_fetches(cx.as_raw().as_ptr()));
}
out.ops.append(&mut self.shared.net.borrow_mut().ops);
}
pub fn set_environment(&self, env: &Environment) {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
let result = (|| {
let raw = cx.as_raw().as_ptr();
unsafe { &(*crate::state::state(raw)).dom }.set_platform(env.os, env.desktop());
if crate::env::set_environment(raw, env).is_err() {
return Err(rquickjs::Error::Exception);
}
Ok(())
})();
self.report(&cx, result);
});
self.run_jobs();
});
}
pub fn set_tokens(&self, tokens: std::sync::Arc<nsh_core::ui::Tokens>) {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
crate::env::set_tokens(cx.as_raw().as_ptr(), tokens);
});
self.run_jobs();
});
}
pub fn wants_frame(&self) -> bool {
!self.shared.frames.borrow().is_empty()
}
pub fn run_frame(&self) {
self.guarded(Phase::Call, || {
let callbacks = std::mem::take(&mut *self.shared.frames.borrow_mut());
if callbacks.is_empty() {
return;
}
self.cx.with(|cx| {
let now = (|| -> rquickjs::Result<f64> {
let performance: rquickjs::Object = cx.globals().get("performance")?;
performance.get::<_, Function>("now")?.call(())
})()
.unwrap_or(0.0);
for (_, callback) in callbacks {
let result = callback.restore(&cx).and_then(|f| f.call::<_, ()>((now,)));
self.report(&cx, result);
}
});
self.run_jobs();
});
}
pub fn take_fonts(&self, out: &mut Vec<String>) {
out.append(&mut self.shared.fonts.borrow_mut());
}
pub fn fetch_event(&self, id: RequestId, event: FetchEvent) {
self.guarded(Phase::Call, || {
self.cx.with(|cx| {
let raw = cx.as_raw().as_ptr();
let result =
crate::web::fetch_event(raw, id, event).map_err(|_| rquickjs::Error::Exception);
self.report(&cx, result);
});
self.run_jobs();
});
}
pub fn object_count(&self) -> i64 {
self.rt
.borrow()
.as_ref()
.map_or(0, |rt| self.scheduler.ready(rt.memory_usage()).obj_count)
}
pub fn collect_garbage(&self) {
self.guarded(Phase::Call, || {
self.scheduler
.ready(self.rt.borrow().as_ref().expect("live VM").run_gc());
self.run_jobs();
});
}
}
impl Host {
fn report<T>(&self, cx: &Ctx<'_>, result: rquickjs::Result<T>) {
if let Err(err) = result.catch(cx) {
self.uncaught(&JsError::caught(err));
}
}
fn uncaught(&self, err: &JsError) {
let err = self.classify(err.clone());
match &self.on_error {
Some(handler) => handler(&err),
None => log::error!(target: "js", "uncaught exception: {err}"),
}
}
}
impl Drop for Host {
fn drop(&mut self) {
self.stop_work();
}
}
fn mark_handled(cx: &Ctx<'_>, promise: &rquickjs::Promise<'_>) {
unsafe { qjs::JS_PromiseMarkAsHandled(cx.as_raw().as_ptr(), promise.as_raw()) };
}
fn video_load<'js>(
cx: &Ctx<'js>,
fields: &[(&'static str, PayloadValue)],
) -> rquickjs::Result<Value<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
let size = rquickjs::Object::new(cx.clone())?;
for (key, value) in fields {
match *key {
"width" | "height" => size.set(*key, payload_value(cx, value)?)?,
_ => obj.set(*key, payload_value(cx, value)?)?,
}
}
obj.set("size", size)?;
Ok(obj.into_value())
}
fn payload_object<'js>(cx: &Ctx<'js>, payload: &EventPayload) -> rquickjs::Result<Value<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
match payload {
EventPayload::None => return Ok(Value::new_undefined(cx.clone())),
EventPayload::Value(value) => return payload_value(cx, value),
EventPayload::Map(fields) => {
for (key, value) in fields {
obj.set(*key, payload_value(cx, value)?)?;
}
}
EventPayload::Hover(nsh_core::HoverEvent {
position,
page_position,
modifiers,
})
| EventPayload::ContextMenu(nsh_core::ContextMenuEvent {
position,
page_position,
modifiers,
}) => {
obj.set("position", point_object(cx, *position)?)?;
obj.set("pagePosition", point_object(cx, *page_position)?)?;
obj.set("modifiers", modifiers_object(cx, modifiers)?)?;
}
EventPayload::FileDrop(uris) => {
let list = rquickjs::Array::new(cx.clone())?;
for (index, uri) in uris.iter().enumerate() {
list.set(index, uri.as_str())?;
}
obj.set("uris", list)?;
}
EventPayload::Native { name, data } => {
obj.set("name", &**name)?;
obj.set("data", json_value(cx, data)?)?;
}
EventPayload::TextLayout(lines) => {
let list = rquickjs::Array::new(cx.clone())?;
for (i, l) in lines.iter().enumerate() {
let line = rquickjs::Object::new(cx.clone())?;
line.set("text", l.text.as_str())?;
let bounds = nsh_core::geometry::Bounds {
origin: nsh_core::geometry::point(l.x, l.y),
size: nsh_core::geometry::Size::new(l.width, l.height),
};
line.set("bounds", bounds_object(cx, bounds)?)?;
line.set("ascender", l.ascender.0)?;
line.set("descender", l.descender.0)?;
line.set("capHeight", l.cap_height.0)?;
line.set("xHeight", l.x_height.0)?;
list.set(i, line)?;
}
obj.set("lines", list)?;
}
EventPayload::Layout(frame) => return Ok(bounds_object(cx, *frame)?.into_value()),
EventPayload::Pan {
translation,
velocity_x,
velocity_y,
value_x,
value_y,
} => {
obj.set("translationX", translation.x.0)?;
obj.set("translationY", translation.y.0)?;
obj.set("velocityX", *velocity_x)?;
obj.set("velocityY", *velocity_y)?;
if let Some(v) = value_x {
obj.set("valueX", v.0)?;
}
if let Some(v) = value_y {
obj.set("valueY", v.0)?;
}
}
EventPayload::Scroll(offset) => {
obj.set("x", offset.x.0)?;
obj.set("y", offset.y.0)?;
}
EventPayload::Image(size) => {
obj.set("width", size.width.0 as f32)?;
obj.set("height", size.height.0 as f32)?;
}
EventPayload::Error { message } => obj.set("message", message.as_str())?,
EventPayload::Text { text, .. } => obj.set("text", text.as_str())?,
EventPayload::Touch(touch) => {
obj.set(
"phase",
match touch.phase {
TouchPhase::Start => "start",
TouchPhase::Move => "move",
TouchPhase::End => "end",
TouchPhase::Cancel => "cancel",
},
)?;
obj.set("timestamp", touch.timestamp)?;
let points = rquickjs::Array::new(cx.clone())?;
for (i, p) in touch.points.iter().enumerate() {
let o = rquickjs::Object::new(cx.clone())?;
o.set("identifier", p.id)?;
o.set("target", p.target)?;
let path = rquickjs::Array::new(cx.clone())?;
for (j, id) in p.path.iter().enumerate() {
path.set(j, *id)?;
}
o.set("path", path)?;
o.set("pageX", p.page.x.0)?;
o.set("pageY", p.page.y.0)?;
o.set("locationX", p.location.x.0)?;
o.set("locationY", p.location.y.0)?;
o.set("changed", p.changed)?;
o.set("timestamp", touch.timestamp)?;
points.set(i, o)?;
}
obj.set("points", points)?;
}
}
Ok(obj.into_value())
}
pub(crate) fn json_to_js(raw: *mut qjs::JSContext, json: &nsh_core::JsonValue) -> qjs::JSValue {
let cx = unsafe { Ctx::from_raw(std::ptr::NonNull::new_unchecked(raw)) };
match json_value(&cx, json) {
Ok(v) => unsafe { qjs::JS_DupValue(raw, v.as_raw()) },
Err(_) => qjs::JS_UNDEFINED,
}
}
fn json_value<'js>(cx: &Ctx<'js>, value: &nsh_core::JsonValue) -> rquickjs::Result<Value<'js>> {
use nsh_core::JsonValue as J;
Ok(match value {
J::Null => Value::new_null(cx.clone()),
J::Bool(b) => Value::new_bool(cx.clone(), *b),
J::Number(n) => Value::new_float(cx.clone(), n.as_f64().unwrap_or(0.0)),
J::String(s) => rquickjs::String::from_str(cx.clone(), s)?.into_value(),
J::Array(items) => {
let array = rquickjs::Array::new(cx.clone())?;
for (i, item) in items.iter().enumerate() {
array.set(i, json_value(cx, item)?)?;
}
array.into_value()
}
J::Object(fields) => {
let object = rquickjs::Object::new(cx.clone())?;
for (key, item) in fields {
object.set(key.as_str(), json_value(cx, item)?)?;
}
object.into_value()
}
})
}
fn point_object<'js>(
cx: &Ctx<'js>,
p: nsh_core::geometry::Point<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
obj.set("x", p.x.0)?;
obj.set("y", p.y.0)?;
Ok(obj)
}
fn size_object<'js>(
cx: &Ctx<'js>,
s: nsh_core::geometry::Size<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
obj.set("width", s.width.0)?;
obj.set("height", s.height.0)?;
Ok(obj)
}
fn bounds_object<'js>(
cx: &Ctx<'js>,
b: nsh_core::geometry::Bounds<nsh_core::geometry::Points>,
) -> rquickjs::Result<rquickjs::Object<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
obj.set("origin", point_object(cx, b.origin)?)?;
obj.set("size", size_object(cx, b.size)?)?;
Ok(obj)
}
fn modifiers_object<'js>(
cx: &Ctx<'js>,
m: &nsh_core::keymap::Modifiers,
) -> rquickjs::Result<rquickjs::Object<'js>> {
let obj = rquickjs::Object::new(cx.clone())?;
obj.set("control", m.ctrl)?;
obj.set("alt", m.alt)?;
obj.set("shift", m.shift)?;
obj.set("platform", m.cmd)?;
Ok(obj)
}
fn payload_value<'js>(cx: &Ctx<'js>, value: &PayloadValue) -> rquickjs::Result<Value<'js>> {
Ok(match value {
PayloadValue::Number(n) => Value::new_float(cx.clone(), *n),
PayloadValue::Bool(b) => Value::new_bool(cx.clone(), *b),
PayloadValue::Str(s) => rquickjs::String::from_str(cx.clone(), s)?.into_value(),
PayloadValue::Null => Value::new_null(cx.clone()),
PayloadValue::Point(p) => point_object(cx, *p)?.into_value(),
PayloadValue::Size(s) => size_object(cx, *s)?.into_value(),
PayloadValue::Bounds(b) => bounds_object(cx, *b)?.into_value(),
})
}
fn describe(value: Value<'_>) -> String {
match value.as_exception() {
Some(e) => e.to_string(),
None => format!("{value:?}"),
}
}
pub(crate) const GLOBALS: &str = r#"declare var console: {
log(...data: unknown[]): void;
info(...data: unknown[]): void;
debug(...data: unknown[]): void;
warn(...data: unknown[]): void;
error(...data: unknown[]): void;
};
declare var performance: {
/** Milliseconds since the JS context started, with sub-millisecond precision. */
now(): number;
};
interface ImportMeta {
/** The module's own URL: `file:` in the app's directory on desktop hosts,
* the page's on the web, `asset:/` in packaged mobile apps, so
* `new URL("./data.json", import.meta.url)` names a file beside it. */
readonly url: string;
}
declare function setTimeout(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): number;
declare function setInterval(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): number;
declare function clearTimeout(id: number | undefined): void;
declare function clearInterval(id: number | undefined): void;
declare function queueMicrotask(callback: () => void): void;
/** Runs `callback` at the next display frame with its time in milliseconds. */
declare function requestAnimationFrame(callback: (time: number) => void): number;
declare function cancelAnimationFrame(id: number | undefined): void;
declare function atob(data: string): string;
declare function btoa(data: string): string;
/** `<If when={…} else={…}>…</If>`: renders its children while `when` is
* truthy, else `else`. A function child gets an accessor of `when`'s value,
* which is set while it shows: `<If when={user()}>{(u) => <Text>{u().name}</Text>}</If>`.
* A global (no import), like `Each`. */
declare function If<T>(props: {
when: T;
else?: import("./types").JSX.Element;
children?: import("./types").JSX.Element | ((value: () => NonNullable<T>) => import("./types").JSX.Element);
}): import("./types").JSX.Element;
declare function If(props: {
when: unknown;
else?: import("./types").JSX.Element;
children?: import("./types").JSX.Element;
}): import("./types").JSX.Element;
/** `<Each of={items} key={…}>{(item, index) => …}</Each>`: renders
* `children(item, index)` for each item of `of` (`item()` and `index()`
* follow the row); rows are kept by `key` (default: the item; objects by
* identity, other values by value). `key="index"` keeps rows by position:
* a changed item updates its row's `item()` instead of making a new row
* (a list of strings streamed in, edited in place). A global. */
declare function Each<T>(props: {
of: readonly T[] | null | undefined;
key?: "index" | ((item: T, index: number) => unknown);
children: (item: () => T, index: () => number) => import("./types").JSX.Element;
}): import("./types").JSX.Element;
declare class DOMException extends Error {
constructor(message?: string, name?: string);
readonly name: string;
readonly message: string;
readonly code: number;
}
"#;
fn install(cx: &Ctx<'_>, shared: &Rc<Shared>) -> rquickjs::Result<()> {
let globals = cx.globals();
console::install(cx)?;
web::install(cx.as_raw().as_ptr())?;
crate::chunks::install(cx.as_raw().as_ptr()).map_err(|_| rquickjs::Error::Exception)?;
crate::dom::install_globals(cx.as_raw().as_ptr());
for (name, repeat) in [("setTimeout", false), ("setInterval", true)] {
let s = shared.clone();
globals.set(
name,
Function::new(
cx.clone(),
move |callback: Function<'_>, delay: Opt<f64>| -> u32 {
let ms = delay.0.unwrap_or(0.0);
let delay = Duration::from_secs_f64(if ms.is_finite() && ms > 0.0 {
ms / 1000.0
} else {
0.0
});
let callback = Persistent::save(&callback.ctx().clone(), callback);
s.timers.borrow_mut().add(callback, delay, repeat)
},
)?,
)?;
}
let s = shared.clone();
globals.set(
"requestAnimationFrame",
Function::new(cx.clone(), move |callback: Function<'_>| -> u32 {
let id = s.next_frame_id.get().wrapping_add(1).max(1);
s.next_frame_id.set(id);
let callback = Persistent::save(&callback.ctx().clone(), callback);
s.frames.borrow_mut().push((id, callback));
id
})?,
)?;
let s = shared.clone();
globals.set(
"cancelAnimationFrame",
Function::new(cx.clone(), move |id: Opt<Value<'_>>| {
if let Some(id) = handle_id(id) {
s.frames.borrow_mut().retain(|(i, _)| *i != id);
}
})?,
)?;
for name in ["clearTimeout", "clearInterval"] {
let s = shared.clone();
globals.set(
name,
Function::new(cx.clone(), move |id: Opt<Value<'_>>| {
if let Some(id) = handle_id(id) {
s.timers.borrow_mut().cancel(id);
}
})?,
)?;
}
Ok(())
}
fn handle_id(id: Opt<Value<'_>>) -> Option<u32> {
let id = id.0?;
let n = match id.as_number() {
Some(n) => n,
None => id
.as_string()?
.to_string()
.ok()?
.trim()
.parse::<f64>()
.ok()?,
};
let n = n.trunc();
(n.is_finite() && n >= 1.0 && n <= f64::from(u32::MAX)).then_some(n as u32)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use nsh_core::{
EventKind, Op,
geometry::{point, px},
};
use super::*;
thread_local! {
pub(super) static SOURCELESS: Cell<bool> = const { Cell::new(false) };
}
#[test]
fn bytecode_only_vms_start_and_use_the_standard_apis_without_source() {
let imports: String = crate::standard::NAMES
.iter()
.enumerate()
.map(|(i, name)| format!("import * as m{i} from {name:?};\n"))
.collect();
let source = format!(
r#"{imports}
import {{ text }} from "nsh:rt";
for (const m of [{modules}]) if (typeof m !== "object") throw Error("module");
if (Buffer.from("nsh").toString("base64") !== "bnNo") throw Error("Buffer");
if (crypto.randomUUID().length !== 36 || typeof crypto.subtle !== "object") throw Error("crypto");
if (typeof process.platform !== "string" || typeof process.nextTick !== "function") throw Error("process");
if (typeof process.run !== "function" || typeof process.env !== "object") throw Error("process");
if (new URL("https://a.b/c").pathname !== "/c") throw Error("URL");
const socket = new WebSocket("ws://127.0.0.1:9/");
if (!(socket instanceof EventTarget) || socket.readyState !== WebSocket.CONNECTING) throw Error("WebSocket");
socket.close();
text("started");
"#,
modules = (0..crate::standard::NAMES.len())
.map(|i| format!("m{i}"))
.collect::<Vec<_>>()
.join(", ")
);
let bytecode = crate::compile_bytecode(&source, true).unwrap();
let harden = crate::compile_harden().unwrap();
SOURCELESS.set(true);
let host = Host::with_options(HostOptions {
harden: true,
harden_bytecode: Some(Arc::new(harden)),
..HostOptions::default()
});
SOURCELESS.set(false);
let host = host.unwrap();
let error = host.eval_source("export {};").unwrap_err();
assert!(error.message.contains("eval is not supported"), "{error}");
host.eval_bytecode(&bytecode).unwrap();
assert_eq!(reported(&host), ["started"]);
}
#[test]
fn strings_outside_a_text_are_reported_once_per_element() {
let host = Host::new().unwrap();
host.eval_source(
r#"import { append, element, insert, prop, text } from "nsh:rt";
const view = element("view");
insert(view, () => "a");
insert(view, () => "b");
const label = element("text");
insert(label, () => "shown");
// A Rust component places what is put in it.
const card = element("view");
prop(card, "component", "Card");
insert(card, () => "placed");
const scroll = element("scroll");
append(scroll, text("c"));"#,
)
.unwrap();
let tags = host
.cx
.with(|cx| crate::dom::unshown_text_tags(cx.as_raw().as_ptr()));
let bit = |t: nsh_core::Tag| 1u64 << t as u32;
assert_eq!(tags, bit(nsh_core::Tag::View) | bit(nsh_core::Tag::Scroll));
}
#[test]
fn resources_follow_their_source_and_count_the_latest_load_only() {
let host = Host::new().unwrap();
host.eval_source(&format!(
r#"{REPORT}
import {{ effect, resource, signal }} from "nsh";
const id = signal(1);
const loads = [];
globalThis.report = report;
globalThis.id = id;
globalThis.loads = loads;
globalThis.user = resource(id, (n, info) => new Promise((resolve, reject) => {{
loads.push({{ n, resolve, reject, info }});
info.signal.addEventListener("abort", () => report(`aborted ${{n}}`));
}}));
effect(() => report(`${{user.state()}}|${{user() ?? ""}}|${{user.error() ?? ""}}|${{user.loading()}}`));"#
))
.unwrap();
assert_eq!(reported(&host), ["pending|||true"]);
let step = |code: &str| {
host.eval_source(code).unwrap();
reported(&host)
};
assert_eq!(step("id.set(2);"), ["aborted 1"]);
assert_eq!(step(r#"loads[0].resolve("one");"#), Vec::<String>::new());
assert_eq!(step(r#"loads[1].resolve("two");"#), ["ready|two||false"]);
assert_eq!(
step("user.refetch(); report(`refetching ${loads[2].info.refetching}`);"),
["refreshing|two||true", "refetching true"]
);
assert_eq!(
step(r#"loads[2].reject(new Error("boom"));"#),
["errored|two|Error: boom|false"]
);
assert_eq!(step(r#"user.mutate("local");"#), ["ready|local||false"]);
assert!(step("id.set(null);").is_empty());
host.eval_source("if (loads.length !== 3) throw new Error(`${loads.length} loads`);")
.unwrap();
}
#[test]
fn resources_without_a_source_with_values_and_throws() {
let host = Host::new().unwrap();
host.eval_source(&format!(
r#"{REPORT}
import {{ effect, resource }} from "nsh";
const now = resource(() => 42);
const kept = resource(() => new Promise(() => {{}}), {{ initialValue: "first" }});
const thrown = resource(() => {{ throw new Error("no"); }});
effect(() => report(`${{now.state()}} ${{now()}} | ${{kept.state()}} ${{kept()}} | ${{thrown.state()}} ${{thrown.error()}}`));
// The methods are bound: they work taken off their resource.
const {{ loading, state }} = kept;
report(`${{loading()}} ${{state()}}`);"#
))
.unwrap();
assert_eq!(
reported(&host),
[
"ready 42 | refreshing first | errored Error: no",
"true refreshing"
]
);
}
#[test]
fn a_resource_going_with_its_owner_aborts_its_load() {
let host = Host::new().unwrap();
host.eval_source(&format!(
r#"{REPORT}
import {{ cond, component, element, insert }} from "nsh:rt";
import {{ effect, resource, signal }} from "nsh";
const shown = signal(true);
globalThis.shown = shown;
function Card() {{
const r = resource((info) => new Promise((resolve) => {{
globalThis.later = resolve;
info.signal.addEventListener("abort", () => report("aborted"));
}}));
effect(() => report(r.state()));
return element("view");
}}
const root = element("view");
insert(root, cond(() => shown(), () => component(Card, {{}})));"#
))
.unwrap();
assert_eq!(reported(&host), ["pending"]);
host.eval_source("shown.set(false);").unwrap();
assert_eq!(reported(&host), ["aborted"]);
host.eval_source(r#"later("late");"#).unwrap();
assert!(reported(&host).is_empty());
}
#[test]
fn a_function_an_effect_returns_is_its_cleanup() {
let host = Host::new().unwrap();
host.eval_source(&format!(
r#"{REPORT}
import {{ cond, component, element, insert }} from "nsh:rt";
import {{ effect, signal }} from "nsh";
const n = signal(0);
const shown = signal(true);
globalThis.n = n;
globalThis.shown = shown;
function Ticker() {{
effect(() => {{
const v = n();
report(`run ${{v}}`);
return () => report(`cleanup ${{v}}`);
}});
// An async effect's promise is not a cleanup.
effect(async () => {{ n(); }});
return element("view");
}}
const root = element("view");
insert(root, cond(() => shown(), () => component(Ticker, {{}})));"#
))
.unwrap();
assert_eq!(reported(&host), ["run 0"]);
host.eval_source("n.set(1);").unwrap();
assert_eq!(reported(&host), ["cleanup 0", "run 1"]);
host.eval_source("shown.set(false);").unwrap();
assert_eq!(reported(&host), ["cleanup 1"]);
}
fn ops(host: &Host) -> Vec<Op> {
let mut out = Vec::new();
host.take_ops(&mut out);
out
}
const REPORT: &str = r#"import { text } from "nsh:rt";
const report = (v) => text(String(v));
"#;
fn reported(host: &Host) -> Vec<String> {
ops(host)
.into_iter()
.filter_map(|op| match op {
Op::CreateText { text, .. } => Some(text),
_ => None,
})
.collect()
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn native_future_wakes_engine_and_resumes_without_idle_polling() {
let host = Host::new().unwrap();
host.scheduler.start_io().unwrap();
let (send, receive) = std::sync::mpsc::channel();
host.set_system_wake(Arc::new(move || {
let _ = send.send(());
}));
host.cx.with(|cx| {
cx.globals().set("nativeFutureDone", false).unwrap();
let owned = cx.clone();
cx.spawn(async move {
tokio::time::sleep(Duration::from_millis(25)).await;
owned.globals().set("nativeFutureDone", true).unwrap();
});
});
host.run_jobs();
assert!(host.has_system_tasks());
assert!(
!host
.cx
.with(|cx| cx.globals().get::<_, bool>("nativeFutureDone").unwrap())
);
receive
.recv_timeout(Duration::from_secs(2))
.expect("native timer wakes owning engine");
host.run_system();
assert!(
host.cx
.with(|cx| cx.globals().get::<_, bool>("nativeFutureDone").unwrap())
);
assert!(!host.has_system_tasks());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn dropping_host_cancels_pending_native_future_and_wake_callback() {
struct Dropped(Arc<AtomicBool>);
impl Drop for Dropped {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let dropped = Arc::new(AtomicBool::new(false));
let callback_dropped = Arc::new(AtomicBool::new(false));
let host = Host::new().unwrap();
host.scheduler.start_io().unwrap();
let callback_guard = Dropped(callback_dropped.clone());
host.set_system_wake(Arc::new(move || {
let _ = &callback_guard;
}));
let guard = Dropped(dropped.clone());
host.cx.with(|cx| {
let owned = cx.clone();
cx.spawn(async move {
let (_guard, _owned) = (guard, owned);
tokio::time::sleep(Duration::from_secs(60)).await;
});
});
host.run_jobs();
assert!(host.has_system_tasks());
drop(host);
assert!(
dropped.load(Ordering::SeqCst),
"pending future must be destroyed with VM"
);
assert!(
callback_dropped.load(Ordering::SeqCst),
"engine callback must not retain old generation"
);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn stopping_host_cancels_native_work_without_dropping_snapshot() {
struct Dropped(Arc<AtomicBool>);
impl Drop for Dropped {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let dropped = Arc::new(AtomicBool::new(false));
let callback_dropped = Arc::new(AtomicBool::new(false));
let host = Host::new().unwrap();
host.scheduler.start_io().unwrap();
let callback_guard = Dropped(callback_dropped.clone());
host.set_system_wake(Arc::new(move || {
let _ = &callback_guard;
}));
let guard = Dropped(dropped.clone());
host.cx.with(|cx| {
let owned = cx.clone();
cx.spawn(async move {
let (_guard, _owned) = (guard, owned);
tokio::time::sleep(Duration::from_secs(60)).await;
});
});
host.run_jobs();
assert!(host.has_system_tasks());
host.eval_source(&format!("{REPORT}report('frozen UI');"))
.unwrap();
host.stop("test stop".into());
assert!(!host.cx.is_live());
assert!(host.rt.borrow().is_none());
assert_eq!(reported(&host), ["frozen UI"]);
assert!(!host.has_system_tasks());
assert!(!host.has_posted());
assert!(!host.wants_frame());
assert!(host.next_timer().is_none());
assert_eq!(host.object_count(), 0);
host.run_jobs();
host.run_system();
host.run_posted();
host.run_frame();
host.collect_garbage();
host.set_stop_flag(Arc::new(AtomicBool::new(false)));
host.take_chunk_requests(&mut Vec::new());
assert!(host.eval_source("throw 1").is_err());
host.stop("repeated stop".into());
assert!(
dropped.load(Ordering::SeqCst),
"pending future must be destroyed with VM"
);
assert!(
callback_dropped.load(Ordering::SeqCst),
"engine callback must not retain old generation"
);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn top_level_await_resumes_and_reports_rejection_on_native_wake() {
let mut host = Host::new().unwrap();
host.scheduler.start_io().unwrap();
let errors = Rc::new(RefCell::new(Vec::new()));
let captured = errors.clone();
host.set_error_handler(Box::new(move |error| {
captured.borrow_mut().push(error.message.clone())
}));
let (send, receive) = std::sync::mpsc::channel();
host.set_system_wake(Arc::new(move || {
let _ = send.send(());
}));
host.cx.with(|cx| {
let promise = Promise::wrap_future(&cx, async {
tokio::time::sleep(Duration::from_millis(25)).await;
7
})
.unwrap();
cx.globals().set("nativePending", promise).unwrap();
});
host.eval_source("await nativePending; throw new Error('native TLA rejected');")
.unwrap();
assert_eq!(host.evaluations.borrow().len(), 1);
receive.recv_timeout(Duration::from_secs(2)).unwrap();
host.run_system();
assert!(host.evaluations.borrow().is_empty());
assert!(
errors
.borrow()
.iter()
.any(|error| error.contains("native TLA rejected"))
);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn oom_retires_pending_native_future_without_dropping_host() {
struct Dropped(Arc<AtomicBool>);
impl Drop for Dropped {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
let dropped = Arc::new(AtomicBool::new(false));
let host = sandboxed(Limits {
memory_bytes: 16 << 20,
..Limits::default()
});
host.scheduler.start_io().unwrap();
let guard = Dropped(dropped.clone());
host.cx.with(|cx| {
cx.spawn(async move {
let _guard = guard;
tokio::time::sleep(Duration::from_secs(60)).await;
})
});
host.run_jobs();
let _ = host.eval_source(
"try { const keep=[]; for (;;) keep.push(new Array(100000).fill(1)); } catch (_) {}",
);
assert!(host.fatal().is_some());
assert!(!host.cx.is_live());
assert!(host.rt.borrow().is_none());
assert!(dropped.load(Ordering::SeqCst));
assert!(!host.has_system_tasks());
}
#[test]
fn stopping_host_releases_exit_delegate_and_refuses_replacement() {
let host = Host::new().unwrap();
let captured = Rc::new(());
let retained = captured.clone();
host.set_exit_handler(Rc::new(move |_| {
let _ = &retained;
}));
assert_eq!(Rc::strong_count(&captured), 2);
host.stop("test exit delegate lifetime".into());
assert_eq!(Rc::strong_count(&captured), 1);
assert!(host.shared.system_exit_handler.borrow().is_none());
let retained = captured.clone();
host.set_exit_handler(Rc::new(move |_| {
let _ = &retained;
}));
assert_eq!(Rc::strong_count(&captured), 1);
assert!(host.shared.system_exit_handler.borrow().is_none());
host.stop("idempotent stop".into());
}
#[test]
fn hover_payload_has_both_positions_and_the_modifiers() {
let host = Host::new().unwrap();
let event = nsh_core::HoverEvent {
position: point(px(3.0), px(4.5)),
page_position: point(px(30.0), px(40.5)),
modifiers: nsh_core::keymap::Modifiers {
shift: true,
cmd: true,
..Default::default()
},
};
host.cx.with(|cx| {
let value = payload_object(&cx, &EventPayload::Hover(event)).unwrap();
let obj = value.as_object().unwrap();
let num = |o: &str, k: &str| {
let o: rquickjs::Object = obj.get(o).unwrap();
o.get::<_, f64>(k).unwrap()
};
let flag = |k: &str| {
let m: rquickjs::Object = obj.get("modifiers").unwrap();
m.get::<_, bool>(k).unwrap()
};
assert_eq!(
(
num("position", "x"),
num("position", "y"),
num("pagePosition", "x"),
num("pagePosition", "y")
),
(3.0, 4.5, 30.0, 40.5)
);
assert!(flag("shift") && flag("platform"));
assert!(!flag("alt") && !flag("control"));
});
}
#[test]
fn context_menu_payload_has_both_positions() {
let host = Host::new().unwrap();
let event = nsh_core::ContextMenuEvent {
position: point(px(1.0), px(2.0)),
page_position: point(px(11.0), px(22.0)),
modifiers: nsh_core::keymap::Modifiers {
ctrl: true,
..Default::default()
},
};
host.cx.with(|cx| {
let value = payload_object(&cx, &EventPayload::ContextMenu(event)).unwrap();
let obj = value.as_object().unwrap();
let num = |o: &str, k: &str| {
let o: rquickjs::Object = obj.get(o).unwrap();
o.get::<_, f64>(k).unwrap()
};
assert_eq!(
(
num("position", "x"),
num("position", "y"),
num("pagePosition", "x"),
num("pagePosition", "y")
),
(1.0, 2.0, 11.0, 22.0)
);
let m: rquickjs::Object = obj.get("modifiers").unwrap();
assert!(m.get::<_, bool>("control").unwrap());
assert!(!m.get::<_, bool>("platform").unwrap());
});
}
#[test]
fn file_drop_payload_keeps_the_native_uri_list() {
let host = Host::new().unwrap();
let uris = vec![
"file:///tmp/a%20b.txt".into(),
"file:///tmp/%E4%B8%AD%E6%96%87/".into(),
];
host.cx.with(|cx| {
let value = payload_object(&cx, &EventPayload::FileDrop(uris.clone())).unwrap();
let actual: Vec<String> = value.as_object().unwrap().get("uris").unwrap();
assert_eq!(actual, uris);
});
}
#[test]
fn styles_decode_shadows_and_corners() {
let host = Host::new().unwrap();
host.eval_source(
r##"import { element, prop } from "nsh:rt";
prop(element("view"), "style", {
flexDirection: "row", backgroundColor: "#ff0000", bogus: 1,
shadowColor: "#000", shadowOffset: { width: 2, height: 6 },
shadowOpacity: 0.25, shadowRadius: 10,
borderRadius: 12, borderBottomLeftRadius: 0,
});
prop(element("view"), "style", { shadowOffset: null });"##,
)
.unwrap();
let styles: Vec<_> = ops(&host)
.into_iter()
.filter_map(|op| match op {
Op::SetStyle { style, .. } => Some(style),
_ => None,
})
.collect();
let style = &styles[0];
assert_eq!(format!("{:?}", style.layout.flex_direction), "Row");
assert_eq!(style.view.background_color, nsh_core::Color(0xff00_00ff));
let shadow = style.view.shadow;
assert_eq!((shadow.offset_x.0, shadow.offset_y.0), (2.0, 6.0));
assert_eq!((shadow.opacity, shadow.radius.0), (0.25, 10.0));
assert_eq!(
style.view.radii().to_array().map(|r| r.0),
[12.0, 12.0, 12.0, 0.0]
);
assert_eq!(styles[1].view.shadow, nsh_core::Shadow::DEFAULT);
}
#[test]
fn styles_flatten_nested_lists() {
let host = Host::new().unwrap();
host.eval_source(
r##"import { element, prop } from "nsh:rt";
const inner = [{ opacity: 0.5 }, false, [null, { backgroundColor: "#00ff00" }]];
prop(element("view"), "style", [
{ flexDirection: "row", backgroundColor: "#ff0000", opacity: 1 },
inner,
undefined,
]);"##,
)
.unwrap();
let style = ops(&host)
.into_iter()
.find_map(|op| match op {
Op::SetStyle { style, .. } => Some(style),
_ => None,
})
.unwrap();
assert_eq!(format!("{:?}", style.layout.flex_direction), "Row");
assert_eq!(style.view.background_color, nsh_core::Color(0x00ff_00ff));
assert_eq!(style.view.opacity, 0.5);
}
#[test]
fn intl_formats_numbers_and_dates() {
let host = Host::new().unwrap();
host.eval_source(&format!(
r#"{REPORT}
report((1234567.891).toLocaleString());
report((1234.5).toLocaleString("de-DE", {{ style: "currency", currency: "EUR" }}));
report((0.256).toLocaleString("en-US", {{ style: "percent", maximumFractionDigits: 1 }}));
report(12345678901234567890n.toLocaleString("en-US"));
const compact = new Intl.NumberFormat("en", {{ notation: "compact" }});
report([1234, 1500000, 999999].map(compact.format).join(" "));
report(new Intl.NumberFormat("en", {{ signDisplay: "always", minimumFractionDigits: 2 }}).format(3));
report(new Intl.NumberFormat("en", {{ useGrouping: false }}).format(12345));
report(JSON.stringify(new Intl.NumberFormat("en", {{ style: "currency", currency: "USD" }}).formatToParts(-1.5)));
report(new Intl.NumberFormat("fr").resolvedOptions().locale);
const at = Date.UTC(2026, 9, 16, 15, 4, 5);
const utc = {{ timeZone: "UTC" }};
report(new Intl.DateTimeFormat("en-US", {{ ...utc, hour: "2-digit", minute: "2-digit", hour12: false }}).format(at));
report(new Date(at).toLocaleString("en-US", utc));
report(new Date(at).toLocaleDateString("en-US", {{ ...utc, dateStyle: "full" }}));
report(new Date(at).toLocaleTimeString("ko-KR", {{ timeZone: "+09:00" }}));
report(new Intl.DateTimeFormat("en-US", {{ timeZone: "UTC", dateStyle: "medium", timeStyle: "short" }}).format(new Date(at)));
report(new Intl.DateTimeFormat().resolvedOptions().locale);
report(new Date(NaN).toLocaleString());
try {{ new Intl.NumberFormat("en", {{ style: "currency" }}); }} catch (e) {{ report(e.name); }}
try {{ new Intl.DateTimeFormat("en", {{ timeZone: "Mars/Olympus" }}); }} catch (e) {{ report(e.name); }}
report(Intl.NumberFormat.supportedLocalesOf(["xx", "ja-jp"]).join());
report(Object.prototype.toString.call(Intl));
"#
))
.unwrap();
assert_eq!(
reported(&host),
[
"1,234,567.891",
"1.234,50\u{a0}€",
"25.6%",
"12,345,678,901,234,567,890",
"1.2K 1.5M 1M",
"+3.00",
"12345",
r#"[{"type":"minusSign","value":"-"},{"type":"currency","value":"$"},{"type":"integer","value":"1"},{"type":"decimal","value":"."},{"type":"fraction","value":"50"}]"#,
"fr",
"15:04",
"10/16/2026, 3:04:05 PM",
"Friday, October 16, 2026",
"오전 12:04:05",
"Oct 16, 2026, 3:04 PM",
"en-US",
"Invalid Date",
"TypeError",
"RangeError",
"ja-JP",
"[object Intl]",
]
);
}
#[test]
fn timers_fire_in_order_and_cancel() {
let host = Host::new().unwrap();
host.eval_source(
r#"
globalThis.log = [];
setTimeout(() => log.push("b"), 20);
setTimeout(() => log.push("a"), 0);
const c = setTimeout(() => log.push("cancelled"), 10);
clearTimeout(c);
Promise.resolve().then(() => log.push("micro"));
"#,
)
.unwrap();
let deadline = Instant::now() + Duration::from_millis(30);
while let Some(next) = host.next_timer() {
std::thread::sleep(next.saturating_duration_since(Instant::now()));
host.run_timers(Instant::now());
assert!(Instant::now() < deadline + Duration::from_secs(1));
}
host.eval_source(&format!("{REPORT}report(log.join(\",\"));"))
.unwrap();
assert_eq!(reported(&host), ["micro,a,b"]);
}
#[test]
fn clearing_ids_that_name_no_timer_is_ignored() {
let host = Host::new().unwrap();
host.eval_source(
r#"
globalThis.log = [];
const t = setTimeout(() => log.push("timeout"), 0);
const i = setInterval(() => { log.push("interval"); clearInterval(i); }, 0);
const f = requestAnimationFrame(() => log.push("frame"));
for (const clear of [clearTimeout, clearInterval, cancelAnimationFrame]) {
clear();
for (const id of [undefined, null, 0, -1, NaN, Infinity, 1e12, 0.5, 99999, "x", "", {}, [], true, Symbol()])
clear(id);
}
const gone = setTimeout(() => log.push("cancelled by string"), 0);
clearTimeout(String(gone));
const gone2 = setTimeout(() => log.push("cancelled by fraction"), 0);
clearTimeout(gone2 + 0.7);
const gone3 = requestAnimationFrame(() => log.push("cancelled frame"));
cancelAnimationFrame(gone3);
"#,
)
.unwrap();
host.run_frame();
while let Some(next) = host.next_timer() {
std::thread::sleep(next.saturating_duration_since(Instant::now()));
host.run_timers(Instant::now());
}
host.eval_source(&format!("{REPORT}report(log.join(\",\"));"))
.unwrap();
assert_eq!(reported(&host), ["frame,timeout,interval"]);
}
fn sandboxed(limits: Limits) -> Host {
Host::with_options(HostOptions {
limits,
harden: true,
..HostOptions::default()
})
.unwrap()
}
#[test]
fn calls_over_budget_are_interrupted_and_the_vm_goes_on() {
let mut host = sandboxed(Limits {
call_budget: Duration::from_millis(50),
..Limits::default()
});
let errors = Rc::new(RefCell::new(Vec::new()));
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(
r#"import { element, prop } from "nsh:rt";
globalThis.views = [true, false].map((loops) => {
const view = element("view");
prop(view, "onPress", () => {
// try/catch cannot swallow the interrupt.
try { if (loops) for (;;) {} } catch (e) {}
element("view");
});
return view;
});"#,
)
.unwrap();
ops(&host);
let start = Instant::now();
host.dispatch_event(2, EventKind::Press, &EventPayload::None);
assert!(start.elapsed() < Duration::from_secs(2));
let errors = errors.borrow().clone();
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(errors[0].contains("budget of 50 ms"), "{}", errors[0]);
assert!(ops(&host).is_empty());
host.dispatch_event(4, EventKind::Press, &EventPayload::None);
let created = ops(&host)
.into_iter()
.filter(|op| matches!(op, Op::Create { .. }))
.count();
assert_eq!(created, 1);
assert!(host.fatal().is_none());
}
#[test]
fn running_out_of_memory_stops_the_vm() {
let host = sandboxed(Limits {
memory_bytes: 16 << 20,
..Limits::default()
});
let err = host
.eval_source("const keep = []; for (;;) keep.push(new Array(100000).fill(1));")
.unwrap_err();
assert!(err.message.contains("limited to 16 MB"), "{}", err.message);
assert!(host.fatal().is_some());
assert!(
host.eval_source(r#"import { element } from "nsh:rt"; element("view");"#)
.is_err()
);
assert!(ops(&host).is_empty());
}
#[test]
fn running_out_of_memory_in_a_timer_stops_the_vm() {
let mut host = sandboxed(Limits {
memory_bytes: 16 << 20,
..Limits::default()
});
let errors = Rc::new(RefCell::new(Vec::new()));
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(
r#"const keep = [];
setTimeout(() => {
for (let n = 0; ; n++) {
const parts = [];
for (let i = 0; i < 1000; i++) parts.push(`{"path":"/a/b/c-${n}-${i}","children":[]}`);
keep.push(JSON.parse("[" + parts.join(",") + "]"));
}
}, 0);"#,
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
let errors = errors.borrow().clone();
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(errors[0].contains("limited to 16 MB"), "{}", errors[0]);
assert!(host.fatal().is_some());
}
#[test]
fn running_out_of_memory_stops_the_vm_even_when_caught() {
let mut host = sandboxed(Limits {
memory_bytes: 16 << 20,
..Limits::default()
});
let errors = Rc::new(RefCell::new(Vec::new()));
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(
r#"setTimeout(() => {
try {
const keep = [];
for (;;) keep.push(new Array(100000).fill(1));
} catch (e) {}
}, 0);"#,
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
let errors = errors.borrow().clone();
assert_eq!(errors.len(), 1, "{errors:?}");
assert!(
errors[0].contains("limited to 16 MB") && errors[0].contains("in pages"),
"{}",
errors[0]
);
assert!(host.fatal().is_some());
}
#[test]
fn too_many_changes_at_once_stop_the_vm() {
let host = sandboxed(Limits {
max_op_values: 1000,
..Limits::default()
});
assert!(
host.eval_source(
r#"import { element } from "nsh:rt"; for (let i = 0; i < 2000; i++) element("view");"#
)
.is_err()
);
assert!(host.fatal().unwrap().contains("more than 1000 changes"));
}
#[test]
fn hardened_vms_run_no_code_from_strings() {
let from_bytecode = Host::with_options(HostOptions {
harden: true,
harden_bytecode: Some(crate::compile_harden().unwrap().into()),
..HostOptions::default()
})
.unwrap();
for host in [sandboxed(Limits::default()), from_bytecode] {
hardened_vm_runs_no_code_from_strings(&host);
}
}
fn hardened_vm_runs_no_code_from_strings(host: &Host) {
host.eval_source(&(REPORT.to_owned()
+ r#"
const results = [];
const attempt = (f) => { try { f(); results.push("ran"); } catch (e) { results.push(e.constructor.name); } };
attempt(() => eval("1"));
attempt(() => new Function("return 1")());
attempt(() => (function () {}).constructor("return 1")());
attempt(() => (async function () {}).constructor("return 1"));
attempt(() => (function* () {}).constructor("yield 1"));
attempt(() => { "use strict"; Array.prototype.map = null; });
attempt(() => { "use strict"; Object.prototype.polluted = 1; });
// Ordinary code is unaffected.
class MyError extends Error { constructor() { super("x"); this.name = "MyError"; } }
attempt(() => { const e = new MyError(); if (e.name !== "MyError") throw new Error(); });
attempt(() => [1, 2].map((x) => x * 2));
// Members of the frozen prototypes can still be overridden on
// other objects (no override mistake), not on the prototypes.
attempt(() => {
"use strict";
function A() {}
A.prototype = Object.create(Object.prototype);
A.prototype.constructor = A;
const o = { toString: undefined };
o.toString = () => "mine";
const d = new Date(0);
d.toJSON = () => "j";
if (new A().constructor !== A || String(o) !== "mine" || JSON.stringify(d) !== '"j"') throw new Error();
if (({}).constructor !== Object || [].toString() !== "") throw new Error();
});
attempt(() => { "use strict"; Object.prototype.toString = null; });
report(results.join(","));
"#))
.unwrap();
assert_eq!(
reported(host),
[
"ReferenceError,TypeError,TypeError,TypeError,TypeError,TypeError,TypeError,ran,ran,ran,TypeError"
]
);
}
#[test]
fn development_vms_keep_eval() {
let host = Host::new().unwrap();
host.eval_source(&format!("{REPORT}report(eval(\"1 + 1\"));"))
.unwrap();
assert_eq!(reported(&host), ["2"]);
}
mod logs {
use std::cell::RefCell;
struct Capture;
thread_local! {
static LINES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
impl log::Log for Capture {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.target() == "js" && metadata.level() == log::Level::Error
}
fn log(&self, record: &log::Record<'_>) {
if self.enabled(record.metadata()) {
LINES.with_borrow_mut(|lines| lines.push(record.args().to_string()));
}
}
fn flush(&self) {}
}
static CAPTURE: Capture = Capture;
pub(super) fn capture() {
static INSTALL: std::sync::Once = std::sync::Once::new();
INSTALL.call_once(|| {
if log::set_logger(&CAPTURE).is_ok() {
log::set_max_level(log::LevelFilter::Error);
}
});
LINES.with_borrow_mut(Vec::clear);
}
pub(super) fn take() -> Vec<String> {
LINES.with_borrow_mut(std::mem::take)
}
}
fn rejections(lines: &[String]) -> Vec<&String> {
lines
.iter()
.filter(|l| l.contains("unhandled rejection"))
.collect()
}
#[test]
fn unhandled_rejections_are_logged_once_the_turn_ends() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(
r#"function fail() { return Promise.reject(new Error("boom")); }
fail();
Promise.reject("plain");"#,
)
.unwrap();
let lines = logs::take();
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(
lines[0].starts_with("unhandled rejection: Error: boom")
&& lines[0].contains("at fail"),
"{}",
lines[0]
);
assert_eq!(lines[1], "unhandled rejection: plain");
host.run_jobs();
host.collect_garbage();
assert!(logs::take().is_empty());
assert_eq!(host.pending_rejections(), 0);
}
#[test]
fn rejections_handled_in_the_same_turn_are_not_logged() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(
r#"// A handler attached later in the same code.
const p = Promise.reject(new Error("later"));
const other = 1 + 1;
p.catch(() => {});
// One attached by a microtask of the same turn.
const q = Promise.reject(new Error("micro"));
Promise.resolve().then(() => Promise.resolve()).then(() => q.catch(() => {}));
// Handled the usual ways.
Promise.reject(new Error("caught")).catch(() => {});
Promise.reject(new Error("then")).then(undefined, () => {});
Promise.reject(new Error("chain")).then(() => 1).catch(() => {});
(async () => { try { await Promise.reject(new Error("awaited")); } catch (e) {} })();
Promise.allSettled([Promise.reject(new Error("settled"))]);"#,
)
.unwrap();
assert_eq!(logs::take(), Vec::<String>::new());
assert_eq!(host.pending_rejections(), 0);
}
#[test]
fn a_rejection_left_by_a_chain_is_logged_once() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(r#"Promise.reject(new Error("chained")).then(() => 1);"#)
.unwrap();
let lines = logs::take();
assert_eq!(rejections(&lines).len(), 1, "{lines:?}");
assert!(lines[0].contains("chained"), "{}", lines[0]);
}
#[test]
fn async_functions_that_throw_unawaited_are_logged() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(
r#"async function now() { throw new Error("at once"); }
async function later() { await null; throw new TypeError("after await"); }
setTimeout(() => { now(); later(); }, 0);"#,
)
.unwrap();
assert!(logs::take().is_empty());
host.run_timers(Instant::now() + Duration::from_millis(1));
let lines = logs::take();
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(
lines[0].contains("at once") && lines[0].contains("at now"),
"{}",
lines[0]
);
assert!(lines[1].contains("after await"), "{}", lines[1]);
}
#[test]
fn a_rejection_handled_in_a_later_turn_is_logged_once() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(
r#"const p = Promise.reject(new Error("too late"));
setTimeout(() => p.catch(() => {}), 0);"#,
)
.unwrap();
assert_eq!(rejections(&logs::take()).len(), 1);
host.run_timers(Instant::now() + Duration::from_millis(1));
assert!(logs::take().is_empty());
assert_eq!(host.pending_rejections(), 0);
}
#[test]
fn rejections_go_to_the_handler_not_the_error_handler() {
logs::capture();
let mut host = Host::new().unwrap();
let (errors, rejected) = (
Rc::new(RefCell::new(Vec::new())),
Rc::new(RefCell::new(Vec::new())),
);
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
let seen = rejected.clone();
host.set_rejection_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(r#"Promise.reject(new Error("to the handler"));"#)
.unwrap();
assert!(errors.borrow().is_empty());
assert_eq!(rejected.borrow().len(), 1);
assert!(rejected.borrow()[0].starts_with("Error: to the handler"));
assert!(logs::take().is_empty());
}
#[test]
fn a_failing_bundle_is_not_an_unhandled_rejection() {
logs::capture();
let host = Host::new().unwrap();
let err = host
.eval_source(r#"throw new Error("top level");"#)
.unwrap_err();
assert!(err.message.contains("top level"), "{}", err.message);
assert!(rejections(&logs::take()).is_empty());
assert_eq!(host.pending_rejections(), 0);
}
#[test]
fn many_rejections_leave_nothing_behind() {
logs::capture();
let host = Host::new().unwrap();
host.eval_source(
r#"globalThis.reject = (n) => {
for (let i = 0; i < n; i++) {
Promise.reject(new Error("unhandled " + i));
Promise.reject(new Error("handled " + i)).catch(() => {});
(async () => { throw new Error("async " + i); })();
}
};
setTimeout(() => reject(1), 0);"#,
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
logs::take();
host.collect_garbage();
let before = host.object_count();
host.eval_script(
"rounds.js",
"for (let i = 0; i < 20; i++) setTimeout(() => reject(50), 0);",
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
assert_eq!(rejections(&logs::take()).len(), 20 * 50 * 2);
assert_eq!(host.pending_rejections(), 0);
host.collect_garbage();
assert!(
host.object_count() < before + 100,
"{} → {}",
before,
host.object_count()
);
}
#[test]
fn interrupts_and_running_out_of_memory_are_not_rejections() {
logs::capture();
let mut host = sandboxed(Limits {
call_budget: Duration::from_millis(50),
..Limits::default()
});
let errors = Rc::new(RefCell::new(Vec::new()));
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(
r#"setTimeout(async () => { await null; for (;;) {} }, 0);
setTimeout(async () => { try { for (;;) {} } catch (e) {} }, 0);"#,
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
assert_eq!(errors.borrow().len(), 2, "{:?}", errors.borrow());
assert!(
errors
.borrow()
.iter()
.all(|e| e.contains("budget of 50 ms"))
);
assert_eq!(rejections(&logs::take()), Vec::<&String>::new());
assert_eq!(host.pending_rejections(), 0);
let mut host = sandboxed(Limits {
memory_bytes: 16 << 20,
..Limits::default()
});
let errors = Rc::new(RefCell::new(Vec::new()));
let seen = errors.clone();
host.set_error_handler(Box::new(move |e| seen.borrow_mut().push(e.message.clone())));
host.eval_source(
r#"setTimeout(async () => {
const keep = [];
for (;;) keep.push(new Array(100000).fill(1));
}, 0);"#,
)
.unwrap();
host.run_timers(Instant::now() + Duration::from_millis(1));
assert_eq!(errors.borrow().len(), 1, "{:?}", errors.borrow());
assert!(errors.borrow()[0].contains("limited to 16 MB"));
assert_eq!(rejections(&logs::take()), Vec::<&String>::new());
}
}