Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(events): expose native device motion and orientation payloads
ldm0a2a71161b4dc
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rsindex 9f70246b8..7cb26fbe1 100644--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs@@ -1,4 +1,5 @@use super::super::constructors::*;+use super::super::events::{device_motion_event_constructor, device_orientation_event_constructor};use super::super::{animation_runtime::{animation_constructor_callback, keyframe_effect_constructor_callback},broadcast_channel::broadcast_channel_constructor_callback,@@ -152,6 +153,16 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(ConstructorKind::WheelEvent => {build_event_subclass_template(scope, EventSubclassKind::WheelEvent)}+ ConstructorKind::DeviceMotionEvent => {+ v8::FunctionTemplate::builder(device_motion_event_constructor)+ .length(1)+ .build(scope)+ }+ ConstructorKind::DeviceOrientationEvent => {+ v8::FunctionTemplate::builder(device_orientation_event_constructor)+ .length(1)+ .build(scope)+ }ConstructorKind::PointerEvent => {build_event_subclass_template(scope, EventSubclassKind::PointerEvent)}diff --git a/moli-renderer-v8/src/context_bootstrap/event_document.rs b/moli-renderer-v8/src/context_bootstrap/event_document.rsindex 4dbfb46ce..8dd88031c 100644--- a/moli-renderer-v8/src/context_bootstrap/event_document.rs+++ b/moli-renderer-v8/src/context_bootstrap/event_document.rs@@ -10,7 +10,7 @@ struct DocumentCreateEventArgs {interface: String,}-#[derive(Debug, PartialEq, Eq, strum::EnumString)]+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::EnumString)]#[strum(serialize_all = "lowercase", ascii_case_insensitive)]enum DocumentCreateEventKind {BeforeUnloadEvent,@@ -45,8 +45,8 @@ impl DocumentCreateEventKind {DocumentCreateEventKind::BeforeUnloadEvent => "Event",DocumentCreateEventKind::Event => "Event",DocumentCreateEventKind::CustomEvent => "CustomEvent",- DocumentCreateEventKind::DeviceMotionEvent => "Event",- DocumentCreateEventKind::DeviceOrientationEvent => "Event",+ DocumentCreateEventKind::DeviceMotionEvent => "DeviceMotionEvent",+ DocumentCreateEventKind::DeviceOrientationEvent => "DeviceOrientationEvent",DocumentCreateEventKind::DragEvent => "Event",DocumentCreateEventKind::UiEvent => "UIEvent",DocumentCreateEventKind::TextEvent => "TextEvent",@@ -66,6 +66,22 @@ fn throw_not_supported_dom_exception(scope: &mut v8::PinScope<'_, '_>, message:crate::context_bootstrap::throw_dom_exception_value(scope, message, "NotSupportedError");}+fn new_uninitialized_document_event<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ kind: DocumentCreateEventKind,+) -> Option<v8::Local<'s, v8::Object>> {+ let name = kind.constructor_name();+ let constructor =+ super::exposed_interfaces::ensure_intrinsic_interface_constructor(scope, name).ok()?;+ if kind == DocumentCreateEventKind::TextEvent {+ return new_uninitialized_text_event(scope);+ }+ let empty_type = v8str(scope, "");+ let event = constructor.new_instance(scope, &[empty_type.into()])?;+ set_event_initialized(scope, event, false);+ Some(event)+}+pub(super) fn document_create_event_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -78,30 +94,27 @@ pub(super) fn document_create_event_callback<'s>(throw_not_supported_dom_exception(scope, "The provided event type is not supported.");return;};- if kind == DocumentCreateEventKind::TextEvent {- match new_uninitialized_text_event(scope) {- Some(event) => rv.set(event.into()),- None => rv.set_undefined(),- }- return;- }- let ctor_name = kind.constructor_name();-- let global = scope.get_current_context().global(scope);- let Some(constructor_value) = global.get(scope, v8str(scope, ctor_name).into()) else {- rv.set_undefined();- return;+ let relevant_context = crate::native_bridge::node_relevant_context(scope, args.this())+ .unwrap_or_else(|| scope.get_current_context());+ // Exposure follows the Document's realm, while an operation's exception+ // belongs to the callee realm even when its receiver is from another one.+ let exposed = {+ let target_scope = &mut v8::ContextScope::new(scope, relevant_context);+ super::exposed_interfaces::is_window_interface_exposed(+ target_scope,+ kind.constructor_name(),+ )};- let Ok(constructor) = v8::Local::<v8::Function>::try_from(constructor_value) else {- rv.set_undefined();+ if !exposed {+ throw_not_supported_dom_exception(+ scope,+ "The provided event type is not exposed in this realm.",+ );return;- };- let empty_type = v8str(scope, "");- match constructor.new_instance(scope, &[empty_type.into()]) {- Some(event) => {- set_event_initialized(scope, event, false);- rv.set(event.into());- }+ }+ let target_scope = &mut v8::ContextScope::new(scope, relevant_context);+ match new_uninitialized_document_event(target_scope, kind) {+ Some(event) => rv.set(event.into()),None => rv.set_undefined(),}}diff --git a/moli-renderer-v8/src/context_bootstrap/event_template.rs b/moli-renderer-v8/src/context_bootstrap/event_template.rsindex 06c378297..4e147f6f3 100644--- a/moli-renderer-v8/src/context_bootstrap/event_template.rs+++ b/moli-renderer-v8/src/context_bootstrap/event_template.rs@@ -336,6 +336,7 @@ pub(super) fn install_event_template_bindings<'s>(install_event_base_bindings(scope, template);}super::events::install_value_event_template_bindings(scope, template, spec.interface.name());+ super::events::install_device_event_template_bindings(scope, template, spec.interface.name());match spec.interface.name() {"UIEvent" => {diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rsindex 2c1ba1669..1cc900b3c 100644--- a/moli-renderer-v8/src/context_bootstrap/events.rs+++ b/moli-renderer-v8/src/context_bootstrap/events.rs@@ -3,6 +3,7 @@ use crate::util::{get_private_value, utf16_units, v8_string, v8_string_from_utf1use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiObject};mod base;+mod device;mod init;mod kind;mod methods;@@ -10,6 +11,11 @@ mod subclasses;mod value;mod wrappers;+pub(in crate::context_bootstrap) use device::{+ device_motion_event_constructor, device_orientation_event_constructor,+ install_device_event_template_bindings,+};+pub(in crate::context_bootstrap) use value::{ValueEventKind, build_value_event_template, install_value_event_template_bindings,};diff --git a/moli-renderer-v8/src/context_bootstrap/events/device.rs b/moli-renderer-v8/src/context_bootstrap/events/device.rsnew file mode 100644index 000000000..32b4bf5ba--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/events/device.rs@@ -0,0 +1,421 @@+//! Script-constructed device events. Sensor delivery and permission prompting+//! are separate from these event payloads.++use super::{+ define_event_property, event_private_value, initialize_event_object_with_type,+ initialize_event_wrapper, new_event_state, set_event_private_value,+};+use crate::{+ util::{get_private_value, new_null_prototype_object, throw_type_error, v8str},+ web_api_interfaces, webidl,+};+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};++const ALPHA: &str = "__moliDeviceAlpha";+const BETA: &str = "__moliDeviceBeta";+const GAMMA: &str = "__moliDeviceGamma";+const ABSOLUTE: &str = "__moliDeviceAbsolute";+const X: &str = "__moliDeviceAccelerationX";+const Y: &str = "__moliDeviceAccelerationY";+const Z: &str = "__moliDeviceAccelerationZ";+const ACCELERATION: &str = "__moliDeviceAcceleration";+const ACCELERATION_WITH_GRAVITY: &str = "__moliDeviceAccelerationIncludingGravity";+const ROTATION_RATE: &str = "__moliDeviceRotationRate";+const INTERVAL: &str = "__moliDeviceInterval";++#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::DeviceOrientationEvent, enumerable, receiver)]+struct OrientationPrototype {+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, ALPHA))]+ alpha: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, BETA))]+ beta: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, GAMMA))]+ gamma: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, ABSOLUTE))]+ absolute: (),+}++#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::DeviceMotionEvent, enumerable, receiver)]+struct MotionPrototype {+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, ACCELERATION))]+ acceleration: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, ACCELERATION_WITH_GRAVITY))]+ acceleration_including_gravity: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, ROTATION_RATE))]+ rotation_rate: (),+ #[webapi(accessor_property, getter = event_payload_getter, data = v8str(scope, INTERVAL))]+ interval: (),+}++#[derive(WebApiObject)]+#[webapi(interface = web_api_interfaces::DeviceMotionEventAcceleration)]+struct AccelerationObject<'s> {+ #[webapi(prototype)]+ prototype: v8::Local<'s, v8::Object>,+ #[webapi(slot = X)]+ x: v8::Local<'s, v8::Value>,+ #[webapi(slot = Y)]+ y: v8::Local<'s, v8::Value>,+ #[webapi(slot = Z)]+ z: v8::Local<'s, v8::Value>,+}++#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::DeviceMotionEventAcceleration, enumerable, receiver)]+struct AccelerationPrototype {+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, X))]+ x: (),+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, Y))]+ y: (),+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, Z))]+ z: (),+}++#[derive(WebApiObject)]+#[webapi(interface = web_api_interfaces::DeviceMotionEventRotationRate)]+struct RotationRateObject<'s> {+ #[webapi(prototype)]+ prototype: v8::Local<'s, v8::Object>,+ #[webapi(slot = ALPHA)]+ alpha: v8::Local<'s, v8::Value>,+ #[webapi(slot = BETA)]+ beta: v8::Local<'s, v8::Value>,+ #[webapi(slot = GAMMA)]+ gamma: v8::Local<'s, v8::Value>,+}++#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::DeviceMotionEventRotationRate, enumerable, receiver)]+struct RotationRatePrototype {+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, ALPHA))]+ alpha: (),+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, BETA))]+ beta: (),+ #[webapi(accessor_property, getter = vector_getter, data = v8str(scope, GAMMA))]+ gamma: (),+}++// Convert inherited EventInit members first, followed by the derived members+// in Web IDL's lexicographic order, including each nested dictionary in place.+#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "DeviceOrientationEventInit")]+struct OrientationInit {+ #[webidl(default = false)]+ bubbles: bool,+ #[webidl(default = false)]+ cancelable: bool,+ #[webidl(default = false)]+ composed: bool,+ #[webidl(default = false)]+ absolute: bool,+ #[webidl(nullable, converter = "double")]+ alpha: Option<f64>,+ #[webidl(nullable, converter = "double")]+ beta: Option<f64>,+ #[webidl(nullable, converter = "double")]+ gamma: Option<f64>,+}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "DeviceMotionEventInit")]+struct MotionInit {+ #[webidl(default = false)]+ bubbles: bool,+ #[webidl(default = false)]+ cancelable: bool,+ #[webidl(default = false)]+ composed: bool,+ #[webidl(with = acceleration_member)]+ acceleration: Option<AccelerationInit>,+ #[webidl(name = "accelerationIncludingGravity", with = acceleration_member)]+ acceleration_including_gravity: Option<AccelerationInit>,+ #[webidl(converter = "double", default = 0.0)]+ interval: f64,+ #[webidl(name = "rotationRate", with = rotation_rate_member)]+ rotation_rate: Option<RotationRateInit>,+}++#[derive(Default, webidl::WebIdlDictionary)]+#[webidl(prefix = "DeviceMotionEventAccelerationInit")]+struct AccelerationInit {+ #[webidl(nullable, converter = "double")]+ x: Option<f64>,+ #[webidl(nullable, converter = "double")]+ y: Option<f64>,+ #[webidl(nullable, converter = "double")]+ z: Option<f64>,+}++#[derive(Default, webidl::WebIdlDictionary)]+#[webidl(prefix = "DeviceMotionEventRotationRateInit")]+struct RotationRateInit {+ #[webidl(nullable, converter = "double")]+ alpha: Option<f64>,+ #[webidl(nullable, converter = "double")]+ beta: Option<f64>,+ #[webidl(nullable, converter = "double")]+ gamma: Option<f64>,+}++fn nested_dictionary_member<'s, T: webidl::WebIdlDictionary<'s> + Default>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<Option<T>, webidl::WebIdlError> {+ let context = webidl::Context::member("DeviceMotionEventInit", name);+ let Some(value) = webidl::property_result(scope, object, name, context)?+ .filter(|value| !value.is_undefined())+ else {+ return Ok(None);+ };+ // An absent member leaves the event attribute null. A present null member+ // converts to an empty dictionary and creates a vector with null components.+ Ok(Some(+ webidl::parse_dictionary::<T>(scope, value, context)?.unwrap_or_default(),+ ))+}++fn acceleration_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<Option<AccelerationInit>, webidl::WebIdlError> {+ nested_dictionary_member(scope, object, name)+}++fn rotation_rate_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &'static str,+) -> Result<Option<RotationRateInit>, webidl::WebIdlError> {+ nested_dictionary_member(scope, object, name)+}++pub(in crate::context_bootstrap) fn install_device_event_template_bindings<'s>(+ scope: &mut v8::PinScope<'s, '_, ()>,+ template: v8::Local<'s, v8::FunctionTemplate>,+ name: &str,+) {+ let prototype = template.prototype_template(scope);+ match name {+ "DeviceOrientationEvent" => {+ OrientationPrototype::initialize_prototype_template(scope, prototype)+ }+ "DeviceMotionEvent" => MotionPrototype::initialize_prototype_template(scope, prototype),+ "DeviceMotionEventAcceleration" => {+ AccelerationPrototype::initialize_prototype_template(scope, prototype)+ }+ "DeviceMotionEventRotationRate" => {+ RotationRatePrototype::initialize_prototype_template(scope, prototype)+ }+ _ => {}+ }+}++fn event_payload_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ let name = args.data().to_rust_string_lossy(scope);+ if let Some(value) = event_private_value(scope, args.this(), &name) {+ rv.set(value);+ }+}++fn vector_getter<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ let name = args.data().to_rust_string_lossy(scope);+ if let Some(value) = get_private_value(scope, args.this(), &name) {+ rv.set(value);+ }+}++fn nullable_number<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: Option<f64>,+) -> v8::Local<'s, v8::Value> {+ match value {+ Some(value) => v8::Number::new(scope, value).into(),+ None => v8::null(scope).into(),+ }+}++fn acceleration_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: Option<AccelerationInit>,+) -> v8::Local<'s, v8::Value> {+ let Some(value) = value else {+ return v8::null(scope).into();+ };+ let prototype = super::super::exposed_interfaces::ensure_intrinsic_interface_prototype(+ scope,+ "DeviceMotionEventAcceleration",+ )+ .expect("DeviceMotionEventAcceleration intrinsic prototype should initialize");+ AccelerationObject::new(+ prototype,+ nullable_number(scope, value.x),+ nullable_number(scope, value.y),+ nullable_number(scope, value.z),+ )+ .bind(scope)+ .expect("DeviceMotionEventAcceleration should initialize")+ .into()+}++fn rotation_rate_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: Option<RotationRateInit>,+) -> v8::Local<'s, v8::Value> {+ let Some(value) = value else {+ return v8::null(scope).into();+ };+ let prototype = super::super::exposed_interfaces::ensure_intrinsic_interface_prototype(+ scope,+ "DeviceMotionEventRotationRate",+ )+ .expect("DeviceMotionEventRotationRate intrinsic prototype should initialize");+ RotationRateObject::new(+ prototype,+ nullable_number(scope, value.alpha),+ nullable_number(scope, value.beta),+ nullable_number(scope, value.gamma),+ )+ .bind(scope)+ .expect("DeviceMotionEventRotationRate should initialize")+ .into()+}++#[derive(Clone, Copy)]+enum DeviceEventKind {+ Orientation,+ Motion,+}++impl DeviceEventKind {+ fn name(self) -> &'static str {+ match self {+ Self::Orientation => "DeviceOrientationEvent",+ Self::Motion => "DeviceMotionEvent",+ }+ }+}++fn initialize_payload<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ kind: DeviceEventKind,+ dictionary: v8::Local<'s, v8::Object>,+ state: v8::Local<'s, v8::Object>,+) -> Result<(bool, bool, bool), webidl::WebIdlError> {+ match kind {+ DeviceEventKind::Orientation => {+ let parsed = webidl::parse_dictionary_object::<OrientationInit>(scope, dictionary)?;+ for (slot, value) in [+ (ALPHA, parsed.alpha),+ (BETA, parsed.beta),+ (GAMMA, parsed.gamma),+ ] {+ let value = nullable_number(scope, value);+ set_event_private_value(scope, state, slot, value);+ }+ set_event_private_value(+ scope,+ state,+ ABSOLUTE,+ v8::Boolean::new(scope, parsed.absolute).into(),+ );+ Ok((parsed.bubbles, parsed.cancelable, parsed.composed))+ }+ DeviceEventKind::Motion => {+ let parsed = webidl::parse_dictionary_object::<MotionInit>(scope, dictionary)?;+ let acceleration = acceleration_value(scope, parsed.acceleration);+ let acceleration_with_gravity =+ acceleration_value(scope, parsed.acceleration_including_gravity);+ let rotation_rate = rotation_rate_value(scope, parsed.rotation_rate);+ set_event_private_value(scope, state, ACCELERATION, acceleration);+ set_event_private_value(+ scope,+ state,+ ACCELERATION_WITH_GRAVITY,+ acceleration_with_gravity,+ );+ set_event_private_value(scope, state, ROTATION_RATE, rotation_rate);+ set_event_private_value(+ scope,+ state,+ INTERVAL,+ v8::Number::new(scope, parsed.interval).into(),+ );+ Ok((parsed.bubbles, parsed.cancelable, parsed.composed))+ }+ }+}++fn device_event_constructor<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+ kind: DeviceEventKind,+) {+ if !args.is_construct_call() {+ throw_type_error(scope, &format!("{} requires 'new'.", kind.name()));+ return;+ }+ if args.length() == 0 {+ throw_type_error(scope, &format!("{} requires a type argument.", kind.name()));+ return;+ }+ let Some(event_type) = args.get(0).to_string(scope) else {+ return;+ };+ let dictionary =+ match webidl::dictionary_arg(&args, 1, webidl::Context::argument(kind.name(), 2)) {+ Ok(dictionary) => dictionary.unwrap_or_else(|| new_null_prototype_object(scope)),+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }+ };+ let state = new_event_state(scope);+ let (bubbles, cancelable, composed) = match initialize_payload(scope, kind, dictionary, state) {+ Ok(flags) => flags,+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }+ };+ initialize_event_object_with_type(scope, state, event_type, bubbles, cancelable);+ define_event_property(+ scope,+ state,+ "composed",+ v8::Boolean::new(scope, composed).into(),+ );+ web_api_interfaces::initialize(scope, state, kind.name())+ .expect("device event brand should initialize");+ if initialize_event_wrapper(scope, args.this(), state).is_some() {+ rv.set(args.this().into());+ }+}++pub(in crate::context_bootstrap) fn device_orientation_event_constructor<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'_, v8::Value>,+) {+ device_event_constructor(scope, args, rv, DeviceEventKind::Orientation);+}++pub(in crate::context_bootstrap) fn device_motion_event_constructor<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'_, v8::Value>,+) {+ device_event_constructor(scope, args, rv, DeviceEventKind::Motion);+}diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rsindex 6c34dc38a..da8eed047 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/install.rs@@ -10,9 +10,9 @@ use super::realm_registry::{IntrinsicInterfaceRegistry, RealmInterfaceState};use super::template_registry::ExposedInterfaceTemplateRegistry;use crate::context_bootstrap::specs::ConstructorSpec;use crate::util::{- constructor_object, constructor_prototype_object, initialize_intrinsic_interface_registry,- register_intrinsic_interface, registered_intrinsic_constructor, registered_intrinsic_prototype,- v8str,+ constructor_object, constructor_prototype_object, get_private_value,+ initialize_intrinsic_interface_registry, register_intrinsic_interface,+ registered_intrinsic_constructor, registered_intrinsic_prototype, v8str,};const LEGACY_WINDOW_INTERFACE_ALIASES: &[(&str, &str)] = &[@@ -153,6 +153,28 @@ pub(crate) fn filter_window_exposed_interfaces(Ok(())}+/// Exposure is determined by the realm's native metadata, independently of+/// author changes to the corresponding global property.+pub(in crate::context_bootstrap) fn is_window_interface_exposed(+ scope: &mut v8::PinScope<'_, '_>,+ name: &str,+) -> bool {+ let global = scope.get_current_context().global(scope);+ let secure = get_private_value(+ scope,+ global,+ crate::context_bootstrap::runtime_state::WINDOW_SECURE_CONTEXT_AVAILABLE_SLOT,+ )+ .is_some_and(|value| value.boolean_value(scope));+ let Some(registry) = ExposedInterfaceTemplateRegistry::current(scope) else {+ return false;+ };+ registry+ .id_by_name(name)+ .and_then(|id| registry.metadata(id))+ .is_some_and(|metadata| metadata.is_exposed(RealmKind::Window, secure))+}+pub(crate) fn initialize_realm_interface_registry(scope: &mut v8::PinScope<'_, '_>,realm_kind: RealmKind,diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rsindex 04d03862c..40ca57a34 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs@@ -94,6 +94,10 @@ pub(in crate::context_bootstrap) const WORKER_SHARED_INTERFACE_NAMES: &[&str] =const SECURE_CONTEXT_ONLY_INTERFACE_NAMES: &[&str] = &["MediaDeviceInfo","InputDeviceInfo",+ "DeviceMotionEvent",+ "DeviceMotionEventAcceleration",+ "DeviceMotionEventRotationRate",+ "DeviceOrientationEvent","MediaDevices","SubtleCrypto","CryptoKey",diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/mod.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/mod.rsindex d97999d5a..bbacebf96 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/mod.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/mod.rs@@ -11,7 +11,7 @@ pub(crate) use install::capture_eager_intrinsic_interfaces;pub(super) use install::{filter_window_exposed_interfaces, initialize_realm_interface_registry,install_interface_template_metadata, install_window_exposed_interfaces,- install_worker_exposed_interfaces, is_lazy_exposed_interface,+ install_worker_exposed_interfaces, is_lazy_exposed_interface, is_window_interface_exposed,prepare_worker_event_target_template,};#[cfg(test)]diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rsindex 8071682df..472137b39 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs@@ -204,6 +204,22 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[interface: web_api_interfaces::BlobEvent::DESCRIPTOR,kind: ConstructorKind::BlobEvent,},+ ConstructorSpec {+ interface: web_api_interfaces::DeviceMotionEvent::DESCRIPTOR,+ kind: ConstructorKind::DeviceMotionEvent,+ },+ ConstructorSpec {+ interface: web_api_interfaces::DeviceMotionEventAcceleration::DESCRIPTOR,+ kind: ConstructorKind::Illegal,+ },+ ConstructorSpec {+ interface: web_api_interfaces::DeviceMotionEventRotationRate::DESCRIPTOR,+ kind: ConstructorKind::Illegal,+ },+ ConstructorSpec {+ interface: web_api_interfaces::DeviceOrientationEvent::DESCRIPTOR,+ kind: ConstructorKind::DeviceOrientationEvent,+ },ConstructorSpec {interface: web_api_interfaces::UIEvent::DESCRIPTOR,kind: ConstructorKind::UiEvent,diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rsindex b9500696d..3e6ab7e6b 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs@@ -19,6 +19,8 @@ pub(in crate::context_bootstrap) enum ConstructorKind {KeyboardEvent,InputEvent,WheelEvent,+ DeviceMotionEvent,+ DeviceOrientationEvent,PointerEvent,TouchEvent,MessageEvent,diff --git a/moli-renderer-v8/src/script_vm/tests/device_event_realms.js b/moli-renderer-v8/src/script_vm/tests/device_event_realms.jsnew file mode 100644index 000000000..a93f4c038--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/device_event_realms.js@@ -0,0 +1,19 @@+(() => {+ const other = document.getElementById('child').contentWindow;+ const rows = [];+ for (const [calleeName, callee] of [['main', globalThis], ['child', other]]) {+ for (const [ownerName, owner] of [['main', globalThis], ['child', other]]) {+ for (const kind of ['UnsupportedEvent', 'DeviceMotionEvent', 'DeviceOrientationEvent']) {+ let actual;+ try { callee.Document.prototype.createEvent.call(owner.document, kind); actual = ['no error']; }+ catch (error) {actual = [error.name, error instanceof callee.DOMException, error instanceof owner.DOMException];}+ const expected = ['NotSupportedError', true, callee === owner];+ rows.push({name: calleeName + '/' + ownerName + '/' + kind, expected, actual, pass: JSON.stringify(actual) === JSON.stringify(expected)});+ }+ }+ }+ rows.push({name: 'insecure-realms',expected:[false,false],actual:[isSecureContext,other.isSecureContext],pass: !isSecureContext && !other.isSecureContext});+ const failures=rows.filter(r => !r.pass);+ globalThis.__nodeReplacementResults={total:rows.length,passed:rows.length-failures.length,failures,rows};+ return failures.length === 0;+})()\ No newline at end of filediff --git a/moli-renderer-v8/src/script_vm/tests/device_events.js b/moli-renderer-v8/src/script_vm/tests/device_events.jsnew file mode 100644index 000000000..484e45ef5--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/device_events.js@@ -0,0 +1,157 @@+(() => {+ const other = document.getElementById('child').contentWindow;+ const realms = [['main', globalThis], ['iframe', other]];+ const rows = [];+ function check(name, expected, run) {+ let actual;+ try { actual = run(); } catch (error) { actual = {error: error.name, message: error.message}; }+ rows.push({name, expected, actual, pass: JSON.stringify(actual) === JSON.stringify(expected)});+ }+ function throwsTypeError(realm, run) {+ try { run(); } catch (error) { return error instanceof realm.TypeError; }+ return false;+ }+ function properties(event) {+ if ('alpha' in event)+ return [event.alpha, event.beta, event.gamma, event.absolute];+ const vector = (object, keys) => object === null ? null : keys.map(key => object[key]);+ return [vector(event.acceleration, ['x', 'y', 'z']),+ vector(event.accelerationIncludingGravity, ['x', 'y', 'z']),+ vector(event.rotationRate, ['alpha', 'beta', 'gamma']), event.interval];+ }+ const examples = [+ ['DeviceOrientationEvent', {alpha: 1, beta: -2, gamma: 3, absolute: true}, [1, -2, 3, true], [null, null, null, false]],+ ['DeviceMotionEvent', {acceleration: {x: 1, y: -2, z: 3}, accelerationIncludingGravity: {y: 4}, rotationRate: {alpha: 5}, interval: 6}, [[1, -2, 3], [null, 4, null], [5, null, null], 6], [null, null, null, 0]],+ ];+ for (const [homeName, home] of realms) for (const [kind, init, values, defaults] of examples) {+ const label = homeName + '/' + kind, Ctor = home[kind];+ check(label + '/exposure', 'function', () => typeof Ctor);+ if (typeof Ctor !== 'function') continue;+ check(label + '/inheritance', [true, true, true, 1, kind], () => [+ Object.getPrototypeOf(Ctor) === home.Event, Object.getPrototypeOf(Ctor.prototype) === home.Event.prototype,+ new Ctor('x') instanceof home.Event, Ctor.length, Ctor.name]);+ check(label + '/defaults', defaults, () => properties(new Ctor('x')));+ check(label + '/payload', values, () => properties(new Ctor('x', init)));+ check(label + '/base-event', ['x\uD800', true, true, true, false], () => {+ const event = new Ctor('x\uD800', {bubbles: true, cancelable: true, composed: true});+ return [event.type, event.bubbles, event.cancelable, event.composed, event.isTrusted];+ });+ check(label + '/requires-new-and-type', [true, true, true], () => [+ throwsTypeError(home, () => Ctor('x')), throwsTypeError(home, () => new Ctor()),+ throwsTypeError(home, () => new Ctor(Symbol('x')))]);+ for (const dictionary of [null, undefined]) check(label + '/nullish-' + dictionary, defaults, () => properties(new Ctor('x', dictionary)));+ for (const dictionary of [0, 'text', true, Symbol('dictionary')]) check(label + '/invalid-dictionary-' + typeof dictionary, true,+ () => throwsTypeError(home, () => new Ctor('x', dictionary)));+ check(label + '/constructor-subclass', [true, true, true], () => {+ class Subclass extends Ctor {}+ const event = new Subclass('x', init);+ return [event instanceof Subclass, event instanceof Ctor, JSON.stringify(properties(event)) === JSON.stringify(values)];+ });+ check(label + '/createEvent', [true, true, true], () => {+ const event = home.document.createEvent(kind.toLowerCase());+ const before = event.type === '' && JSON.stringify(properties(event)) === JSON.stringify(defaults);+ event.initEvent('ready', true, false);+ return [Object.getPrototypeOf(event) === Ctor.prototype, before, event.type === 'ready' && event.bubbles];+ });+ check(label + '/dispatch', [true, true, true], () => {+ const event = new Ctor('sensor', {...init, cancelable: true});+ const target = new home.EventTarget(); let seen = false;+ target.addEventListener('sensor', current => { seen = current === event && JSON.stringify(properties(current)) === JSON.stringify(values); current.preventDefault(); });+ return [!target.dispatchEvent(event), seen, event.target === target];+ });+ const fields = kind === 'DeviceOrientationEvent' ? ['alpha', 'beta', 'gamma', 'absolute'] : ['acceleration', 'accelerationIncludingGravity', 'rotationRate', 'interval'];+ for (const [calleeName, callee] of realms) {+ check(label + '/' + calleeName + '/createEvent-realm', [true, true], () => {+ const event = callee.Document.prototype.createEvent.call(home.document, kind);+ return [Object.getPrototypeOf(event) === Ctor.prototype,+ JSON.stringify(properties(event)) === JSON.stringify(defaults)];+ });+ for (const field of fields) {+ const descriptor = Object.getOwnPropertyDescriptor(callee[kind].prototype, field), real = new Ctor('x', init);+ check(label + '/' + calleeName + '/' + field + '/descriptor', ['function', 'get ' + field, 0, undefined, true, true, false], () => [typeof descriptor.get, descriptor.get.name, descriptor.get.length, descriptor.set, descriptor.enumerable, descriptor.configurable, Object.hasOwn(real, field)]);+ check(label + '/' + calleeName + '/' + field + '/genuine', true, () => descriptor.get.call(real) === real[field]);+ const revoked = Proxy.revocable(real, {}); revoked.revoke(); let traps = 0;+ for (const [index, receiver] of [null, undefined, {}, new home.Event('x'), Ctor.prototype, Object.create(real), new Proxy(real, {}), revoked.proxy,+ new Proxy(real, {get() {traps++;}, getPrototypeOf() {traps++;}})].entries())+ check(label + '/' + calleeName + '/' + field + '/invalid-' + index, true, () => throwsTypeError(callee, () => descriptor.get.call(receiver)));+ check(label + '/' + calleeName + '/' + field + '/no-traps', 0, () => traps);+ }+ }+ }+ for (const [name, realm] of realms) {+ if (typeof realm.DeviceOrientationEvent !== 'function' || typeof realm.DeviceMotionEvent !== 'function') continue;+ check(name + '/orientation-order', ['type', 'bubbles', 'cancelable', 'composed', 'absolute', 'alpha', 'beta', 'gamma'], () => {+ const order = [];+ new realm.DeviceOrientationEvent({toString() {order.push('type'); return 'x';}}, new Proxy({}, {get(_, key) {order.push(key);}}));+ return order;+ });+ check(name + '/motion-order', ['bubbles', 'cancelable', 'composed', 'acceleration', 'x', 'y', 'z', 'accelerationIncludingGravity', 'x', 'y', 'z', 'interval', 'rotationRate', 'alpha', 'beta', 'gamma'], () => {+ const order = [];+ new realm.DeviceMotionEvent('x', new Proxy({}, {get(_, key) {+ order.push(key);+ if (['acceleration', 'accelerationIncludingGravity', 'rotationRate'].includes(key)) return new Proxy({}, {get(_, inner) {order.push(inner);}});+ }}));+ return order;+ });+ check(name + '/conversion-exception', true, () => {+ const marker = new Error('dictionary');+ try { new realm.DeviceOrientationEvent('x', {get beta() {throw marker;}}); }+ catch (error) {return error === marker;}+ return false;+ });+ for (const field of ['alpha', 'beta', 'gamma']) {+ check(name + '/nullable-' + field, [null, null, 2, true], () => [+ new realm.DeviceOrientationEvent('x', {[field]: null})[field], new realm.DeviceOrientationEvent('x', {[field]: undefined})[field],+ new realm.DeviceOrientationEvent('x', {[field]: '2'})[field], Object.is(new realm.DeviceOrientationEvent('x', {[field]: -0})[field], -0)]);+ for (const [i, value] of [NaN, Infinity, -Infinity, 1n, Symbol('number')].entries())+ check(name + '/nonfinite-' + field + '-' + i, true, () => throwsTypeError(realm, () => new realm.DeviceOrientationEvent('x', {[field]: value})));+ }+ for (const field of ['acceleration', 'accelerationIncludingGravity', 'rotationRate']) {+ const type = field === 'rotationRate' ? 'DeviceMotionEventRotationRate' : 'DeviceMotionEventAcceleration';+ const keys = field === 'rotationRate' ? ['alpha', 'beta', 'gamma'] : ['x', 'y', 'z'];+ check(name + '/' + field + '/missing-null-empty', [true, true, true], () => [+ new realm.DeviceMotionEvent('x', {[field]: undefined})[field] === null,+ keys.every(k => new realm.DeviceMotionEvent('x', {[field]: null})[field][k] === null),+ keys.every(k => new realm.DeviceMotionEvent('x', {[field]: {}})[field][k] === null)]);+ check(name + '/' + field + '/vector', [true, '[object ' + type + ']', 0, true, true, true], () => {+ const source = {[keys[0]]: -0, [keys[1]]: '2'}, event = new realm.DeviceMotionEvent('x', {[field]: source}), vector = event[field];+ source[keys[1]] = 99;+ return [Object.getPrototypeOf(vector) === realm[type].prototype, Object.prototype.toString.call(vector), Object.keys(vector).length,+ vector === event[field], Object.is(vector[keys[0]], -0), vector[keys[1]] === 2];+ });+ for (const key of keys) {+ check(name + '/' + field + '/' + key + '/finite', true, () => throwsTypeError(realm, () => new realm.DeviceMotionEvent('x', {[field]: {[key]: Infinity}})));+ for (const [calleeName, callee] of realms) check(name + '/' + field + '/' + key + '/' + calleeName + '/brand', [true, true, true, true], () => {+ const vector = new realm.DeviceMotionEvent('x', {[field]: {[key]: 5}})[field];+ const getter = Object.getOwnPropertyDescriptor(callee[type].prototype, key).get;+ return [getter.call(vector) === 5, throwsTypeError(callee, () => getter.call({})),+ throwsTypeError(callee, () => getter.call(new Proxy(vector, {}))), throwsTypeError(callee, () => getter.call(Object.create(vector)))];+ });+ }+ check(name + '/' + field + '/illegal-constructor', [true, true], () => [throwsTypeError(realm, () => new realm[type]()), throwsTypeError(realm, () => realm[type]())]);+ for (const [i, value] of [true, 1, 'bad', Symbol('dictionary')].entries()) check(name + '/' + field + '/bad-dictionary-' + i, true,+ () => throwsTypeError(realm, () => new realm.DeviceMotionEvent('x', {[field]: value})));+ }+ check(name + '/interval-conversion', [0, 2, true, true], () => [new realm.DeviceMotionEvent('x', {interval: null}).interval,+ new realm.DeviceMotionEvent('x', {interval: '2'}).interval, Object.is(new realm.DeviceMotionEvent('x', {interval: -0}).interval, -0),+ throwsTypeError(realm, () => new realm.DeviceMotionEvent('x', {interval: NaN}))]);+ }+ check('lazy-vector-intrinsics-ignore-public-constructors', [0, 1, 2, 'DeviceMotionEventAcceleration', 'DeviceMotionEventRotationRate', true, false], () => {+ const frame = document.createElement('iframe'); document.body.appendChild(frame);+ try {+ const realm = frame.contentWindow, Motion = realm.DeviceMotionEvent;+ let reads = 0;+ const publicGetter = () => {reads++; throw new Error('public constructor getter');};+ Object.defineProperty(realm, 'DeviceMotionEventAcceleration', {configurable: true, get: publicGetter});+ delete realm.DeviceMotionEventRotationRate;+ const event = new Motion('x', {acceleration: {x: 1}, rotationRate: {alpha: 2}});+ return [reads, event.acceleration.x, event.rotationRate.alpha,+ Object.getPrototypeOf(event.acceleration).constructor.name, Object.getPrototypeOf(event.rotationRate).constructor.name,+ Object.getOwnPropertyDescriptor(realm, 'DeviceMotionEventAcceleration').get === publicGetter,+ Object.hasOwn(realm, 'DeviceMotionEventRotationRate')];+ } finally {frame.remove();}+ });+ globalThis.__deviceEventFailures = rows.filter(row => !row.pass);+ globalThis.__nodeReplacementResults = {total: rows.length, passed: rows.filter(row => row.pass).length, failures: __deviceEventFailures, rows};+ return rows.every(row => row.pass);+})()diff --git a/moli-renderer-v8/src/script_vm/tests/device_events.rs b/moli-renderer-v8/src/script_vm/tests/device_events.rsnew file mode 100644index 000000000..96ffe5e4c--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/device_events.rs@@ -0,0 +1,75 @@+use super::*;++#[test]+fn device_event_payloads_preserve_webidl_conversions_native_brands_and_realms() {+ let mut vm = new_parsed_test_vm(+ "https://device-events.test/",+ "<!doctype html><body><iframe id=child></iframe></body>",+ );+ vm.eval(include_str!("device_events.js")).unwrap();+ assert_eq!(+ vm.eval("JSON.stringify(__deviceEventFailures)").unwrap(),+ "[]"+ );+}++#[test]+fn device_event_exposure_errors_use_the_callee_realm() {+ let mut vm = new_parsed_test_vm(+ "http://device-events.test/",+ "<!doctype html><body><iframe id=child></iframe></body>",+ );+ vm.eval(include_str!("device_event_realms.js")).unwrap();+ assert_eq!(+ vm.eval("JSON.stringify(__nodeReplacementResults.failures)")+ .unwrap(),+ "[]"+ );+}++#[test]+fn device_event_exposure_and_legacy_creation_use_native_realm_metadata() {+ for (url, exposed) in [+ ("https://device-events.test/", true),+ ("http://device-events.test/", false),+ ("http://localhost/", true),+ ] {+ let mut vm = new_parsed_test_vm(url, "<!doctype html><body></body>");+ let types = vm+ .eval(+ r#"['DeviceMotionEvent', 'DeviceOrientationEvent',+ 'DeviceMotionEventAcceleration', 'DeviceMotionEventRotationRate']+ .map(name => typeof globalThis[name]).join(',')"#,+ )+ .unwrap();+ assert_eq!(+ types,+ if exposed {+ "function,function,function,function"+ } else {+ "undefined,undefined,undefined,undefined"+ },+ "{url}"+ );+ let result = vm.eval(r#"(() => {+ const rows = [];+ for (const name of ['Event', 'BeforeUnloadEvent', 'TextEvent', 'DeviceMotionEvent', 'DeviceOrientationEvent']) {+ Object.defineProperty(globalThis, name, {configurable: true, get() {throw new Error('public constructor');}});+ try {+ const event = document.createEvent(name);+ rows.push(Object.prototype.toString.call(event) + ':' + event.type);+ } catch(error) { rows.push(error.name); }+ }+ return JSON.stringify(rows);+ })()"#).unwrap();+ assert_eq!(+ result,+ if exposed {+ r#"["[object Event]:","[object Event]:","[object TextEvent]:","[object DeviceMotionEvent]:","[object DeviceOrientationEvent]:"]"#+ } else {+ r#"["[object Event]:","[object Event]:","[object TextEvent]:","NotSupportedError","NotSupportedError"]"#+ },+ "{url}"+ );+ }+}diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex f6bf3664b..730f32681 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2129,6 +2129,7 @@ mod canvas_arguments;mod canvas_paths;mod canvas_webgl;mod child_dynamic_inline_scripts;+mod device_events;mod dom_elements;mod dom_xhr;mod element_click;diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rsindex 525577f6a..7f531fa94 100644--- a/moli-renderer-v8/src/web_api_interfaces.rs+++ b/moli-renderer-v8/src/web_api_interfaces.rs@@ -128,6 +128,10 @@ interfaces! {DedicatedWorkerGlobalScope: WorkerGlobalScope;DeprecatedStorageInfo;DeprecatedStorageQuota;+ DeviceMotionEvent: Event;+ DeviceMotionEventAcceleration;+ DeviceMotionEventRotationRate;+ DeviceOrientationEvent: Event;Document: Node;DocumentFragment: Node;DocumentTimeline: AnimationTimeline;