Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(renderer): use native prototypes for browser-created objects

lanyue-llk55deac605025
diff --git a/moli-renderer-v8/src/context_bootstrap/media_cues.rs b/moli-renderer-v8/src/context_bootstrap/media_cues.rs
index cbe798a94..6869deeb6 100644
--- a/moli-renderer-v8/src/context_bootstrap/media_cues.rs
+++ b/moli-renderer-v8/src/context_bootstrap/media_cues.rs
@@ -252,12 +252,9 @@ pub(crate) fn new_media_error_value<'s>(
code: u32,
message: &str,
) -> Option<v8::Local<'s, v8::Object>> {
- let global = scope.get_current_context().global(scope);
- let constructor = global.get(scope, v8str(scope, "MediaError").into())?;
- let constructor = v8::Local::<v8::Object>::try_from(constructor).ok()?;
- let prototype = constructor.get(scope, v8str(scope, "prototype").into())?;
+ let prototype = super::ensure_intrinsic_interface_prototype(scope, "MediaError").ok()?;
let object = v8::Object::new(scope);
- if object.set_prototype(scope, prototype) != Some(true) {
+ if object.set_prototype(scope, prototype.into()) != Some(true) {
return None;
}
set_private_value(
diff --git a/moli-renderer-v8/src/custom_elements/definition_callbacks.rs b/moli-renderer-v8/src/custom_elements/definition_callbacks.rs
index ebe456ad3..ac0373ee2 100644
--- a/moli-renderer-v8/src/custom_elements/definition_callbacks.rs
+++ b/moli-renderer-v8/src/custom_elements/definition_callbacks.rs
@@ -19,11 +19,7 @@ pub(super) fn callbacks_for_prototype<'s>(
) -> Result<CustomElementCallbacks, CustomElementDefineError> {
let connected = callback_for_prototype(scope, prototype, "connectedCallback")?;
let disconnected = callback_for_prototype(scope, prototype, "disconnectedCallback")?;
- let connected_move = if supports_connected_move_callback(scope) {
- callback_for_prototype(scope, prototype, "connectedMoveCallback")?
- } else {
- None
- };
+ let connected_move = callback_for_prototype(scope, prototype, "connectedMoveCallback")?;
let adopted = callback_for_prototype(scope, prototype, "adoptedCallback")?;
let attribute_changed = callback_for_prototype(scope, prototype, "attributeChangedCallback")?;
Ok(CustomElementCallbacks {
@@ -52,25 +48,6 @@ pub(super) fn form_callbacks_for_prototype<'s>(
Ok(())
}
-fn supports_connected_move_callback(scope: &mut v8::PinScope<'_, '_>) -> bool {
- let global = scope.get_current_context().global(scope);
- let Some(element_ctor) = global
- .get(scope, v8str(scope, "Element").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return false;
- };
- let Some(prototype) = element_ctor
- .get(scope, v8str(scope, "prototype").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return false;
- };
- prototype
- .has(scope, v8str(scope, "moveBefore").into())
- .unwrap_or(false)
-}
-
fn callback_for_prototype<'s>(
scope: &mut v8::PinScope<'s, '_>,
prototype: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/custom_elements/registry_install.rs b/moli-renderer-v8/src/custom_elements/registry_install.rs
index ea23323e5..1485e1b60 100644
--- a/moli-renderer-v8/src/custom_elements/registry_install.rs
+++ b/moli-renderer-v8/src/custom_elements/registry_install.rs
@@ -1,9 +1,12 @@
use super::registry_runtime::CUSTOM_ELEMENTS_REGISTRY_CHILD_HANDLE_SLOT;
use crate::web_api_interfaces;
use crate::{
- context_bootstrap::{WindowLazySurface, rematerialize_window_lazy_surface_if_cached},
+ context_bootstrap::{
+ WindowLazySurface, ensure_intrinsic_interface_prototype,
+ rematerialize_window_lazy_surface_if_cached,
+ },
document_runtime::DomHandle,
- util::{get_private_value, set_private_value, v8str},
+ util::{get_private_value, set_private_value},
};
use anyhow::Result;
use moli_webapi_declare::WebApiObject;
@@ -79,8 +82,7 @@ fn new_custom_elements_registry_for_owner<'s>(
scope: &mut v8::PinScope<'s, '_>,
child_handle: Option<DomHandle>,
) -> Result<v8::Local<'s, v8::Object>> {
- let global = scope.get_current_context().global(scope);
- let registry = new_custom_elements_registry(scope, global)?;
+ let registry = new_custom_elements_registry(scope)?;
let Some(child_handle) = child_handle else {
return Ok(registry);
};
@@ -96,16 +98,8 @@ fn new_custom_elements_registry_for_owner<'s>(
fn new_custom_elements_registry<'s>(
scope: &mut v8::PinScope<'s, '_>,
- global: v8::Local<'s, v8::Object>,
) -> Result<v8::Local<'s, v8::Object>> {
- let ctor = global
- .get(scope, v8str(scope, "CustomElementRegistry").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .ok_or_else(|| anyhow::anyhow!("failed to load CustomElementRegistry constructor"))?;
- let prototype = ctor
- .get(scope, v8str(scope, "prototype").into())
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .ok_or_else(|| anyhow::anyhow!("failed to load CustomElementRegistry prototype"))?;
+ let prototype = ensure_intrinsic_interface_prototype(scope, "CustomElementRegistry")?;
CustomElementsRegistryDeclaration::new(prototype)
.bind(scope)
.map_err(anyhow::Error::from)
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs
index 820579e83..739652661 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/collections.rs
@@ -473,11 +473,9 @@ pub(in crate::native_bridge::document) fn build_detached_document_all<'s>(
collect_detached_document_all_values(scope, root, &mut values);
}
- let global = scope.get_current_context().global(scope);
- let html_all_ctor = global.get(scope, v8str(scope, "HTMLAllCollection").into())?;
- let html_all_ctor = v8::Local::<v8::Function>::try_from(html_all_ctor).ok()?;
- let prototype = html_all_ctor.get(scope, v8str(scope, "prototype").into())?;
- let prototype = v8::Local::<v8::Object>::try_from(prototype).ok()?;
+ let prototype =
+ crate::context_bootstrap::ensure_intrinsic_interface_prototype(scope, "HTMLAllCollection")
+ .ok()?;
let items = build_object_array(scope, &values);
let named =
diff --git a/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs b/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs
index d2f7641e1..d5f6c2e1f 100644
--- a/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs
+++ b/moli-renderer-v8/src/native_bridge/document/live_collections/all/builder.rs
@@ -53,11 +53,9 @@ pub(super) fn build_document_all_collection<'s>(
let data = DocumentAllCollectionDataDeclaration::new(items, named)
.bind(scope)
.ok()?;
- let global = scope.get_current_context().global(scope);
- let html_all_ctor = global.get(scope, v8str(scope, "HTMLAllCollection").into())?;
- let html_all_ctor = v8::Local::<v8::Function>::try_from(html_all_ctor).ok()?;
- let prototype = html_all_ctor.get(scope, v8str(scope, "prototype").into())?;
- let prototype = v8::Local::<v8::Object>::try_from(prototype).ok()?;
+ let prototype =
+ crate::context_bootstrap::ensure_intrinsic_interface_prototype(scope, "HTMLAllCollection")
+ .ok()?;
let object_template = v8::ObjectTemplate::new(scope);
object_template.mark_as_undetectable();
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
index 579070ba7..217a79bbe 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/media.rs
@@ -243,6 +243,58 @@ async fn media_invalid_request_url_fails_before_load() {
);
}
+#[tokio::test]
+async fn media_error_uses_the_native_prototype_after_public_constructor_replacement() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(
+ "https://media-error-intrinsics.test/page.html",
+ &loader,
+ );
+
+ vm.eval(
+ r#"
+ globalThis.__mediaErrorNativeConstructor = window.MediaError;
+ globalThis.__mediaErrorNativePrototype = MediaError.prototype;
+ window.MediaError = function ReplacementMediaError() {};
+ const video = document.createElement("video");
+ video.src = "http://[";
+ (document.body || document.documentElement).appendChild(video);
+ globalThis.__mediaErrorIntrinsicVideo = video;
+ "queued";
+ "#,
+ )
+ .expect("media error intrinsic setup should evaluate");
+
+ run_next_page_media_element_event_for_test(
+ &mut vm,
+ &loader,
+ "intrinsic media error loadstart turn",
+ )
+ .await;
+ run_next_page_media_element_event_for_test(
+ &mut vm,
+ &loader,
+ "intrinsic media error failure turn",
+ )
+ .await;
+
+ assert_eq!(
+ vm.eval(
+ r#"JSON.stringify({
+ publicConstructorReplaced: window.MediaError !== __mediaErrorNativeConstructor,
+ nativePrototype:
+ Object.getPrototypeOf(__mediaErrorIntrinsicVideo.error) ===
+ __mediaErrorNativePrototype,
+ nativeInstance:
+ __mediaErrorIntrinsicVideo.error instanceof __mediaErrorNativeConstructor,
+ code: __mediaErrorIntrinsicVideo.error && __mediaErrorIntrinsicVideo.error.code
+ })"#,
+ )
+ .expect("media error intrinsic result should evaluate"),
+ r#"{"publicConstructorReplaced":true,"nativePrototype":true,"nativeInstance":true,"code":4}"#
+ );
+}
+
#[tokio::test]
async fn media_blocks_http_dangling_markup_without_blocking_safe_url_inputs() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/construction_and_document_upgrade.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/construction_and_document_upgrade.rs
index ffb47000c..62ee4a8cc 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/construction_and_document_upgrade.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/construction_and_document_upgrade.rs
@@ -149,6 +149,172 @@ fn custom_elements_registry_shape_matches_chromium_probe() {
);
}
+#[tokio::test]
+async fn custom_elements_uses_realm_intrinsics_after_public_constructor_replacement() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let mut vm = new_page_task_executor_test_vm_with_loader(
+ "https://custom-elements-intrinsics.test/",
+ &loader,
+ );
+
+ vm.eval(
+ r#"
+ globalThis.__customElementsIntrinsicResult = "pending";
+ globalThis.__customElementsIntrinsicDetails = null;
+
+ const frame = document.createElement("iframe");
+ (document.body || document.documentElement).appendChild(frame);
+ const child = frame.contentWindow;
+
+ const parentNativeConstructor = window.CustomElementRegistry;
+ const parentNativePrototype = parentNativeConstructor.prototype;
+ const childNativeConstructor = child.CustomElementRegistry;
+ const childNativePrototype = childNativeConstructor.prototype;
+
+ function ReplacementRegistry() {
+ this.definitions = new Map();
+ }
+ ReplacementRegistry.prototype.define = function(name, constructor) {
+ this.definitions.set(name, constructor);
+ };
+ ReplacementRegistry.prototype.get = function(name) {
+ return this.definitions.get(name);
+ };
+ ReplacementRegistry.prototype.whenDefined = function(name) {
+ return Promise.resolve(this.definitions.get(name));
+ };
+
+ window.CustomElementRegistry = ReplacementRegistry;
+ child.CustomElementRegistry = ReplacementRegistry;
+
+ const parentRegistry = window.customElements;
+ const childRegistry = child.customElements;
+ const parentSameObject = parentRegistry === window.customElements;
+ const childSameObject = childRegistry === child.customElements;
+ const parentNativePrototypePreserved =
+ Object.getPrototypeOf(parentRegistry) === parentNativePrototype &&
+ parentRegistry instanceof parentNativeConstructor;
+ const childNativePrototypePreserved =
+ Object.getPrototypeOf(childRegistry) === childNativePrototype &&
+ childRegistry instanceof childNativeConstructor;
+
+ let parentConnected = 0;
+ let childConnected = 0;
+ class ParentIntrinsicElement extends HTMLElement {
+ connectedCallback() {
+ parentConnected++;
+ this.textContent = "parent connected";
+ }
+ }
+ const ChildIntrinsicElement = class extends child.HTMLElement {
+ connectedCallback() {
+ childConnected++;
+ this.textContent = "child connected";
+ }
+ };
+
+ const parentDefined = parentRegistry
+ .whenDefined("intrinsic-parent-element")
+ .then(constructor => constructor === ParentIntrinsicElement);
+ const childDefined = childRegistry
+ .whenDefined("intrinsic-child-element")
+ .then(constructor => constructor === ChildIntrinsicElement);
+ parentRegistry.define("intrinsic-parent-element", ParentIntrinsicElement);
+ childRegistry.define("intrinsic-child-element", ChildIntrinsicElement);
+
+ const parentElement = document.createElement("intrinsic-parent-element");
+ (document.body || document.documentElement).appendChild(parentElement);
+ const childElement = child.document.createElement("intrinsic-child-element");
+ (child.document.body || child.document.documentElement).appendChild(childElement);
+
+ Promise.all([parentDefined, childDefined]).then(([parentResolved, childResolved]) => {
+ const details = {
+ parentSameObject,
+ childSameObject,
+ parentNativePrototypePreserved,
+ childNativePrototypePreserved,
+ parentResolved,
+ childResolved,
+ parentConnected,
+ childConnected,
+ parentText: parentElement.textContent,
+ childText: childElement.textContent
+ };
+ __customElementsIntrinsicDetails = details;
+ __customElementsIntrinsicResult = "finished";
+ }, error => {
+ __customElementsIntrinsicDetails = { error: String(error) };
+ __customElementsIntrinsicResult = "finished";
+ });
+ "queued";
+ "#,
+ )
+ .expect("custom element intrinsic isolation scenario should initialize");
+
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "__customElementsIntrinsicResult",
+ "finished",
+ "custom element registry intrinsic isolation",
+ )
+ .await;
+ assert_eq!(
+ vm.eval("JSON.stringify(__customElementsIntrinsicDetails)")
+ .expect("custom element intrinsic isolation details should remain observable"),
+ r#"{"parentSameObject":true,"childSameObject":true,"parentNativePrototypePreserved":true,"childNativePrototypePreserved":true,"parentResolved":true,"childResolved":true,"parentConnected":1,"childConnected":1,"parentText":"parent connected","childText":"child connected"}"#
+ );
+}
+
+#[test]
+fn custom_element_move_callback_support_uses_the_native_element_interface() {
+ let mut vm = new_parsed_test_vm(
+ "https://custom-element-move-intrinsics.test/",
+ "<!doctype html><html><body></body></html>",
+ );
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const NativeElement = window.Element;
+ const nativePrototype = NativeElement.prototype;
+ const nativeMoveBefore = nativePrototype.moveBefore;
+ delete nativePrototype.moveBefore;
+ window.Element = function ReplacementElement() {};
+
+ const calls = [];
+ class MovingElement extends HTMLElement {
+ connectedCallback() { calls.push("connected"); }
+ disconnectedCallback() { calls.push("disconnected"); }
+ connectedMoveCallback() { calls.push("moved"); }
+ }
+ customElements.define("intrinsic-moving-element", MovingElement);
+
+ const parent = document.createElement("section");
+ const before = document.createElement("span");
+ const moving = document.createElement("intrinsic-moving-element");
+ parent.append(moving, before);
+ (document.body || document.documentElement).appendChild(parent);
+ calls.length = 0;
+ nativeMoveBefore.call(parent, moving, null);
+
+ return JSON.stringify({
+ nativeSurfaceRemoved: !("moveBefore" in nativePrototype),
+ publicReplacementSupportsMove: "moveBefore" in window.Element.prototype,
+ calls
+ });
+ })()
+ "#,
+ )
+ .expect("custom element move callback intrinsic probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"nativeSurfaceRemoved":true,"publicReplacementSupportsMove":false,"calls":["moved"]}"#
+ );
+}
+
#[test]
fn custom_elements_define_options_extends_uses_webidl_conversion() {
let mut vm = new_storage_test_vm("https://example.com/");
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_lifecycle_and_adoption.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_lifecycle_and_adoption.rs
index 5fc2765e1..d2b71fdac 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_lifecycle_and_adoption.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached/document_lifecycle_and_adoption.rs
@@ -1,5 +1,42 @@
use super::*;
+#[test]
+fn html_all_collections_ignore_public_constructor_replacement() {
+ let mut vm = new_parsed_test_vm(
+ "https://dom-intrinsics.test/",
+ "<!doctype html><html><body><div id='live-all'></div></body></html>",
+ );
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const nativeAllPrototype = HTMLAllCollection.prototype;
+ window.HTMLAllCollection = function ReplacementAllCollection() {};
+
+ const liveAll = document.all;
+ const detachedHtml = document.implementation.createHTMLDocument("");
+ const detachedAll = detachedHtml.all;
+
+ return JSON.stringify({
+ liveAllPrototype: Object.getPrototypeOf(liveAll) === nativeAllPrototype,
+ liveAllWorks: liveAll.namedItem("live-all") ===
+ document.getElementById("live-all"),
+ detachedAllPrototype:
+ Object.getPrototypeOf(detachedAll) === nativeAllPrototype,
+ detachedAllWorks: detachedAll.item(0) === detachedHtml.documentElement
+ });
+ })()
+ "#,
+ )
+ .expect("native DOM object intrinsic probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"liveAllPrototype":true,"liveAllWorks":true,"detachedAllPrototype":true,"detachedAllWorks":true}"#
+ );
+}
+
#[test]
fn detached_document_lifecycle_methods_use_document_prototype_brand_checks() {
let mut vm = new_storage_test_vm("https://detached-document-lifecycle-brand.test/");