refactor(webapi): extract message and storage events with native factories

This commit is contained in:
ldm0
2026-11-17 04:40:15 +08:00
committed by Donough Liu
parent 1cb6b555f4
commit a2368fc2bc
18 changed files with 554 additions and 370 deletions
@@ -19,31 +19,6 @@ struct InitEventArgs {
cancelable: bool,
}
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "StorageEvent.initStorageEvent")]
struct InitStorageEventArgs<'s> {
#[webidl(
required,
converter = "raw",
missing_message = "Failed to execute 'initStorageEvent': 1 argument required."
)]
event_type: webidl::DomString16,
#[webidl(default = false)]
bubbles: bool,
#[webidl(default = false)]
cancelable: bool,
#[webidl(index = 3, nullable, converter = "raw")]
key: Option<webidl::DomString16>,
#[webidl(name = "oldValue", index = 4, nullable, converter = "raw")]
old_value: Option<webidl::DomString16>,
#[webidl(name = "newValue", index = 5, nullable, converter = "raw")]
new_value: Option<webidl::DomString16>,
#[webidl(default = "", index = 6, converter = "usv_string")]
url: String,
#[webidl(index = 7, converter = "raw", nullable)]
storage_area: Option<super::web_storage::StorageReference<'s>>,
}
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "UIEvent.initUIEvent")]
struct InitUiEventArgs<'s> {
@@ -358,32 +333,3 @@ pub(super) fn composition_event_init_callback<'s>(
.initialize(scope, event)
.expect("legacy CompositionEvent init declaration should initialize");
}
pub(super) fn storage_event_init_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
let event = super::events::event_backing(scope, args.this());
let Some(parsed) = webidl::parse_args::<InitStorageEventArgs>(scope, &args) else {
return;
};
if !reinitialize_event_object(
scope,
event,
&parsed.event_type.0,
parsed.bubbles,
parsed.cancelable,
) {
return;
}
super::events::define_storage_event_properties_utf16(
scope,
event,
parsed.key.as_ref().map(|value| value.0.as_slice()),
parsed.old_value.as_ref().map(|value| value.0.as_slice()),
parsed.new_value.as_ref().map(|value| value.0.as_slice()),
&parsed.url,
parsed.storage_area.map(|value| value.0.into()),
);
}
@@ -2,7 +2,7 @@ use super::{
event_document::{document_create_event_callback, document_has_focus_callback},
event_legacy::{
composition_event_init_callback, event_init_event_callback, mouse_event_init_callback,
storage_event_init_callback, text_event_init_callback, ui_event_init_callback,
text_event_init_callback, ui_event_init_callback,
},
events::{
event_bubbles_getter_function, event_cancel_bubble_getter_function,
@@ -17,9 +17,9 @@ use super::{
event_time_stamp_getter_function, event_type_getter_function, event_value_attribute_getter,
focus_event_related_target_getter_function, form_data_event_form_data_getter_function,
input_event_get_target_ranges_callback, keyboard_event_init_callback,
message_event_init_callback, mouse_event_related_target_getter_function,
pointer_event_get_predicted_events_callback, submit_event_submitter_getter_function,
ui_event_pseudo_target_getter_function, ui_event_which_getter_function,
mouse_event_related_target_getter_function, pointer_event_get_predicted_events_callback,
submit_event_submitter_getter_function, ui_event_pseudo_target_getter_function,
ui_event_which_getter_function,
},
selection_surface::document_get_selection_callback,
specs::ConstructorSpec,
@@ -220,17 +220,6 @@ struct InputEventTemplateAccessorsDeclaration {
input_type: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::StorageEvent, enumerable, receiver)]
struct StorageEventTemplateMethodsDeclaration {
#[webapi(
method = "initStorageEvent",
length = 1,
callback = storage_event_init_callback
)]
init_storage_event: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::KeyboardEvent, enumerable, receiver)]
struct KeyboardEventTemplateMethodsDeclaration {
@@ -384,13 +373,6 @@ struct DocumentEventTemplateMethodsDeclaration {
get_selection: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::MessageEvent, enumerable, receiver)]
struct MessageEventTemplateMethodsDeclaration {
#[webapi(method = "initMessageEvent", length = 1, callback = message_event_init_callback)]
init_message_event: (),
}
// Installation and wrapper placement share the same native declarations. Public
// prototype mutations cannot change which fields are exposed as own properties.
fn event_template_declaration(interface: &str) -> Option<EventTemplateDeclaration> {
@@ -398,7 +380,6 @@ fn event_template_declaration(interface: &str) -> Option<EventTemplateDeclaratio
return Some(declaration);
}
Some(match interface {
"MessageEvent" => EventTemplateDeclaration::new::<MessageEventTemplateMethodsDeclaration>(),
"Event" => EventTemplateDeclaration::new::<EventBaseTemplateMethodsDeclaration>(),
"DragEvent" => EventTemplateDeclaration::new::<DragEventTemplateAccessorsDeclaration>(),
"UIEvent" => EventTemplateDeclaration::new::<UiEventTemplateMethodsDeclaration>(),
@@ -408,7 +389,6 @@ fn event_template_declaration(interface: &str) -> Option<EventTemplateDeclaratio
EventTemplateDeclaration::new::<CompositionEventTemplateMethodsDeclaration>()
}
"InputEvent" => EventTemplateDeclaration::new::<InputEventTemplateAccessorsDeclaration>(),
"StorageEvent" => EventTemplateDeclaration::new::<StorageEventTemplateMethodsDeclaration>(),
"KeyboardEvent" => {
EventTemplateDeclaration::new::<KeyboardEventTemplateMethodsDeclaration>()
}
@@ -1,18 +1,20 @@
use super::*;
use crate::util::{get_private_value, v8_string, v8_string_from_utf16_units, v8str};
use crate::webidl::{SnapshotPrototype, WebIdlDictionarySerialize};
pub(crate) use moli_webapi::events::subclasses::construct_original_page_transition_event;
use moli_webapi_declare::WebApiObject;
mod base;
use moli_webapi::events::device;
mod init;
use moli_webapi::events::kind;
mod message;
pub(crate) use message::construct_original_message_event;
pub(crate) use moli_webapi::events::subclasses::message::construct_original_message_event;
pub(crate) use moli_webapi::events::subclasses::storage::construct_original_storage_event_utf16;
mod methods;
mod modifiers;
mod subclasses;
use moli_webapi::events::subclasses::submit;
pub(crate) use moli_webapi::events::subclasses::submit::{
mark_agent_submit_event, take_submit_event_response,
};
pub(crate) use subclasses::clear_input_event_target_ranges;
pub(crate) use subclasses::initialize_native_security_policy_violation_event;
pub(in crate::context_bootstrap) use subclasses::input_event_get_target_ranges_callback;
@@ -32,18 +34,6 @@ pub(in crate::context_bootstrap) use value::{
ValueEventKind, build_value_event_template, install_value_event_template_bindings,
};
pub(crate) use submit::{mark_agent_submit_event, take_submit_event_response};
#[derive(WebApiObject)]
#[webapi(plain)]
struct PageTransitionEventInitDeclaration {
#[webapi(data_property, enumerable)]
bubbles: bool,
#[webapi(data_property, enumerable)]
cancelable: bool,
#[webapi(data_property, enumerable)]
persisted: bool,
}
#[derive(Default, WebApiObject)]
#[webapi(fragment, prototype = "PointerEvent", enumerable)]
struct SecurePointerEventPrototypeRuntimeDeclaration {
@@ -121,82 +111,6 @@ pub(crate) fn construct_original_text_input_event<'s>(
Some(event)
}
pub(crate) fn construct_original_page_transition_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_type: &str,
persisted: bool,
) -> Option<v8::Local<'s, v8::Object>> {
let event_ctor = super::exposed_interfaces::ensure_intrinsic_interface_constructor(
scope,
"PageTransitionEvent",
)
.ok()?;
let event_type = v8_string(scope, event_type)?;
let init = PageTransitionEventInitDeclaration::new(true, true, persisted)
.bind(scope)
.expect("PageTransitionEvent init declaration should bind");
let event = {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let scope = try_catch.init();
event_ctor.new_instance(&scope, &[event_type.into(), init.into()])
}?;
mark_event_trusted(scope, event);
Some(event)
}
pub(crate) fn construct_original_storage_event_utf16<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_type: &str,
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) -> Option<v8::Local<'s, v8::Object>> {
let event_ctor =
super::exposed_interfaces::ensure_intrinsic_interface_constructor(scope, "StorageEvent")
.ok()?;
let event_type = v8_string(scope, event_type)?;
let parsed = subclasses::StorageEventInitMembers::from_native(
key,
old_value,
new_value,
url,
storage_area,
);
let init = parsed.to_js_snapshot(scope, SnapshotPrototype::Null)?;
let event = {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let scope = try_catch.init();
event_ctor.new_instance(&scope, &[event_type.into(), init.into()])
}?;
define_storage_event_properties_utf16(
scope,
event,
key,
old_value,
new_value,
url,
storage_area,
);
Some(event)
}
pub(in crate::context_bootstrap) fn define_storage_event_properties_utf16<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) {
let event = event_backing(scope, event);
subclasses::StorageEventInitMembers::from_native(key, old_value, new_value, url, storage_area)
.initialize_own_snapshot(scope, event)
.expect("StorageEvent native payload");
}
pub(crate) use base::{
EVENT_DISPATCHING_SLOT, EVENT_PASSIVE_SLOT, EVENT_STOP_IMMEDIATE_PROPAGATION_SLOT,
EVENT_STOP_PROPAGATION_SLOT, clear_event_composed_path, define_event_property, event_backing,
@@ -408,7 +322,6 @@ pub(crate) use wrappers::{
set_event_private_value,
};
pub(in crate::context_bootstrap) use message::message_event_init_callback;
pub(in crate::context_bootstrap) use wrappers::{
event_platform_attribute_getter, event_value_attribute_getter,
};
@@ -20,9 +20,7 @@ pub(in crate::context_bootstrap) use pointer::{
pointer_event_get_coalesced_events_callback, pointer_event_get_predicted_events_callback,
};
pub(in crate::context_bootstrap::events) use data::{
StorageEventInitMembers, initialize_navigate_event_methods,
};
pub(in crate::context_bootstrap::events) use data::initialize_navigate_event_methods;
pub(in crate::context_bootstrap) use keyboard::keyboard_event_init_callback;
pub(crate) use moli_webapi::events::subclasses::error::construct_original_error_event;
@@ -1,32 +1,12 @@
use super::super::message;
use super::*;
fn event_subclass_kind_from_callback_data(
data: v8::Local<'_, v8::Value>,
) -> Option<EventSubclassKind> {
let value = i32::try_from(v8::Local::<v8::Integer>::try_from(data).ok()?.value()).ok()?;
EventSubclassKind::from_i32(value)
}
fn required_arguments(kind: EventSubclassKind) -> i32 {
match kind {
EventSubclassKind::NavigateEvent
| EventSubclassKind::NavigationCurrentEntryChangeEvent
| EventSubclassKind::PromiseRejectionEvent
| EventSubclassKind::FormDataEvent => 2,
_ => 1,
}
}
// Every kind has a complete derived dictionary. A new kind must select its
// dictionary explicitly; there is no legacy EventInit-only fallback.
enum SubclassInit<'s> {
Basic(basic::BasicEventInit<'s>),
Pointing(pointer::PointerEventInitPayload<'s>),
Interaction(input::InteractionEventInit<'s>),
Storage(data::StorageEventInitMembers<'s>),
Keyboard(keyboard::KeyboardEventInit<'s>),
Message(message::MessageEventInit<'s>),
CurrentEntry(navigation_init::NavigationCurrentEntryChangeEventInitMembers<'s>),
Navigate(navigation_init::NavigateEventInitMembers<'s>),
}
@@ -55,15 +35,9 @@ impl<'s> SubclassInit<'s> {
| EventSubclassKind::CapturedMouseEvent => {
Self::Interaction(input::InteractionEventInit::parse(scope, args, kind)?)
}
EventSubclassKind::StorageEvent => {
Self::Storage(data::parse_storage_event_init(scope, args)?)
}
EventSubclassKind::KeyboardEvent => {
Self::Keyboard(keyboard::parse_keyboard_event_init(scope, args)?)
}
EventSubclassKind::MessageEvent => {
Self::Message(message::parse_message_event_init(scope, args)?)
}
EventSubclassKind::NavigationCurrentEntryChangeEvent => Self::CurrentEntry(
navigation_init::parse_current_entry_change_event_init(scope, args)?,
),
@@ -79,9 +53,7 @@ impl<'s> SubclassInit<'s> {
Self::Basic(init) => init.event_flags(),
Self::Pointing(init) => init.event_flags(),
Self::Interaction(init) => init.event_flags(),
Self::Storage(init) => init.event_flags(),
Self::Keyboard(init) => init.event_flags(),
Self::Message(init) => init.event_flags(),
Self::CurrentEntry(init) => init.event_flags(),
Self::Navigate(init) => init.event_flags(),
}
@@ -96,9 +68,7 @@ impl<'s> SubclassInit<'s> {
Self::Basic(init) => init.initialize(scope, event),
Self::Pointing(init) => init.initialize(scope, event),
Self::Interaction(init) => return init.initialize(scope, event),
Self::Storage(init) => data::initialize_storage_event(scope, event, init),
Self::Keyboard(init) => keyboard::initialize_keyboard_event(scope, event, init),
Self::Message(init) => message::initialize_message_event(scope, event, init),
Self::CurrentEntry(init) => {
data::initialize_navigation_current_entry_change_event(scope, event, init)
}
@@ -113,7 +83,7 @@ fn event_subclass_constructor_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(kind) = event_subclass_kind_from_callback_data(args.data()) else {
let Some(kind) = EventSubclassKind::from_value(args.data()) else {
throw_type_error(scope, "Invalid event subclass constructor.");
return;
};
@@ -127,7 +97,7 @@ fn event_subclass_constructor_callback<'s>(
);
return;
}
if required_arguments(kind) == 2 && args.length() < 2 {
if kind.required_arguments() == 2 && args.length() < 2 {
throw_type_error(
scope,
&format!(
@@ -167,6 +137,6 @@ pub(in crate::context_bootstrap) fn build_event_subclass_template<'s>(
let data: v8::Local<'s, v8::Value> = v8::Integer::new(scope, kind as i32).into();
v8::FunctionTemplate::builder(event_subclass_constructor_callback)
.data(data)
.length(required_arguments(kind))
.length(kind.required_arguments())
.build(scope)
}
@@ -1,5 +1,4 @@
use super::*;
use crate::context_bootstrap::events::EventInit;
use crate::context_bootstrap::navigation_activation::install_navigation_transition;
use crate::context_bootstrap::navigation_events::navigation_scroll_event_is_active;
use crate::context_bootstrap::navigation_handler_callbacks::{
@@ -10,7 +9,6 @@ use crate::context_bootstrap::navigation_handler_callbacks::{
use crate::context_bootstrap::navigation_window::{
child_browsing_context_handle_for_runtime_owner, runtime_window_is_global, runtime_window_owner,
};
use crate::context_bootstrap::web_storage::StorageReference;
use crate::native_bridge::element::scroll_to_url_fragment_or_top;
use crate::native_bridge::throw_dom_exception;
use crate::util::context_host_ptr_from_global_bridge;
@@ -130,67 +128,6 @@ struct NavigateEventMethodsDeclaration {
scroll: (),
}
#[derive(Default, webidl::WebIdlDictionary)]
#[webidl(prefix = "StorageEventInit", snapshot)]
pub(in crate::context_bootstrap::events) struct StorageEventInitMembers<'s> {
#[webidl(inherit)]
base: EventInit,
#[webidl(nullable, converter = "raw")]
key: Option<webidl::DomString16>,
#[webidl(name = "newValue", nullable, converter = "raw")]
new_value: Option<webidl::DomString16>,
#[webidl(name = "oldValue", nullable, converter = "raw")]
old_value: Option<webidl::DomString16>,
#[webidl(name = "storageArea", converter = "raw", nullable)]
storage_area: Option<StorageReference<'s>>,
#[webidl(default = "", converter = "usv_string")]
url: String,
}
impl<'s> StorageEventInitMembers<'s> {
pub(in crate::context_bootstrap::events) fn from_native(
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) -> Self {
Self {
base: EventInit::default(),
key: key.map(|value| webidl::DomString16(value.to_vec())),
old_value: old_value.map(|value| webidl::DomString16(value.to_vec())),
new_value: new_value.map(|value| webidl::DomString16(value.to_vec())),
url: url.to_owned(),
storage_area: storage_area
.and_then(|value| value.try_into().ok())
.map(StorageReference),
}
}
}
impl StorageEventInitMembers<'_> {
pub(super) fn event_flags(&self) -> (bool, bool, bool) {
(self.base.bubbles, self.base.cancelable, self.base.composed)
}
}
pub(super) fn parse_storage_event_init<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
) -> Option<StorageEventInitMembers<'s>> {
crate::context_bootstrap::events::parse_event_dictionary(scope, args, "StorageEvent")
}
pub(in crate::context_bootstrap::events::subclasses) fn initialize_storage_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
parsed: StorageEventInitMembers<'s>,
) {
parsed
.initialize_snapshot(scope, event)
.expect("StorageEvent state");
}
pub(super) fn initialize_navigation_current_entry_change_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
@@ -1,35 +1,4 @@
use super::*;
use crate::webidl;
pub(crate) struct StorageReference<'scope>(pub(crate) v8::Local<'scope, v8::Object>);
impl webidl::WebIdlSnapshotValue for StorageReference<'_> {
const SNAPSHOT_KIND: webidl::SnapshotKind = webidl::SnapshotKind::Identity;
}
impl<'s> moli_webapi_declare::WebApiValue<'s> for StorageReference<'s> {
fn to_v8_value(&self, _: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
Some(self.0.into())
}
}
impl<'scope> webidl::WebIdlConverter<'scope> for StorageReference<'scope> {
type Options = ();
fn convert(
scope: &mut v8::PinScope<'scope, '_>,
value: v8::Local<'scope, v8::Value>,
context: webidl::Context,
_options: &Self::Options,
) -> Result<Self, webidl::WebIdlError> {
if let Ok(object) = v8::Local::<v8::Object>::try_from(value)
&& crate::web_api_interfaces::Storage::is_instance(scope, object)
{
return Ok(Self(object));
}
Err(webidl::WebIdlError::cannot_convert(context, "Storage"))
}
}
mod accessors;
mod callbacks;
@@ -108,6 +108,15 @@ fn setup_worker_context() -> (v8::OwnedIsolate, v8::Global<v8::Context>) {
let drain_key = v8::String::new(ctx_scope, "__drainWorkerMessages").unwrap();
let _ = global.set(ctx_scope, drain_key.into(), drain_fn.into());
// This harness omits eager Worker globals and their capture phase.
// Install the protected resolver before it executes author script, as
// the complete Worker bootstrap does after creating its eager globals.
crate::context_bootstrap::exposed_interfaces::initialize_realm_interface_registry(
ctx_scope,
crate::context_bootstrap::exposed_interfaces::RealmKind::DedicatedWorker,
)
.expect("standalone Worker tests need protected intrinsic allocation");
v8::Global::new(ctx_scope, context)
};
(isolate, context)
@@ -11,3 +11,100 @@ fn event_constructors_preserve_dom_string_code_units_and_conversion_order() {
.expect("event constructors should preserve DOMString code units and conversion errors");
assert_eq!(result, "true");
}
#[test]
fn native_value_event_factories_keep_renderer_templates_without_author_dictionary_reads() {
let mut vm = new_parsed_test_vm(
"https://native-value-event-factories.test/",
"<!doctype html><main>ready</main>",
);
vm.eval(r#"
globalThis.originalEventFactories = {MessageEvent, StorageEvent, ErrorEvent, PageTransitionEvent};
for (const name of Object.keys(originalEventFactories)) {
delete globalThis[name];
Object.defineProperty(globalThis, name, {configurable: true, get() {throw new Error('public event constructor');}});
}
Object.defineProperty(Object.prototype, 'composed', {configurable: true, get() {throw new Error('native event dictionary read');}});
"#).unwrap();
vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| {
let data = v8::Integer::new(scope, 7).into();
let source = v8::null(scope).into();
let ports = v8::Array::new(scope, 0);
let message = crate::context_bootstrap::construct_original_message_event(
scope,
"message",
data,
"origin",
&[0xd800],
source,
ports,
)
.unwrap();
let storage = crate::context_bootstrap::construct_original_storage_event_utf16(
scope,
"storage",
Some(&[0xd800]),
None,
Some(&[0xdfff]),
"url",
None,
)
.unwrap();
let error_value = v8::Integer::new(scope, 9).into();
let error = crate::context_bootstrap::construct_original_error_event(
scope,
"boom",
"file",
4,
2,
error_value,
)
.unwrap();
let transition = crate::context_bootstrap::construct_original_page_transition_event(
scope, "pageshow", true,
)
.unwrap();
let global = scope.get_current_context().global(scope);
for (name, interface, event) in [
("nativeMessageFactory", "MessageEvent", message),
("nativeStorageFactory", "StorageEvent", storage),
("nativeErrorFactory", "ErrorEvent", error),
("nativePageFactory", "PageTransitionEvent", transition),
] {
assert_eq!(
event.get_constructor_name().to_rust_string_lossy(scope),
interface
);
assert_eq!(
moli_webapi_declare::web_api_object_type(scope, event)
.unwrap()
.name(),
interface
);
let name = crate::util::v8str(scope, name);
assert_eq!(
global.create_data_property(scope, name.into(), event.into()),
Some(true)
);
}
Ok(())
})
.unwrap();
assert_eq!(vm.eval(r#"(() => {
delete Object.prototype.composed;
for (const [event, Ctor] of [
[nativeMessageFactory, originalEventFactories.MessageEvent],
[nativeStorageFactory, originalEventFactories.StorageEvent],
[nativeErrorFactory, originalEventFactories.ErrorEvent],
[nativePageFactory, originalEventFactories.PageTransitionEvent],
]) {
if (!(event instanceof Ctor) || !Number.isFinite(event.timeStamp)) return false;
}
return nativeMessageFactory.data === 7 && nativeMessageFactory.lastEventId === '\ud800'
&& Object.isFrozen(nativeMessageFactory.ports) && nativeMessageFactory.source === null
&& nativeStorageFactory.key === '\ud800' && nativeStorageFactory.newValue === '\udfff'
&& nativeErrorFactory.message === 'boom' && nativeErrorFactory.error === 9 && nativeErrorFactory.cancelable
&& nativePageFactory.persisted && nativePageFactory.bubbles && nativePageFactory.cancelable
&& !nativePageFactory.composed && nativePageFactory.isTrusted;
})()"#).unwrap(), "true");
}
+15
View File
@@ -36,6 +36,21 @@ pub enum EventSubclassKind {
}
impl EventSubclassKind {
pub fn from_value(data: v8::Local<'_, v8::Value>) -> Option<Self> {
let value = i32::try_from(v8::Local::<v8::Integer>::try_from(data).ok()?.value()).ok()?;
Self::from_i32(value)
}
pub fn required_arguments(self) -> i32 {
match self {
Self::NavigateEvent
| Self::NavigationCurrentEntryChangeEvent
| Self::PromiseRejectionEvent
| Self::FormDataEvent => 2,
_ => 1,
}
}
pub fn from_i32(value: i32) -> Option<Self> {
match value {
1 => Some(Self::UiEvent),
+22 -19
View File
@@ -12,8 +12,10 @@ mod clipboard_change;
mod custom;
pub mod error;
pub mod font;
pub mod message;
mod payload;
pub mod security_policy;
pub mod storage;
pub mod submit;
mod templates;
mod values;
@@ -38,23 +40,10 @@ pub const EVENT_SUBCLASS_KIND_SLOT: &str = "__moliEventSubclassKind";
const BEFORE_UNLOAD_EVENT_RETURN_VALUE_SLOT: &str = "__moliBeforeUnloadEventReturnValue";
pub const FONT_FACE_SET_LOAD_EVENT_FONTFACES_SLOT: &str = "__moliFontFaceSetLoadEventFontfaces";
fn kind_from_callback_data(data: v8::Local<'_, v8::Value>) -> Option<EventSubclassKind> {
let value = i32::try_from(v8::Local::<v8::Integer>::try_from(data).ok()?.value()).ok()?;
EventSubclassKind::from_i32(value)
}
fn required_arguments(kind: EventSubclassKind) -> i32 {
match kind {
EventSubclassKind::NavigateEvent
| EventSubclassKind::NavigationCurrentEntryChangeEvent
| EventSubclassKind::PromiseRejectionEvent
| EventSubclassKind::FormDataEvent => 2,
_ => 1,
}
}
enum SubclassInit<'s> {
Custom(custom::CustomEventInit<'s>),
Message(message::MessageEventInit<'s>),
Storage(storage::StorageEventInitMembers<'s>),
Values(values::ValueEventInit<'s>),
Payload(payload::PayloadEventInit<'s>),
ClipboardChange(clipboard_change::ClipboardChangeEventInitMembers<'s>),
@@ -69,6 +58,12 @@ impl<'s> SubclassInit<'s> {
kind: EventSubclassKind,
) -> Option<Self> {
Some(match kind {
EventSubclassKind::MessageEvent => {
Self::Message(message::parse_message_event_init(scope, args)?)
}
EventSubclassKind::StorageEvent => {
Self::Storage(storage::parse_storage_event_init(scope, args)?)
}
EventSubclassKind::CustomEvent => {
Self::Custom(parse_event_dictionary(scope, args, "CustomEvent")?)
}
@@ -106,6 +101,8 @@ impl<'s> SubclassInit<'s> {
fn event_flags(&self) -> (bool, bool, bool) {
match self {
Self::Custom(init) => init.event_flags(),
Self::Message(init) => init.event_flags(),
Self::Storage(init) => init.event_flags(),
Self::Values(init) => init.event_flags(),
Self::Payload(init) => init.event_flags(),
Self::ClipboardChange(init) => init.event_flags(),
@@ -121,6 +118,8 @@ impl<'s> SubclassInit<'s> {
) -> bool {
match self {
Self::Custom(init) => init.initialize(scope, event),
Self::Message(init) => message::initialize_message_event(scope, event, init),
Self::Storage(init) => storage::initialize_storage_event(scope, event, init),
Self::Values(init) => init.initialize(scope, event),
Self::Payload(init) => init.initialize(scope, event),
Self::ClipboardChange(init) => {
@@ -173,7 +172,7 @@ fn constructor_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(kind) = kind_from_callback_data(args.data()) else {
let Some(kind) = EventSubclassKind::from_value(args.data()) else {
throw_type_error(scope, "Invalid event subclass constructor.");
return;
};
@@ -187,7 +186,7 @@ fn constructor_callback<'s>(
);
return;
}
if required_arguments(kind) == 2 && args.length() < 2 {
if kind.required_arguments() == 2 && args.length() < 2 {
throw_type_error(
scope,
&format!(
@@ -224,7 +223,7 @@ fn template<'s>(
let data: v8::Local<'s, v8::Value> = v8::Integer::new(scope, kind as i32).into();
v8::FunctionTemplate::builder(constructor_callback)
.data(data)
.length(required_arguments(kind))
.length(kind.required_arguments())
.build(scope)
}
@@ -233,7 +232,9 @@ pub fn build_template<'s>(
kind: EventSubclassKind,
) -> Option<v8::Local<'s, v8::FunctionTemplate>> {
match kind {
EventSubclassKind::CustomEvent
EventSubclassKind::MessageEvent
| EventSubclassKind::StorageEvent
| EventSubclassKind::CustomEvent
| EventSubclassKind::ClipboardEvent
| EventSubclassKind::CloseEvent
| EventSubclassKind::CommandEvent
@@ -253,3 +254,5 @@ pub fn build_template<'s>(
_ => None,
}
}
pub use values::construct_original_page_transition_event;
@@ -5,9 +5,7 @@ pub fn event_subclass_kind<'s>(
event: v8::Local<'s, v8::Object>,
) -> Option<EventSubclassKind> {
event_private_value(scope, event, EVENT_SUBCLASS_KIND_SLOT)
.and_then(|value| v8::Local::<v8::Integer>::try_from(value).ok())
.and_then(|value| i32::try_from(value.value()).ok())
.and_then(EventSubclassKind::from_i32)
.and_then(EventSubclassKind::from_value)
}
pub fn new_uninitialized_before_unload_event<'s>(
+15 -15
View File
@@ -1,5 +1,4 @@
use super::super::init::EventInit;
use super::*;
use moli_v8_util::v8_string;
use moli_webidl as webidl;
use webidl::WebIdlDictionarySerialize;
@@ -46,9 +45,7 @@ impl<'s> ErrorEventInit<'s> {
}
}
/// Runtime reports carry already converted payloads. Use the protected
/// constructor with no dictionary so author getters and replacements never
/// participate in native error reporting.
/// Reports carry converted values, without invoking author constructors or getters.
pub fn construct_original_error_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
message: &str,
@@ -57,15 +54,8 @@ pub fn construct_original_error_event<'s>(
colno: u32,
error: v8::Local<'s, v8::Value>,
) -> Option<v8::Local<'s, v8::Object>> {
let constructor = v8::Local::<v8::Function>::try_from(moli_v8_util::global_constructor_object(
scope,
"ErrorEvent",
)?)
.ok()?;
let event_type = v8_string(scope, "error")?;
let event = constructor.new_instance(scope, &[event_type.into()])?;
let state = event_backing(scope, event);
ErrorEventInit {
let init = ErrorEventInit {
base: EventInit {
cancelable: true,
..EventInit::default()
@@ -75,7 +65,17 @@ pub fn construct_original_error_event<'s>(
lineno,
colno,
error: Some(error),
}
.initialize_snapshot(scope, state)?;
Some(event)
};
let wrapper = moli_v8_util::new_intrinsic_interface_instance(scope, "ErrorEvent")?;
super::construct_subclass(
scope,
wrapper,
super::EventSubclassKind::ErrorEvent,
event_type,
init.event_flags(),
|scope, event| {
init.initialize(scope, event);
true
},
)
}
@@ -1,7 +1,8 @@
use super::super::init::EventInit;
use super::{event_backing, reinitialize_event_object};
use crate::context_bootstrap::events::EventInit;
use crate::util::v8_string;
use crate::{web_api_interfaces, webidl};
use crate::interfaces as web_api_interfaces;
use moli_v8_util::v8_string;
use moli_webidl as webidl;
use webidl::WebIdlDictionarySerialize;
// Interface metadata for the Window | MessagePort | ServiceWorker union.
@@ -34,7 +35,7 @@ pub(super) struct MessageEventInit<'s> {
last_event_id: webidl::DomString16,
#[webidl(default = "", converter = "usv_string")]
origin: String,
#[webidl(sequence, interface = crate::web_api_interfaces::MessagePort, default = Vec::new(), snapshot_frozen)]
#[webidl(sequence, interface = crate::interfaces::MessagePort, default = Vec::new(), snapshot_frozen)]
ports: Vec<v8::Local<'s, v8::Object>>,
#[webidl(nullable, interface = MessageEventSource)]
source: Option<v8::Local<'s, v8::Object>>,
@@ -50,7 +51,7 @@ pub(super) fn parse_message_event_init<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
) -> Option<MessageEventInit<'s>> {
crate::context_bootstrap::events::parse_event_dictionary(scope, args, "MessageEvent")
super::super::init::parse_event_dictionary(scope, args, "MessageEvent")
}
#[derive(webidl::WebIdlArgs)]
@@ -74,7 +75,7 @@ struct InitMessageEventArgs<'s> {
last_event_id: webidl::DomString16,
#[webidl(nullable, interface = MessageEventSource)]
source: Option<v8::Local<'s, v8::Object>>,
#[webidl(sequence, interface = crate::web_api_interfaces::MessagePort, default = Vec::new())]
#[webidl(sequence, interface = crate::interfaces::MessagePort, default = Vec::new())]
ports: Vec<v8::Local<'s, v8::Object>>,
}
@@ -96,9 +97,8 @@ pub(super) fn initialize_message_event<'s>(
.expect("MessageEvent state should initialize");
}
/// Native producers supply already deserialized values. Their dense ports
/// arrays must not run author-defined iterators or dictionary getters.
pub(crate) fn construct_original_message_event<'s>(
/// Native producers supply already deserialized values and dense port arrays.
pub fn construct_original_message_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_type: &str,
data: v8::Local<'s, v8::Value>,
@@ -107,36 +107,37 @@ pub(crate) fn construct_original_message_event<'s>(
source: v8::Local<'s, v8::Value>,
ports: v8::Local<'s, v8::Array>,
) -> Option<v8::Local<'s, v8::Object>> {
let constructor = super::super::exposed_interfaces::ensure_intrinsic_interface_constructor(
scope,
"MessageEvent",
)
.ok()?;
let event_type = v8_string(scope, event_type)?;
let event = constructor.new_instance(scope, &[event_type.into()])?;
let ports = (0..ports.length())
.map(|index| ports.get_index(scope, index)?.try_into().ok())
.collect::<Option<Vec<_>>>()?;
initialize_message_event(
scope,
event,
MessageEventInit {
base: EventInit::default(),
data: Some(data),
origin: origin.to_owned(),
last_event_id: webidl::DomString16(last_event_id.to_vec()),
source: if source.is_null_or_undefined() {
None
} else {
Some(source.try_into().ok()?)
},
ports,
let init = MessageEventInit {
base: EventInit::default(),
data: Some(data),
origin: origin.to_owned(),
last_event_id: webidl::DomString16(last_event_id.to_vec()),
source: if source.is_null_or_undefined() {
None
} else {
Some(source.try_into().ok()?)
},
);
Some(event)
ports,
};
let wrapper = moli_v8_util::new_intrinsic_interface_instance(scope, "MessageEvent")?;
super::construct_subclass(
scope,
wrapper,
super::EventSubclassKind::MessageEvent,
event_type,
init.event_flags(),
|scope, event| {
initialize_message_event(scope, event, init);
true
},
)
}
pub(in crate::context_bootstrap) fn message_event_init_callback<'s>(
pub fn message_event_init_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
@@ -0,0 +1,189 @@
use super::*;
use moli_v8_util::v8_string;
use moli_webidl as webidl;
use webidl::WebIdlDictionarySerialize;
struct StorageReference<'scope>(v8::Local<'scope, v8::Object>);
impl webidl::WebIdlSnapshotValue for StorageReference<'_> {
const SNAPSHOT_KIND: webidl::SnapshotKind = webidl::SnapshotKind::Identity;
}
impl<'s> moli_webapi_declare::WebApiValue<'s> for StorageReference<'s> {
fn to_v8_value(&self, _: &mut v8::PinScope<'s, '_>) -> Option<v8::Local<'s, v8::Value>> {
Some(self.0.into())
}
}
impl<'scope> webidl::WebIdlConverter<'scope> for StorageReference<'scope> {
type Options = ();
fn convert(
scope: &mut v8::PinScope<'scope, '_>,
value: v8::Local<'scope, v8::Value>,
context: webidl::Context,
_options: &Self::Options,
) -> Result<Self, webidl::WebIdlError> {
if let Ok(object) = v8::Local::<v8::Object>::try_from(value)
&& crate::interfaces::Storage::is_instance(scope, object)
{
return Ok(Self(object));
}
Err(webidl::WebIdlError::cannot_convert(context, "Storage"))
}
}
#[derive(Default, webidl::WebIdlDictionary)]
#[webidl(prefix = "StorageEventInit", snapshot)]
pub(super) struct StorageEventInitMembers<'s> {
#[webidl(inherit)]
base: EventInit,
#[webidl(nullable, converter = "raw")]
key: Option<webidl::DomString16>,
#[webidl(name = "newValue", nullable, converter = "raw")]
new_value: Option<webidl::DomString16>,
#[webidl(name = "oldValue", nullable, converter = "raw")]
old_value: Option<webidl::DomString16>,
#[webidl(name = "storageArea", converter = "raw", nullable)]
storage_area: Option<StorageReference<'s>>,
#[webidl(default = "", converter = "usv_string")]
url: String,
}
impl<'s> StorageEventInitMembers<'s> {
fn from_native(
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) -> Self {
Self {
base: EventInit::default(),
key: key.map(|value| webidl::DomString16(value.to_vec())),
old_value: old_value.map(|value| webidl::DomString16(value.to_vec())),
new_value: new_value.map(|value| webidl::DomString16(value.to_vec())),
url: url.to_owned(),
storage_area: storage_area
.and_then(|value| value.try_into().ok())
.map(StorageReference),
}
}
}
impl StorageEventInitMembers<'_> {
pub(super) fn event_flags(&self) -> (bool, bool, bool) {
(self.base.bubbles, self.base.cancelable, self.base.composed)
}
}
pub(super) fn parse_storage_event_init<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
) -> Option<StorageEventInitMembers<'s>> {
super::super::init::parse_event_dictionary(scope, args, "StorageEvent")
}
pub(super) fn initialize_storage_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
parsed: StorageEventInitMembers<'s>,
) {
parsed
.initialize_snapshot(scope, event)
.expect("StorageEvent state");
}
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "StorageEvent.initStorageEvent")]
struct InitStorageEventArgs<'s> {
#[webidl(
required,
converter = "raw",
missing_message = "Failed to execute 'initStorageEvent': 1 argument required."
)]
event_type: webidl::DomString16,
#[webidl(default = false)]
bubbles: bool,
#[webidl(default = false)]
cancelable: bool,
#[webidl(index = 3, nullable, converter = "raw")]
key: Option<webidl::DomString16>,
#[webidl(name = "oldValue", index = 4, nullable, converter = "raw")]
old_value: Option<webidl::DomString16>,
#[webidl(name = "newValue", index = 5, nullable, converter = "raw")]
new_value: Option<webidl::DomString16>,
#[webidl(default = "", index = 6, converter = "usv_string")]
url: String,
#[webidl(index = 7, converter = "raw", nullable)]
storage_area: Option<StorageReference<'s>>,
}
pub(super) fn storage_event_init_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
let event = event_backing(scope, args.this());
let Some(parsed) = webidl::parse_args::<InitStorageEventArgs>(scope, &args) else {
return;
};
if !reinitialize_event_object(
scope,
event,
&parsed.event_type.0,
parsed.bubbles,
parsed.cancelable,
) {
return;
}
define_storage_event_properties_utf16(
scope,
event,
parsed.key.as_ref().map(|value| value.0.as_slice()),
parsed.old_value.as_ref().map(|value| value.0.as_slice()),
parsed.new_value.as_ref().map(|value| value.0.as_slice()),
&parsed.url,
parsed.storage_area.map(|value| value.0.into()),
);
}
pub fn construct_original_storage_event_utf16<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_type: &str,
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) -> Option<v8::Local<'s, v8::Object>> {
let event_type = v8_string(scope, event_type)?;
let init = StorageEventInitMembers::from_native(key, old_value, new_value, url, storage_area);
let wrapper = moli_v8_util::new_intrinsic_interface_instance(scope, "StorageEvent")?;
super::construct_subclass(
scope,
wrapper,
super::EventSubclassKind::StorageEvent,
event_type,
init.event_flags(),
|scope, event| {
initialize_storage_event(scope, event, init);
true
},
)
}
fn define_storage_event_properties_utf16<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
key: Option<&[u16]>,
old_value: Option<&[u16]>,
new_value: Option<&[u16]>,
url: &str,
storage_area: Option<v8::Local<'s, v8::Value>>,
) {
let event = event_backing(scope, event);
StorageEventInitMembers::from_native(key, old_value, new_value, url, storage_area)
.initialize_own_snapshot(scope, event)
.expect("StorageEvent native payload");
}
@@ -1,4 +1,5 @@
use super::*;
use super::{message::message_event_init_callback, storage::storage_event_init_callback};
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiFunctionTemplateDeclaration};
pub struct EventTemplateDeclaration {
@@ -151,6 +152,8 @@ struct ClipboardChangeEventTemplateAccessorsDeclaration {
pub fn template_declaration(interface: &str) -> Option<EventTemplateDeclaration> {
Some(match interface {
"MessageEvent" => EventTemplateDeclaration::new::<MessageEventTemplateMethodsDeclaration>(),
"StorageEvent" => EventTemplateDeclaration::new::<StorageEventTemplateMethodsDeclaration>(),
"ClipboardEvent" => {
EventTemplateDeclaration::new::<ClipboardEventTemplateAccessorsDeclaration>()
}
@@ -173,3 +176,21 @@ pub fn template_declaration(interface: &str) -> Option<EventTemplateDeclaration>
_ => return None,
})
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::MessageEvent, enumerable, receiver)]
struct MessageEventTemplateMethodsDeclaration {
#[webapi(method = "initMessageEvent", length = 1, callback = message_event_init_callback)]
init_message_event: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::StorageEvent, enumerable, receiver)]
struct StorageEventTemplateMethodsDeclaration {
#[webapi(
method = "initStorageEvent",
length = 1,
callback = storage_event_init_callback
)]
init_storage_event: (),
}
@@ -171,3 +171,33 @@ impl<'s> ValueEventInit<'s> {
.expect("value event dictionary state");
}
}
pub fn construct_original_page_transition_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
event_type: &str,
persisted: bool,
) -> Option<v8::Local<'s, v8::Object>> {
let event_type = moli_v8_util::v8_string(scope, event_type)?;
let init = ValueEventInit::PageTransition(PageTransitionInit {
base: EventInit {
bubbles: true,
cancelable: true,
..EventInit::default()
},
persisted,
});
let wrapper = moli_v8_util::new_intrinsic_interface_instance(scope, "PageTransitionEvent")?;
let event = super::construct_subclass(
scope,
wrapper,
EventSubclassKind::PageTransitionEvent,
event_type,
init.event_flags(),
|scope, event| {
init.initialize(scope, event);
true
},
)?;
super::mark_event_trusted(scope, event);
Some(event)
}
+108
View File
@@ -120,6 +120,8 @@ fn install(scope: &mut v8::PinScope<'_, '_>, now: f64) {
for kind in [
EventSubclassKind::CustomEvent,
EventSubclassKind::MessageEvent,
EventSubclassKind::StorageEvent,
EventSubclassKind::CloseEvent,
EventSubclassKind::ClipboardEvent,
EventSubclassKind::CommandEvent,
@@ -319,6 +321,8 @@ fn install(scope: &mut v8::PinScope<'_, '_>, now: f64) {
(interfaces::RTCDataChannel::DESCRIPTOR, "channel"),
(interfaces::AudioBuffer::DESCRIPTOR, "buffer"),
(interfaces::DataTransfer::DESCRIPTOR, "clipboard"),
(interfaces::MessagePort::DESCRIPTOR, "endpoint"),
(interfaces::Storage::DESCRIPTOR, "storage"),
(interfaces::FormData::DESCRIPTOR, "form"),
(interfaces::TextTrack::DESCRIPTOR, "track"),
(interfaces::FontFace::DESCRIPTOR, "font"),
@@ -870,3 +874,107 @@ fn native_error_and_before_unload_factories_ignore_replaced_public_constructors(
})()"#).is_true());
assert_eq!(state::event_initialized(scope, event), Some(false));
}
#[test]
fn message_and_storage_events_preserve_native_references_and_conversion_order() {
check(
r#"(() => {
const payload = {}, order = [];
const message = new MessageEvent('message', new Proxy({
data: payload, origin: '\ud800', lastEventId: '\ud800', ports: [endpoint], source: endpoint,
}, {get(target, name) {order.push(name); return target[name];}}));
assert(order.join(',') === 'bubbles,cancelable,composed,data,lastEventId,origin,ports,source', order);
assert(message.data === payload && message.source === endpoint && message.ports[0] === endpoint);
assert(message.origin === '\ufffd' && message.lastEventId === '\ud800' && Object.isFrozen(message.ports));
const storageOrder = [];
const storageEvent = new StorageEvent('storage', new Proxy({
key: '\ud800', newValue: '\udfff', oldValue: null, storageArea: storage, url: '\ud800',
}, {get(target, name) {storageOrder.push(name); return target[name];}}));
assert(storageOrder.join(',') === 'bubbles,cancelable,composed,key,newValue,oldValue,storageArea,url', storageOrder);
assert(storageEvent.storageArea === storage && storageEvent.key === '\ud800');
assert(storageEvent.newValue === '\udfff' && storageEvent.oldValue === null && storageEvent.url === '\ufffd');
for (const [Ctor, init] of [
[MessageEvent, {source: {}}], [MessageEvent, {ports: [{}]}],
[StorageEvent, {storageArea: {}}],
]) {
let caught; try {new Ctor('invalid', init);} catch (error) {caught = error;}
assert(caught instanceof TypeError, Ctor.name);
}
return true;
})()"#,
);
}
#[test]
fn message_and_storage_legacy_initializers_keep_converted_payloads() {
check(
r#"(() => {
const payload = {}, message = new MessageEvent('before', {composed: true});
message.initMessageEvent('after\ud800', true, true, payload, '\ud800', '\udfff', endpoint, [endpoint]);
assert(message.type === 'after\ud800' && message.bubbles && message.cancelable && message.composed);
assert(message.data === payload && message.origin === '\ufffd' && message.lastEventId === '\udfff');
assert(message.source === endpoint && message.ports[0] === endpoint && Object.isFrozen(message.ports));
const e = new StorageEvent('before', {composed: true});
e.initStorageEvent('after', true, false, '\ud800', null, '\udfff', '\ud800', storage);
assert(e.type === 'after' && e.bubbles && !e.cancelable && e.composed);
assert(e.key === '\ud800' && e.oldValue === null && e.newValue === '\udfff' && e.url === '\ufffd');
assert(e.storageArea === storage);
return true;
})()"#,
);
}
#[test]
fn native_message_and_storage_factories_do_not_read_author_constructors_or_iterators() {
ensure_v8();
let mut isolate = v8::Isolate::new(Default::default());
let scope = pin!(v8::HandleScope::new(&mut isolate));
let scope = &mut scope.init();
let context = v8::Context::new(scope, Default::default());
let scope = &mut v8::ContextScope::new(scope, context);
install(scope, 37.25);
let endpoint = eval(scope, "endpoint");
let storage = eval(scope, "storage");
let ports = v8::Array::new_with_elements(scope, &[endpoint]);
let data = v8::Integer::new(scope, 7).into();
eval(
scope,
r#"
globalThis.OriginalMessage = MessageEvent; globalThis.OriginalStorage = StorageEvent;
for (const name of ['MessageEvent', 'StorageEvent']) {
Object.defineProperty(globalThis, name, {configurable: true, get() {throw new Error('public constructor');}});
}
Object.defineProperty(Array.prototype, Symbol.iterator, {configurable: true, get() {throw new Error('author iterator');}});
"#,
);
let message = subclasses::message::construct_original_message_event(
scope,
"message",
data,
"origin",
&[0xd800],
endpoint,
ports,
)
.unwrap();
publish(scope, "nativeMessage", message);
let storage = subclasses::storage::construct_original_storage_event_utf16(
scope,
"storage",
Some(&[0xd800]),
None,
Some(&[0xdfff]),
"url",
Some(storage),
)
.unwrap();
publish(scope, "nativeStorage", storage);
assert!(eval(scope, r#"(() => {
assert(nativeMessage instanceof OriginalMessage && nativeMessage.data === 7);
assert(nativeMessage.source === endpoint && nativeMessage.ports[0] === endpoint && Object.isFrozen(nativeMessage.ports));
assert(nativeMessage.lastEventId === '\ud800');
assert(nativeStorage instanceof OriginalStorage && nativeStorage.storageArea === storage);
assert(nativeStorage.key === '\ud800' && nativeStorage.newValue === '\udfff');
return true;
})()"#).is_true());
}