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): classify modulepreload admission by relation

ldm0d0fdcf8fffe5
diff --git a/moli-renderer-v8/src/frame_owner_model/store_tests.rs b/moli-renderer-v8/src/frame_owner_model/store_tests.rs
index ef03dfae4..c3464657e 100644
--- a/moli-renderer-v8/src/frame_owner_model/store_tests.rs
+++ b/moli-renderer-v8/src/frame_owner_model/store_tests.rs
@@ -740,12 +740,6 @@ fn main_modulepreload_owner_never_allocates_a_load_event_delay() {
Some(false),
"network-phase owner identity must not allocate a load-delay token"
);
-
- assert_eq!(
- store.current_main_document_has_style_load_event_delay(owner),
- Some(false),
- "modulepreload terminal events must not touch the Document load gate"
- );
}
#[test]
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index e86bd44c1..9dca853a2 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -9436,6 +9436,59 @@ async fn spawn_gated_text_track_resource_server(
)
}
+async fn spawn_gated_module_resource_server() -> (
+ String,
+ tokio::sync::oneshot::Receiver<String>,
+ tokio::sync::oneshot::Sender<()>,
+ tokio::task::JoinHandle<()>,
+) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind gated module resource server");
+ let addr = listener
+ .local_addr()
+ .expect("gated module resource server addr");
+ let (request_tx, request_rx) = tokio::sync::oneshot::channel();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();
+ let server = tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let (mut stream, _) = listener
+ .accept()
+ .await
+ .expect("accept gated module resource request");
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 1024];
+ loop {
+ let read = stream
+ .read(&mut buffer)
+ .await
+ .expect("read gated module resource request");
+ if read == 0 {
+ break;
+ }
+ request.extend_from_slice(&buffer[..read]);
+ if request.windows(4).any(|window| window == b"\r\n\r\n") {
+ break;
+ }
+ }
+ let _ = request_tx.send(String::from_utf8_lossy(&request).into_owned());
+ let _ = release_rx.await;
+ let body = "export default 1;";
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ });
+ (
+ format!("http://{addr}/slow-module.mjs"),
+ request_rx,
+ release_tx,
+ server,
+ )
+}
+
async fn spawn_child_external_parser_module_ready_lane_server() -> (
String,
tokio::sync::oneshot::Receiver<String>,
@@ -13419,7 +13472,7 @@ fn new_parsed_test_vm_with_loader_and_resource_completion_queue(
}
#[test]
-fn connected_modulepreload_admission_never_acquires_a_network_load_delay() {
+fn cached_connected_modulepreload_never_acquires_a_load_delay() {
let mut vm = new_parsed_test_vm(
"https://example.test/page.html",
concat!(
@@ -13469,6 +13522,116 @@ fn connected_modulepreload_admission_never_acquires_a_network_load_delay() {
);
}
+// Mirrors WPT `preload/avoid-delaying-onload-link-modulepreload.html`: the
+// response stays pending until after Window load has been observed.
+#[tokio::test]
+async fn in_flight_connected_modulepreload_does_not_delay_window_load() {
+ let (module_url, request_rx, release_tx, server) = spawn_gated_module_resource_server().await;
+ let document_url = module_url.replace("/slow-module.mjs", "/page.html");
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let markup = format!(
+ concat!(
+ "<!doctype html><html><head>",
+ "<link id='preload' rel='modulepreload' href='{module_url}'>",
+ "</head><body></body></html>",
+ ),
+ module_url = module_url,
+ );
+ let mut vm = new_parsed_page_task_executor_test_vm(&document_url, &markup, &loader);
+ vm.exec(
+ r#"
+ globalThis.__modulepreloadLifecycleEvents = [];
+ document.getElementById("preload").addEventListener("load", () => {
+ __modulepreloadLifecycleEvents.push(`link:${document.readyState}`);
+ });
+ window.addEventListener("load", () => {
+ __modulepreloadLifecycleEvents.push(`window:${document.readyState}`);
+ });
+ "#,
+ None,
+ )
+ .expect("modulepreload lifecycle listeners should install");
+ let owner = vm
+ .current_main_document_task_owner()
+ .expect("modulepreload fixture must retain a current Document owner");
+
+ vm.queue_initial_connected_style_loads_for_current_owner();
+ vm.prime_document_lifecycle_processing_and_record_stylesheet_network_results();
+ let request = tokio::time::timeout(std::time::Duration::from_secs(2), request_rx)
+ .await
+ .expect("modulepreload request should reach the server")
+ .expect("modulepreload request channel should remain open");
+ assert!(request.starts_with("GET /slow-module.mjs HTTP/1.1"));
+ assert_eq!(
+ vm.current_main_document_has_style_load_event_delay(owner),
+ Some(false),
+ "an in-flight modulepreload request must not hold the Document load gate"
+ );
+
+ let interactive = vm
+ .finish_current_main_document_parsing(owner)
+ .expect("parser EOF should prepare interactive");
+ vm.apply_main_document_interactive_lifecycle_action(interactive)
+ .expect("interactive transition should apply");
+ vm.dispatch_main_document_domcontentloaded_lifecycle(owner);
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .current_main_document_complete_transition_is_ready(owner),
+ Some(true),
+ "window load must become ready while modulepreload remains in flight"
+ );
+ assert!(
+ vm.dispatch_main_document_window_load_lifecycle(owner)
+ .expect("main Window load lifecycle should apply")
+ .is_none()
+ );
+ assert_eq!(
+ vm.eval("__modulepreloadLifecycleEvents.join('|')")
+ .expect("pre-terminal lifecycle event trace"),
+ "window:complete",
+ "window load must run before the pending modulepreload terminal"
+ );
+
+ release_tx.send(()).expect("release modulepreload response");
+ wait_for_one_page_resource_completion_selected_task_executor_test_turn(
+ &mut vm,
+ &loader,
+ "modulepreload network completion",
+ )
+ .await;
+ assert_eq!(
+ vm.eval("__modulepreloadLifecycleEvents.join('|')")
+ .expect("network-terminal lifecycle event trace"),
+ "window:complete",
+ "the network terminal may only queue the later link event"
+ );
+ assert!(
+ vm.has_ready_native_module_owner_actions(),
+ "the module-map terminal must publish its joined link-client notification"
+ );
+ assert!(
+ vm.run_one_oldest_ready_page_task_executor_turn(&loader)
+ .await
+ .expect("modulepreload owner-notification turn"),
+ "the joined link client must be notified in a later selected task"
+ );
+ assert!(
+ vm.run_one_dom_manipulation_task_executor_turn(
+ PageDomManipulationTestFamily::ConnectedStyleEvent,
+ &loader,
+ )
+ .await
+ .expect("modulepreload link-event turn")
+ );
+ assert_eq!(
+ vm.eval("__modulepreloadLifecycleEvents.join('|')")
+ .expect("complete modulepreload lifecycle event trace"),
+ "window:complete|link:complete"
+ );
+ server.await.expect("modulepreload server should finish");
+}
+
fn new_streamed_parser_test_vm(url: &str, markup: &str) -> StandaloneScriptVmHarness {
let _js_runtime = crate::JsRuntime::initialize();
let mut stream = HtmlParser.start_document(Url::parse(url).expect("test url"));
@@ -13703,9 +13866,19 @@ async fn connected_modulepreload_invalid_as_dispatches_link_error_event() {
None,
)
.expect("runtime-inserted invalid modulepreload should append");
+ let owner = vm
+ .current_main_document_task_owner()
+ .expect("invalid modulepreload fixture must retain a current Document owner");
+
+ vm.prime_document_lifecycle_processing_and_record_stylesheet_network_results();
+ assert_eq!(
+ vm.current_main_document_has_style_load_event_delay(owner),
+ Some(false),
+ "invalid modulepreload admission must retain only event identity before its error task"
+ );
assert!(
- vm.apply_connected_style_lifecycle_bodies_for_test(),
+ vm.apply_next_connected_style_event_body_for_test(),
"connected invalid modulepreload should dispatch through its document-owned link lane"
);
assert_eq!(
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index c0c32f587..6476ea637 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -500,12 +500,13 @@ impl DocumentRuntime {
if !csp_blocked && !kind.uses_connected_load_lifecycle() {
return None;
}
- let event_plan =
- if !csp_blocked && self.connected_owner_is_non_blocking_modulepreload(handle) {
- ConnectedStyleLoadEventPlan::non_blocking_modulepreload(handle)
- } else {
- ConnectedStyleLoadEventPlan::load_delaying(handle)
- };
+ let event_plan = if !csp_blocked
+ && self.connected_owner_uses_non_blocking_modulepreload_identity(handle)
+ {
+ ConnectedStyleLoadEventPlan::non_blocking_modulepreload(handle)
+ } else {
+ ConnectedStyleLoadEventPlan::load_delaying(handle)
+ };
Some(PreparedConnectedStyleLoad::new(
handle,
csp_blocked,
@@ -625,14 +626,27 @@ impl DocumentRuntime {
.has_lifecycle_state(handle)
}
- fn connected_owner_is_non_blocking_modulepreload(&self, handle: DomHandle) -> bool {
+ /// Choose the load-event lifecycle from the link relation, independently
+ /// of whether the current request is valid or fetchable.
+ ///
+ /// HTML requires every `modulepreload` processing outcome to be
+ /// non-load-delaying. Invalid `as`, non-matching media and malformed URLs
+ /// therefore retain only exact Document/element identity for any terminal
+ /// event. A stylesheet relation takes precedence when both tokens occur.
+ fn connected_owner_uses_non_blocking_modulepreload_identity(&self, handle: DomHandle) -> bool {
let node_id = NodeId::new(handle.index());
if stylesheet_link_disposition(&self.dom_host, node_id).is_some() {
return false;
}
- connected_preload_like_link_url(&self.dom_host, node_id)
- .and_then(|url| self.connected_modulepreload_request(handle, &url))
- .is_some()
+ self.dom_host
+ .node(handle)
+ .and_then(Node::as_element)
+ .is_some_and(|element| {
+ element.is_html_element("link")
+ && element
+ .attribute("rel")
+ .is_some_and(|rel| link_rel_includes_token(rel, "modulepreload"))
+ })
}
fn settle_connected_style_load_binding(
@@ -836,7 +850,7 @@ impl DocumentRuntime {
}
if let Some(admission) = event_admission {
let expects_modulepreload_identity =
- self.connected_owner_is_non_blocking_modulepreload(handle);
+ self.connected_owner_uses_non_blocking_modulepreload_identity(handle);
let admission_matches_current_processing = matches!(
(expects_modulepreload_identity, admission),
(
diff --git a/moli-renderer-v8/src/stylesheet_runtime/load.rs b/moli-renderer-v8/src/stylesheet_runtime/load.rs
index 78008cdcb..29ce8d984 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/load.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/load.rs
@@ -212,9 +212,11 @@ impl ConnectedStyleLoadEventPlan {
/// Lifecycle authority committed for one connected style/link plan.
///
-/// Valid `modulepreload` links take the identity-only variant, which captures
-/// the exact Document and element without touching the Document load gate.
-/// All other owners retain the stylesheet load-event lease.
+/// `modulepreload` links take the identity-only variant, which captures the
+/// exact Document and element without touching the Document load gate. This
+/// classification is independent of request validity, so error outcomes also
+/// remain non-load-delaying. All other owners retain the stylesheet
+/// load-event lease.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConnectedStyleLoadEventAdmission {
LoadDelaying(MainDocumentStyleLoadEventBinding),