Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(dom): derive ShadowRootInit before attaching shadow roots

ldm01db687145c1c
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/shadow_dom.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/shadow_dom.rs
index b8ea24979..6c3f0e2a1 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/shadow_dom.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/shadow_dom.rs
@@ -166,7 +166,8 @@ pub(in crate::native_bridge) fn detached_attach_shadow_method_callback<'s>(
throw_type_error(scope, "Element.attachShadow receiver must be an element.");
return;
}
- let Some((init, shadow_init)) = shadow_root_init_from_attach_shadow_value(scope, args.get(0))
+ let Some((registry_association, shadow_init)) =
+ shadow_root_init_from_attach_shadow_value(scope, args.get(0))
else {
return;
};
@@ -183,9 +184,6 @@ pub(in crate::native_bridge) fn detached_attach_shadow_method_callback<'s>(
);
return;
}
- let registry_association = init
- .get(scope, v8str(scope, "customElementRegistry").into())
- .and_then(|value| custom_elements::registry_association_from_value(scope, value));
if let Some(runtime_ptr) = context_host_ptr_from_global_bridge(scope)
&& let Some(owner_document) = detached_owner_document_object(scope, host)
&& let Some(document_handle) = detached_native_handle(scope, owner_document)
diff --git a/moli-renderer-v8/src/native_bridge/element/shadow_dom/attach.rs b/moli-renderer-v8/src/native_bridge/element/shadow_dom/attach.rs
index 71beb4f54..56bcc4565 100644
--- a/moli-renderer-v8/src/native_bridge/element/shadow_dom/attach.rs
+++ b/moli-renderer-v8/src/native_bridge/element/shadow_dom/attach.rs
@@ -1,84 +1,96 @@
use crate::custom_elements;
use crate::dom::native::ShadowRootInit;
-use crate::util::{throw_type_error, v8str};
+use crate::webidl;
use super::super::super::{
document::{self, validate_registry_association_for_document},
node::node_runtime_and_handle_from_args,
set_wrapped_handle_or_null_for_receiver, throw_dom_exception,
};
-use super::super::property_string_value;
-fn dictionary_boolean(
- scope: &mut v8::PinScope<'_, '_>,
- init: v8::Local<'_, v8::Object>,
- name: &'static str,
-) -> bool {
- init.get(scope, crate::util::v8str(scope, name).into())
- .is_some_and(|value| value.boolean_value(scope))
+#[derive(webidl::WebIdlEnum)]
+enum ShadowRootMode {
+ #[webidl(token = "open")]
+ Open,
+ #[webidl(token = "closed")]
+ Closed,
}
-fn dictionary_string(
- scope: &mut v8::PinScope<'_, '_>,
- init: v8::Local<'_, v8::Object>,
- name: &'static str,
-) -> Option<Option<String>> {
- let value = init.get(scope, crate::util::v8str(scope, name).into())?;
- if value.is_undefined() {
- return Some(None);
- }
- property_string_value(scope, value).map(Some)
+#[derive(webidl::WebIdlEnum)]
+enum SlotAssignmentMode {
+ #[webidl(token = "named")]
+ Named,
+ #[webidl(token = "manual")]
+ Manual,
}
-fn dictionary_nullable_string(
- scope: &mut v8::PinScope<'_, '_>,
- init: v8::Local<'_, v8::Object>,
- name: &'static str,
-) -> Option<Option<String>> {
- let value = init.get(scope, crate::util::v8str(scope, name).into())?;
- if value.is_null_or_undefined() {
- return Some(None);
- }
- property_string_value(scope, value).map(Some)
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "ShadowRootInit")]
+struct ShadowRootInitMembers {
+ #[webidl(default = false)]
+ clonable: bool,
+ #[webidl(with = custom_element_registry_member)]
+ custom_element_registry: Option<custom_elements::CustomElementRegistryAssociation>,
+ #[webidl(default = false)]
+ delegates_focus: bool,
+ #[webidl(required, converter = "enum")]
+ mode: ShadowRootMode,
+ #[webidl(nullable)]
+ reference_target: Option<String>,
+ #[webidl(default = false)]
+ serializable: bool,
+ #[webidl(default = SlotAssignmentMode::Named, converter = "enum")]
+ slot_assignment: SlotAssignmentMode,
+}
+
+fn custom_element_registry_member<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ init: v8::Local<'s, v8::Object>,
+ _: &str,
+) -> Result<Option<custom_elements::CustomElementRegistryAssociation>, webidl::WebIdlError> {
+ let context = webidl::Context::member("ShadowRootInit", "customElementRegistry");
+ let Some(value) = webidl::property_result(scope, init, "customElementRegistry", context)?
+ .filter(|value| !value.is_undefined())
+ else {
+ return Ok(None);
+ };
+ custom_elements::registry_association_from_value(scope, value)
+ .map(Some)
+ .ok_or_else(|| webidl::WebIdlError::cannot_convert(context, "CustomElementRegistry"))
}
pub(in crate::native_bridge) fn shadow_root_init_from_attach_shadow_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
-) -> Option<(v8::Local<'s, v8::Object>, ShadowRootInit)> {
- let Some(init) = value.to_object(scope) else {
- throw_type_error(scope, "Element.attachShadow requires an init dictionary.");
- return None;
- };
- let Some(Some(mode)) = dictionary_string(scope, init, "mode") else {
- throw_type_error(scope, "Element.attachShadow init.mode is required.");
- return None;
- };
- if mode != "open" && mode != "closed" {
- throw_type_error(
- scope,
- "Element.attachShadow init.mode must be 'open' or 'closed'.",
- );
- return None;
- }
- let mut shadow_init = ShadowRootInit::new(&mode);
- shadow_init.set_delegates_focus(dictionary_boolean(scope, init, "delegatesFocus"));
- shadow_init.set_clonable(dictionary_boolean(scope, init, "clonable"));
- shadow_init.set_serializable(dictionary_boolean(scope, init, "serializable"));
- if let Some(Some(slot_assignment)) = dictionary_string(scope, init, "slotAssignment") {
- if slot_assignment != "named" && slot_assignment != "manual" {
- throw_type_error(
- scope,
- "Element.attachShadow init.slotAssignment must be 'named' or 'manual'.",
- );
+) -> Option<(
+ Option<custom_elements::CustomElementRegistryAssociation>,
+ ShadowRootInit,
+)> {
+ let init = match webidl::convert::<webidl::Dictionary<ShadowRootInitMembers>>(
+ scope,
+ value,
+ webidl::Context::argument("Element.attachShadow", 1),
+ ) {
+ Ok(init) => init.0,
+ Err(error) => {
+ webidl::throw_error(scope, &error);
return None;
}
- shadow_init.set_slot_assignment(&slot_assignment);
- }
- if let Some(reference_target) = dictionary_nullable_string(scope, init, "referenceTarget") {
- shadow_init.set_reference_target(reference_target);
- }
- Some((init, shadow_init))
+ };
+ let mode = match init.mode {
+ ShadowRootMode::Open => "open",
+ ShadowRootMode::Closed => "closed",
+ };
+ let mut shadow_init = ShadowRootInit::new(mode);
+ shadow_init.set_clonable(init.clonable);
+ shadow_init.set_delegates_focus(init.delegates_focus);
+ shadow_init.set_serializable(init.serializable);
+ shadow_init.set_slot_assignment(match init.slot_assignment {
+ SlotAssignmentMode::Named => "named",
+ SlotAssignmentMode::Manual => "manual",
+ });
+ shadow_init.set_reference_target(init.reference_target);
+ Some((init.custom_element_registry, shadow_init))
}
pub(in crate::native_bridge) fn element_attach_shadow_callback<'s>(
@@ -94,15 +106,13 @@ pub(in crate::native_bridge) fn element_attach_shadow_callback<'s>(
document::detached_attach_shadow_method_callback(scope, args, rv);
return;
}
- let Some((init, shadow_init)) = shadow_root_init_from_attach_shadow_value(scope, args.get(0))
+ let Some((registry_association, shadow_init)) =
+ shadow_root_init_from_attach_shadow_value(scope, args.get(0))
else {
return;
};
let available_to_element_internals =
custom_elements::preserves_custom_element_identity(runtime_ptr, handle);
- let registry_association = init
- .get(scope, v8str(scope, "customElementRegistry").into())
- .and_then(|value| custom_elements::registry_association_from_value(scope, value));
let runtime = unsafe { &mut *runtime_ptr };
let Some(document_handle) = runtime.dom_host().owner_document_handle(handle) else {
rv.set_null();
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index 679f7204c..b84cdf5dc 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -53,6 +53,7 @@ mod security_policy;
mod security_policy_event_init;
mod service_worker_drain;
mod session_description;
+mod shadow_root_init;
mod simple_event_target_handlers;
mod simple_handler_object;
mod speech_synthesis;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/shadow_root_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/shadow_root_init.rs
new file mode 100644
index 000000000..c28be6c43
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/shadow_root_init.rs
@@ -0,0 +1,49 @@
+use super::*;
+
+#[test]
+fn shadow_root_init_converts_once_before_attaching_live_or_detached_roots() {
+ let mut vm = new_storage_html_test_vm("https://shadow-root-init.test/");
+ assert_eq!(vm.eval(r#"(() => {
+ const members = ['clonable', 'customElementRegistry', 'delegatesFocus', 'mode',
+ 'referenceTarget', 'serializable', 'slotAssignment'];
+ const sentinel = {sentinel: true};
+ for (const owner of [document, document.implementation.createHTMLDocument('detached')]) {
+ for (const member of members) {
+ const host = owner.createElement('div');
+ owner.body.appendChild(host);
+ const reads = [];
+ const init = new Proxy({mode: 'open'}, {get(target, key) {
+ reads.push(key);
+ if (key === member) throw sentinel;
+ return target[key];
+ }});
+ let caught;
+ try {host.attachShadow(init);} catch (error) {caught = error;}
+ if (caught !== sentinel || host.shadowRoot !== null ||
+ reads.join(',') !== members.slice(0, members.indexOf(member) + 1).join(','))
+ throw Error('failed conversion mutated a host or read later members: ' + member);
+ if (!host.attachShadow({mode:'open'})) throw Error('host was not reusable');
+ }
+ const host = owner.createElement('div');
+ const reads = [];
+ const root = host.attachShadow(new Proxy({mode:'closed', clonable:true,
+ serializable:true, delegatesFocus:true, slotAssignment:'manual',
+ referenceTarget:'target', customElementRegistry:null}, {get(target,key) {
+ reads.push(key); return target[key];
+ }}));
+ if (reads.join(',') !== members.join(',') || root.mode !== 'closed' ||
+ !root.clonable || !root.serializable || !root.delegatesFocus ||
+ root.slotAssignment !== 'manual' || root.referenceTarget !== 'target')
+ throw Error('converted state');
+ for (const init of [undefined, null, 1, true, 'open', {}, {mode:'invalid'},
+ {mode:'open',slotAssignment:'invalid'}, {mode:'open',customElementRegistry:{}}]) {
+ const invalidHost = owner.createElement('div');
+ let error;
+ try {invalidHost.attachShadow(init);} catch (caught) {error=caught;}
+ if (!(error instanceof TypeError) || invalidHost.shadowRoot !== null)
+ throw Error('invalid dictionary accepted');
+ }
+ }
+ return true;
+ })()"#).unwrap(), "true");
+}