Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(css): synchronize cached wrappers in their creation realm

ldm08e4d0a347f98
diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
index 3cc10420f..b6888f19d 100644
--- a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
+++ b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
@@ -141,13 +141,10 @@ pub(super) fn sync_document_fonts<'s>(
pub(super) fn apply_font_face_owner_projection<'s>(
scope: &mut v8::PinScope<'s, '_>,
- document: DomHandle,
+ holder: v8::Local<'s, v8::Object>,
owner: DomHandle,
projection: Option<&OwnerFontFaceProjection>,
) -> bool {
- let Some(holder) = crate::util::node_wrapper_from_handle(scope, document) else {
- return false;
- };
let Some(fonts) = object_property_as_object(scope, holder, FONTS_SLOT) else {
return false;
};
@@ -158,11 +155,9 @@ pub(super) fn apply_font_face_owner_projection<'s>(
pub(super) fn finish_font_face_owner_projections<'s>(
scope: &mut v8::PinScope<'s, '_>,
host: &JsContextHost,
+ holder: v8::Local<'s, v8::Object>,
document: DomHandle,
) {
- let Some(holder) = crate::util::node_wrapper_from_handle(scope, document) else {
- return;
- };
let Some(fonts) = object_property_as_object(scope, holder, FONTS_SLOT) else {
return;
};
diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs b/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs
index b938623d9..7516d9575 100644
--- a/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs
+++ b/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs
@@ -9,7 +9,7 @@ use crate::{
document_runtime::DomHandle,
dom::native::{DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, Node},
native_bridge::JsContextHost,
- util::node_wrapper_from_handle,
+ util::with_cached_node_wrapper_realm,
};
use std::collections::HashMap;
@@ -116,28 +116,42 @@ impl DocumentCssProjections {
fn apply(self, scope: &mut v8::PinScope<'_, '_>, host: &JsContextHost) {
let mut font_face_documents = Vec::new();
for projection in self.projections {
- match projection {
- DocumentCssProjection::StyleSheetList { document } => {
- let Some(holder) = node_wrapper_from_handle(scope, document) else {
- continue;
- };
- let _ = sync_document_style_sheets(scope, holder, host.dom_host(), document);
- }
- DocumentCssProjection::FontFaceOwner {
- document,
- owner,
- projection,
- } => {
- if apply_font_face_owner_projection(scope, document, owner, projection.as_ref())
- && !font_face_documents.contains(&document)
- {
- font_face_documents.push(document);
+ let document = match &projection {
+ DocumentCssProjection::StyleSheetList { document }
+ | DocumentCssProjection::FontFaceOwner { document, .. } => *document,
+ };
+ // CSS getters initialize unexposed objects from prepared native sources.
+ with_cached_node_wrapper_realm(
+ scope,
+ host,
+ document,
+ |scope, holder| match projection {
+ DocumentCssProjection::StyleSheetList { document } => {
+ let _ =
+ sync_document_style_sheets(scope, holder, host.dom_host(), document);
}
- }
- }
+ DocumentCssProjection::FontFaceOwner {
+ document,
+ owner,
+ projection,
+ } => {
+ if apply_font_face_owner_projection(
+ scope,
+ holder,
+ owner,
+ projection.as_ref(),
+ ) && !font_face_documents.contains(&document)
+ {
+ font_face_documents.push(document);
+ }
+ }
+ },
+ );
}
for document in font_face_documents {
- finish_font_face_owner_projections(scope, host, document);
+ with_cached_node_wrapper_realm(scope, host, document, |scope, holder| {
+ finish_font_face_owner_projections(scope, host, holder, document);
+ });
}
}
}
@@ -154,9 +168,10 @@ pub(crate) fn apply_stylesheet_owner_css_projections(
} else {
owner_change_detaches_cached_inline_sheet(host, change)
};
- if owner_change_projects_css(host, change)
- && let Some(owner_wrapper) = node_wrapper_from_handle(scope, owner)
- {
+ if !owner_change_projects_css(host, change) {
+ continue;
+ }
+ with_cached_node_wrapper_realm(scope, host, owner, |scope, owner_wrapper| {
if matches!(
change.kind(),
DomStylesheetOwnerChangeKind::Attribute {
@@ -186,7 +201,7 @@ pub(crate) fn apply_stylesheet_owner_css_projections(
stylesheet.id(),
);
}
- }
+ });
}
DocumentCssProjections::from_owner_changes(host, changes).apply(scope, host);
}
@@ -249,13 +264,14 @@ pub(crate) fn apply_stylesheet_source_css_projection(
&& let Some(expected_id) = host
.linked_stylesheet_source_for_owner(owner)
.and_then(|source| source.live_stylesheet_id())
- && let Some(owner_wrapper) = node_wrapper_from_handle(scope, owner)
{
- crate::native_bridge::element::detach_cached_style_sheet_if_live_stylesheet_changed(
- scope,
- owner_wrapper,
- expected_id,
- );
+ with_cached_node_wrapper_realm(scope, host, owner, |scope, owner_wrapper| {
+ crate::native_bridge::element::detach_cached_style_sheet_if_live_stylesheet_changed(
+ scope,
+ owner_wrapper,
+ expected_id,
+ );
+ });
}
DocumentCssProjections::for_source_change(host, owner).apply(scope, host);
}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
index 9c04311aa..e7d3376eb 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
@@ -6714,6 +6714,148 @@ async fn element_matches_delegates_loaded_child_document_elements() {
);
}
+#[tokio::test]
+async fn child_parser_css_preserves_document_and_result_realms() {
+ for head in [
+ "<style>div { color: green; }</style>",
+ "<link rel=author href=/author>",
+ ] {
+ let mut vm = new_storage_test_vm("https://child-parser-css-realm.test/");
+ let markup = serde_json::to_string(&format!(
+ "<!doctype html><head>{head}</head><body><div id=target>child</div>"
+ ))
+ .unwrap();
+ vm.exec(
+ &format!(
+ r#"
+globalThis.realmFrame = document.createElement('iframe');
+realmFrame.srcdoc = {markup};
+(document.body || document.documentElement || document).appendChild(realmFrame);
+"#
+ ),
+ None,
+ )
+ .expect("child CSS document should be queued");
+ run_child_navigation_commit_and_host_load_for_test(&mut vm, "child CSS realm document")
+ .await;
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const w = realmFrame.contentWindow, d = realmFrame.contentDocument;
+ const element = d.getElementById('target');
+ const list = d.querySelectorAll('div'), range = d.createRange();
+ let typeError, syntaxError;
+ try { element.matches(); } catch (error) { typeError = error; }
+ try { element.matches('['); } catch (error) { syntaxError = error; }
+ return JSON.stringify({
+ document: d === w.document && d instanceof w.Document && !(d instanceof Document),
+ element: element instanceof w.Element && !(element instanceof Element),
+ list: list instanceof w.NodeList && !(list instanceof NodeList),
+ range: range instanceof w.Range && !(range instanceof Range),
+ typeError: typeError instanceof w.TypeError && !(typeError instanceof TypeError),
+ syntaxError: syntaxError instanceof w.DOMException && !(syntaxError instanceof DOMException),
+ sheets: d.styleSheets instanceof w.StyleSheetList &&
+ Array.from(d.styleSheets).every(sheet => sheet instanceof w.CSSStyleSheet &&
+ sheet.cssRules[0] instanceof w.CSSStyleRule),
+ sheetCount: d.styleSheets.length,
+ fonts: d.fonts instanceof w.FontFaceSet
+ });
+})()
+"#,
+ )
+ .expect("child CSS wrappers and DOM results should remain in the child realm");
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),
+ serde_json::json!({
+ "document": true,
+ "element": true,
+ "list": true,
+ "range": true,
+ "typeError": true,
+ "syntaxError": true,
+ "sheets": true,
+ "sheetCount": usize::from(head.starts_with("<style>")),
+ "fonts": true,
+ }),
+ "child markup: {head}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn child_parser_css_updates_held_collections_in_their_realm() {
+ let mut vm = new_storage_test_vm("https://child-parser-css-held-realm.test/");
+ vm.exec(
+ r#"
+globalThis.realmFrame = document.createElement('iframe');
+realmFrame.srcdoc = `<!doctype html><head><script>
+ globalThis.heldSheets = document.styleSheets;
+ globalThis.heldFonts = document.fonts;
+</` + `script><style>
+ @font-face { font-family: ChildParser; src: local('ChildParser'); }
+ div { color: green; }
+</style></head><body><div>child</div>`;
+(document.body || document.documentElement || document).appendChild(realmFrame);
+"#,
+ None,
+ )
+ .expect("child CSS collection setup should be queued");
+ run_realm_prerequisite_then_expected_child_frame_semantic_turn_for_test(
+ &mut vm,
+ ChildFrameSemanticTurnKind::NavigationCommit,
+ "child should commit before the script captures CSS collections",
+ )
+ .await;
+ run_realm_prerequisite_then_expected_child_frame_semantic_turn_for_test(
+ &mut vm,
+ ChildFrameSemanticTurnKind::DocumentScriptReady,
+ "child script should capture collections before parsing style",
+ )
+ .await;
+ run_child_document_lifecycle_and_host_load_for_test(&mut vm, "child CSS collection update")
+ .await;
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const w = realmFrame.contentWindow;
+ // Inspect held objects before any Document getter can initialize or resync them.
+ const sheets = w.heldSheets, fonts = w.heldFonts;
+ const faces = Array.from(fonts);
+ const result = {
+ sheetCount: sheets.length,
+ ruleCount: sheets[0].cssRules.length,
+ sheetRealm: sheets[0] instanceof w.CSSStyleSheet &&
+ sheets[0].cssRules[0] instanceof w.CSSFontFaceRule,
+ fontCount: faces.length,
+ fontRealm: faces.every(face => face instanceof w.FontFace && !(face instanceof FontFace)),
+ sheetListRealm: sheets instanceof w.StyleSheetList,
+ fontSetRealm: fonts instanceof w.FontFaceSet
+ };
+ result.identity = sheets === w.document.styleSheets && fonts === w.document.fonts;
+ return JSON.stringify(result);
+})()
+"#,
+ )
+ .expect("parser should update already exposed child CSS collections");
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),
+ serde_json::json!({
+ "sheetCount": 1,
+ "ruleCount": 2,
+ "sheetRealm": true,
+ "fontCount": 1,
+ "fontRealm": true,
+ "sheetListRealm": true,
+ "fontSetRealm": true,
+ "identity": true,
+ })
+ );
+}
+
#[tokio::test]
async fn child_content_document_getter_does_not_enumerate_script_wrappers_after_load() {
let mut vm = new_storage_test_vm("https://child-content-document-getter-script-state.test/");
diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs
index 62b4a301f..1ff2ee510 100644
--- a/moli-renderer-v8/src/util.rs
+++ b/moli-renderer-v8/src/util.rs
@@ -482,6 +482,25 @@ pub(super) fn node_wrapper_from_handle<'s>(
.wrap_handle(scope, host_ptr, handle)
}
+/// Update an existing node wrapper in its creation realm. Native lifecycle work
+/// can run before that realm exists, so it must not allocate a wrapper in the
+/// caller's context just to synchronize a JavaScript view of native state.
+pub(crate) fn with_cached_node_wrapper_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ host: &JsContextHost,
+ handle: DomHandle,
+ operation: impl FnOnce(&mut v8::PinScope<'s, '_>, v8::Local<'s, v8::Object>),
+) {
+ let Some(wrapper) = host.native_bridge().cached_handle_wrapper(scope, handle) else {
+ return;
+ };
+ let Some(context) = wrapper.get_creation_context(scope) else {
+ return;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ operation(scope, wrapper);
+}
+
pub(super) fn global_bridge_method<'s>(
scope: &mut v8::PinScope<'s, '_>,
name: &str,