Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(custom-elements): checkpoint only outside active JavaScript

ldm01b214ad0886a
diff --git a/moli-renderer-v8/src/callback_invocation.rs b/moli-renderer-v8/src/callback_invocation.rs
index 1b944327c..38a887998 100644
--- a/moli-renderer-v8/src/callback_invocation.rs
+++ b/moli-renderer-v8/src/callback_invocation.rs
@@ -32,8 +32,7 @@ pub(crate) fn invoke_synchronous_webidl_callback_function<'s>(
receiver,
arguments,
|scope, callback, receiver, arguments| {
- callback
- .call(scope, receiver, arguments)
+ crate::script_execution::run(scope, |scope| callback.call(scope, receiver, arguments))
.map(|value| v8::Global::new(scope, value))
.ok_or(())
},
@@ -80,31 +79,33 @@ pub(crate) fn invoke_synchronous_webidl_callback_interface<'s, R>(
let mut scope = try_catch.init();
let result =
with_webidl_callback_contexts(&mut scope, relevant_context, incumbent_context, |scope| {
- let callback_object = callback.callback(scope);
- invoke_webidl_callback(
- scope,
- WebIdlCallbackInvocation::new(
- callback_object,
- callback_this,
- callback.callable_at_conversion(),
- operation_name,
- arguments,
- ),
- |scope, callback, receiver, arguments| {
- let value = callback
- .call(scope, receiver, arguments)
- .ok_or(Failure::Pending)?;
- convert_return(scope, value).ok_or(Failure::Pending)
- },
- |scope, failure| {
- Failure::Captured(Box::new(build_event_handler_exception_report(
- scope,
- failure.exception(),
- failure.message(),
- failure.stack_trace(),
- )))
- },
- )
+ crate::script_execution::run(scope, |scope| {
+ let callback_object = callback.callback(scope);
+ invoke_webidl_callback(
+ scope,
+ WebIdlCallbackInvocation::new(
+ callback_object,
+ callback_this,
+ callback.callable_at_conversion(),
+ operation_name,
+ arguments,
+ ),
+ |scope, callback, receiver, arguments| {
+ let value = callback
+ .call(scope, receiver, arguments)
+ .ok_or(Failure::Pending)?;
+ convert_return(scope, value).ok_or(Failure::Pending)
+ },
+ |scope, failure| {
+ Failure::Captured(Box::new(build_event_handler_exception_report(
+ scope,
+ failure.exception(),
+ failure.message(),
+ failure.stack_trace(),
+ )))
+ },
+ )
+ })
});
match result {
@@ -207,9 +208,9 @@ impl CallbackInvoker {
invocation.relevant_context,
invocation.incumbent_context,
|scope| {
- let relevant_context = invocation.relevant_context;
- let previous_window_event =
- invocation
+ crate::script_execution::run(scope, |scope| {
+ let relevant_context = invocation.relevant_context;
+ let previous_window_event = invocation
.host_ptr
.and(invocation.current_event)
.map(|event| {
@@ -222,44 +223,45 @@ impl CallbackInvoker {
previous
});
- let webidl_invocation = WebIdlCallbackInvocation::new(
- invocation.callback,
- invocation.callback_this,
- invocation.is_callable,
- invocation.operation_name,
- invocation.arguments,
- );
- let result = invoke_webidl_callback(
- scope,
- webidl_invocation,
- |scope, callback, receiver, arguments| {
- invoke_callback_with_report(
- scope,
- callback_kind,
- log_label,
- log_level,
- callback_name,
- callback,
- receiver,
- arguments,
- )
- },
- |scope, failure| {
- capture_callback_resolution_failure(
- scope,
- log_label,
- log_level,
- callback_name,
- failure,
- )
- },
- );
+ let webidl_invocation = WebIdlCallbackInvocation::new(
+ invocation.callback,
+ invocation.callback_this,
+ invocation.is_callable,
+ invocation.operation_name,
+ invocation.arguments,
+ );
+ let result = invoke_webidl_callback(
+ scope,
+ webidl_invocation,
+ |scope, callback, receiver, arguments| {
+ invoke_callback_with_report(
+ scope,
+ callback_kind,
+ log_label,
+ log_level,
+ callback_name,
+ callback,
+ receiver,
+ arguments,
+ )
+ },
+ |scope, failure| {
+ capture_callback_resolution_failure(
+ scope,
+ log_label,
+ log_level,
+ callback_name,
+ failure,
+ )
+ },
+ );
- if let Some(previous) = previous_window_event {
- let global = relevant_context.global(scope);
- let _ = global.set(scope, v8str(scope, WINDOW_EVENT_SLOT).into(), previous);
- }
- result
+ if let Some(previous) = previous_window_event {
+ let global = relevant_context.global(scope);
+ let _ = global.set(scope, v8str(scope, WINDOW_EVENT_SLOT).into(), previous);
+ }
+ result
+ })
},
);
diff --git a/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs b/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs
index dd84a7dad..b3d7dabc2 100644
--- a/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/chrome_runtime.rs
@@ -376,6 +376,8 @@ fn run_chrome_app_install_state_callback<'s>(
.expect("chrome.app.installState trampoline must retain its callback");
let receiver = v8::undefined(scope);
let state: v8::Local<'s, v8::Value> = v8str(scope, INSTALL_STATE_NOT_INSTALLED).into();
- let _ = callback.call(scope, receiver.into(), &[state]);
+ let _ = crate::script_execution::run(scope, |scope| {
+ callback.call(scope, receiver.into(), &[state])
+ });
rv.set_undefined();
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
index d281ed19d..e3e4617ff 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
@@ -188,7 +188,9 @@ fn invoke_navigation_handler<'s>(
|scope, callback, receiver, arguments| {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let mut scope = try_catch.init();
- match callback.call(&scope, receiver, arguments) {
+ match crate::script_execution::run(&mut scope, |scope| {
+ callback.call(scope, receiver, arguments)
+ }) {
Some(result) => {
let current_context = scope.get_current_context();
if let Ok(promise) = v8::Local::<v8::Promise>::try_from(result)
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index 88d622f6f..dbc030b15 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -1250,7 +1250,9 @@ fn run_child_window_eval_expression<'s>(
{
scope.set_continuation_preserved_embedder_data(value);
}
- let result = function.call(scope, window.into(), &[window.into(), expression.into()]);
+ let result = crate::script_execution::run(scope, |scope| {
+ function.call(scope, window.into(), &[window.into(), expression.into()])
+ });
scope.set_continuation_preserved_embedder_data(previous_continuation_data);
let previous_active_child = v8::Local::new(scope, &previous_active_child);
native_bridge::restore_active_child_window_scope(scope, previous_active_child);
diff --git a/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs
index 7fbd404d0..874083054 100644
--- a/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/trusted_types/policy_callbacks.rs
@@ -160,7 +160,9 @@ fn invoke_and_convert_policy_callback<'s>(
arguments: &[v8::Local<'s, v8::Value>],
kind: TrustedTypeKind,
) -> Result<Option<String>, ()> {
- let result = callback.call(scope, receiver, arguments).ok_or(())?;
+ let result =
+ crate::script_execution::run(scope, |scope| callback.call(scope, receiver, arguments))
+ .ok_or(())?;
if result.is_null() || result.is_undefined() {
return Ok(None);
}
diff --git a/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/lifecycle.rs b/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/lifecycle.rs
index f497d719b..d19a26302 100644
--- a/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/lifecycle.rs
+++ b/moli-renderer-v8/src/context_bootstrap/view_transition_runtime/lifecycle.rs
@@ -301,7 +301,10 @@ pub(crate) fn run_view_transition_update_callback<'s>(
|scope, callback, receiver, arguments| {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let mut scope = try_catch.init();
- let result = callback.call(&scope, receiver, arguments).ok_or_else(|| {
+ let result = crate::script_execution::run(&mut scope, |scope| {
+ callback.call(scope, receiver, arguments)
+ })
+ .ok_or_else(|| {
ViewTransitionUpdateInvocationFailure::CallbackThrew(
scope
.exception()
diff --git a/moli-renderer-v8/src/custom_elements/construction_invocation.rs b/moli-renderer-v8/src/custom_elements/construction_invocation.rs
index 7ec0d23e4..ade53d37c 100644
--- a/moli-renderer-v8/src/custom_elements/construction_invocation.rs
+++ b/moli-renderer-v8/src/custom_elements/construction_invocation.rs
@@ -1,6 +1,7 @@
use super::reactions::enter_custom_element_reaction;
use super::super::native_bridge::JsContextHost;
+use crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections;
pub(super) enum CustomElementConstructorInvocation {
Created(v8::Global<v8::Object>),
@@ -13,22 +14,47 @@ pub(super) fn invoke_custom_element_constructor(
host_ptr: *mut JsContextHost,
constructor: v8::Local<'_, v8::Function>,
) -> CustomElementConstructorInvocation {
- let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
- let scope = try_catch.init();
- let created = {
- let _reaction = enter_custom_element_reaction(host_ptr);
- constructor.new_instance(&scope, &[])
- };
- match created {
- Some(object) => {
- CustomElementConstructorInvocation::Created(v8::Global::new(&scope, object))
+ let invocation = {
+ let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
+ let mut scope = try_catch.init();
+ let created = {
+ let _reaction = enter_custom_element_reaction(host_ptr);
+ crate::script_execution::run(&mut scope, |scope| constructor.new_instance(scope, &[]))
+ };
+ match created {
+ Some(object) => {
+ CustomElementConstructorInvocation::Created(v8::Global::new(&scope, object))
+ }
+ None if scope.has_caught() => scope
+ .exception()
+ .map(|exception| {
+ CustomElementConstructorInvocation::Exception(v8::Global::new(
+ &scope, exception,
+ ))
+ })
+ .unwrap_or(CustomElementConstructorInvocation::Empty),
+ None => CustomElementConstructorInvocation::Empty,
}
- None if scope.has_caught() => scope
- .exception()
- .map(|exception| {
- CustomElementConstructorInvocation::Exception(v8::Global::new(&scope, exception))
- })
- .unwrap_or(CustomElementConstructorInvocation::Empty),
- None => CustomElementConstructorInvocation::Empty,
+ };
+
+ // Cleaning up a constructor call checkpoints only when its caller left no
+ // JavaScript on the stack. Parser construction must do this before result
+ // validation, while createElement() and document.write() called from script
+ // must leave the queued microtasks for that outer script's completion.
+ if can_perform_custom_element_microtask_checkpoint(scope) {
+ perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
}
+ invocation
+}
+
+pub(super) fn can_perform_custom_element_microtask_checkpoint(
+ scope: &v8::PinScope<'_, '_>,
+) -> bool {
+ !scope.is_execution_terminating()
+ && scope
+ .get_current_context()
+ .get_microtask_queue()
+ .is_some_and(|queue| {
+ queue.get_microtasks_scope_depth() == 0 && !queue.is_running_microtasks()
+ })
}
diff --git a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
index d5b9fc8b3..59faaf8c5 100644
--- a/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
+++ b/moli-renderer-v8/src/custom_elements/parser_handoff_direct.rs
@@ -1,5 +1,6 @@
use super::construction_invocation::{
- CustomElementConstructorInvocation, invoke_custom_element_constructor,
+ CustomElementConstructorInvocation, can_perform_custom_element_microtask_checkpoint,
+ invoke_custom_element_constructor,
};
use super::parser_handoff_attributes::append_parser_custom_element_token_attributes;
use super::parser_handoff_definition::ParserCustomElementDefinitionMatch;
@@ -73,18 +74,14 @@ pub(super) fn construct_parser_created_custom_element_direct(
.owner_document_handle(handle);
let _dynamic_markup = enter_upgrade_dynamic_markup_insertion(host_ptr, handle);
let _parser_pause = unsafe { &mut *host_ptr }.enter_parser_pause();
- if unsafe { &*host_ptr }.should_checkpoint_before_parser_custom_element_constructor() {
+ if unsafe { &*host_ptr }.should_checkpoint_before_parser_custom_element_constructor()
+ && can_perform_custom_element_microtask_checkpoint(scope)
+ {
perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
}
with_custom_element_reaction_scope(scope, host_ptr, |scope| {
let invocation: CustomElementConstructorInvocation =
invoke_custom_element_constructor(scope, host_ptr, constructor);
- // The parser invokes the constructor from a stack-empty boundary. Run
- // the microtasks it queued before validating the constructed element,
- // matching the HTML parser's custom-element construction algorithm.
- // In particular, a constructor microtask can add an attribute and make
- // the subsequent construction-result validation fail.
- perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
let constructed_handle = handle_parser_direct_constructor_invocation(
scope,
host_ptr,
diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
index 394a118bf..a9d95d6f5 100644
--- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs
+++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs
@@ -1909,7 +1909,7 @@ fn execute_committed_inline_classic_script(
return;
};
unsafe { &mut *host_ptr }.push_current_inline_script(node);
- let run_result = script.run(scope);
+ let run_result = crate::script_execution::run(scope, |scope| script.run(scope));
unsafe { &mut *host_ptr }.pop_current_inline_script(node);
if run_result.is_some() {
let _ = runtime.enqueue_script_event_lifecycle_work(
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
index e74af900a..fdc77eef6 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
@@ -160,7 +160,7 @@ impl DocumentRuntime {
let source = v8::String::new(scope, &source)?;
let origin = create_script_origin(scope, self.document_url().as_str(), 0);
let script = v8::Script::compile(scope, source, Some(&origin))?;
- script.run(scope)
+ crate::script_execution::run(scope, |scope| script.run(scope))
})()
};
let script_timed_out = watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut;
diff --git a/moli-renderer-v8/src/exception_reporting.rs b/moli-renderer-v8/src/exception_reporting.rs
index df523e3de..72319c7d6 100644
--- a/moli-renderer-v8/src/exception_reporting.rs
+++ b/moli-renderer-v8/src/exception_reporting.rs
@@ -527,11 +527,11 @@ fn eval_debug_probe(scope: &mut v8::PinScope<'_, '_>, source: &str) -> String {
return "<alloc failed>".to_owned();
};
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
- let scope = try_catch.init();
+ let mut scope = try_catch.init();
let Some(script) = v8::Script::compile(&scope, source, None) else {
return "<compile failed>".to_owned();
};
- let Some(result) = script.run(&scope) else {
+ let Some(result) = crate::script_execution::run(&mut scope, |scope| script.run(scope)) else {
return scope
.exception()
.and_then(|value| value.to_string(&scope))
@@ -721,7 +721,9 @@ fn invoke_callback_with_report_inner<'s>(
{
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let mut scope = try_catch.init();
- if let Some(returned) = handler.call(&scope, receiver, args) {
+ if let Some(returned) =
+ crate::script_execution::run(&mut scope, |scope| handler.call(scope, receiver, args))
+ {
returned_value = Some(v8::Global::new(&scope, returned));
} else {
if scope.is_execution_terminating() {
diff --git a/moli-renderer-v8/src/host/timers.rs b/moli-renderer-v8/src/host/timers.rs
index 2ea5e9c3b..1d2e99547 100644
--- a/moli-renderer-v8/src/host/timers.rs
+++ b/moli-renderer-v8/src/host/timers.rs
@@ -1252,7 +1252,7 @@ fn run_window_timer_source(
stack_trace,
)));
};
- if script.run(&scope).is_some() {
+ if crate::script_execution::run(&mut scope, |scope| script.run(scope)).is_some() {
Ok(())
} else {
let exception = scope.exception();
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index dcd26d948..cfda37405 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -91,6 +91,7 @@ mod resource_owner;
mod resource_ready;
mod runtime;
mod runtime_binding_data;
+mod script_execution;
mod script_execution_control;
mod script_provenance;
mod script_vm;
diff --git a/moli-renderer-v8/src/module_runtime/wasm_synthetic.rs b/moli-renderer-v8/src/module_runtime/wasm_synthetic.rs
index 02217c795..83709951c 100644
--- a/moli-renderer-v8/src/module_runtime/wasm_synthetic.rs
+++ b/moli-renderer-v8/src/module_runtime/wasm_synthetic.rs
@@ -363,8 +363,7 @@ fn evaluate_wasm_dependency_module<'s>(
perform_microtasks: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Option<()>,
messages: WasmDependencyModuleMessages,
) -> Option<()> {
- let value = module
- .evaluate(scope)
+ let value = crate::script_execution::run(scope, |scope| module.evaluate(scope))
.or_else(|| preserve_current_v8_module_exception(scope))?;
perform_microtasks(scope)?;
finish_wasm_dependency_module_evaluation(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
index 3cbabd7d1..a52cabb42 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -3528,8 +3528,8 @@ impl JsContextHost {
let previous_message_source = self.enter_window_message_source_scope(
super::PendingWindowMessageEndpoint::LightweightPopup(popup_id),
);
- let run_succeeded = function
- .call(
+ let run_succeeded = crate::script_execution::run(scope, |scope| {
+ function.call(
scope,
window.into(),
&[
@@ -3541,7 +3541,8 @@ impl JsContextHost {
restore_active_popup.into(),
],
)
- .is_some();
+ })
+ .is_some();
self.restore_window_message_source_scope(previous_message_source);
if !self.lightweight_popup_document_owner_is_current(script_document_owner) {
@@ -3702,7 +3703,9 @@ impl JsContextHost {
super::PendingWindowMessageEndpoint::LightweightPopup(popup_id),
);
let eval_permit = crate::context_bootstrap::arm_internal_javascript_url_eval(scope);
- let completion = function.call(scope, window.into(), &[window.into(), source_value.into()]);
+ let completion = crate::script_execution::run(scope, |scope| {
+ function.call(scope, window.into(), &[window.into(), source_value.into()])
+ });
crate::context_bootstrap::restore_internal_javascript_url_eval(scope, eval_permit);
self.restore_window_message_source_scope(previous_message_source);
restore_active_lightweight_popup_scope(scope, previous_popup);
diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rs
index 1e56dc268..2c475044f 100644
--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs
@@ -16764,6 +16764,7 @@ window.WptWrittenTiming = class extends HTMLElement {
};
customElements.define('wpt-written-timing', window.WptWrittenTiming);
document.write('<wpt-written-timing data-token="owned"></wpt-written-timing><span id="after-write"></span>');
+window.writeCeEvents.push('after-write');
</script>
<script>
const element = document.querySelector('wpt-written-timing');
@@ -16809,8 +16810,8 @@ document.body.setAttribute('data-bad-write', String(!!document.getElementById('b
);
assert_eq!(
body_element.attribute("data-events"),
- Some("false|false|false|InvalidStateError|attr:data-token:null:owned|mo:data-token:owned|promise:owned|connected|owned|0|false|true"),
- "document.write token attributes should queue initial attribute reactions and run the resulting microtask checkpoint before connectedCallback, then flush connected before child or following sibling tokens"
+ Some("false|false|false|InvalidStateError|attr:data-token:null:owned|connected|owned|0|false|true|after-write|mo:data-token:owned|promise:owned"),
+ "document.write must deliver reactions before following tokens, then defer mutation observers and promises until its outer script returns"
);
assert_eq!(
body_element.attribute("data-connected-event"),
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index a44abfe1a..376226991 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -3647,6 +3647,55 @@ customElements.define("wpt-parser-throws", globalThis.__ThrowsElement);
.expect("parser failed custom element page should close");
}
+#[tokio::test(flavor = "current_thread")]
+async fn parser_custom_element_document_write_microtasks_wait_for_outer_script() {
+ let runtime = JsRuntime::initialize();
+ let loader =
+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
+ let url =
+ url::Url::parse("https://example.test/parser-custom-element-write-microtasks").unwrap();
+ let html = r#"<!doctype html><body>
+<script>
+window.onerror = () => true;
+globalThis.constructorMicrotaskLog = [];
+class WrittenElement extends HTMLElement {
+ constructor() {
+ super();
+ constructorMicrotaskLog.push("constructor");
+ Promise.resolve().then(() => {
+ constructorMicrotaskLog.push("microtask");
+ this.setAttribute("data-constructed", "yes");
+ });
+ }
+}
+customElements.define("microtask-written-element", WrittenElement);
+document.write("<microtask-written-element></microtask-written-element>");
+constructorMicrotaskLog.push("after-write");
+constructorMicrotaskLog.push(document.querySelector("microtask-written-element") instanceof WrittenElement);
+</script>
+<script>constructorMicrotaskLog.push("following-script");</script>
+</body>"#;
+ let mut page = create_test_html_page(&runtime, &loader, url, html).await;
+
+ let (reply, _) = page
+ .run_async_command(RendererPageCommand::EvaluateExpression {
+ expression: "JSON.stringify({log: constructorMicrotaskLog, value: document.querySelector('microtask-written-element').getAttribute('data-constructed')})".to_owned(),
+ await_promise: false,
+ })
+ .await
+ .expect("parser document.write microtask order should evaluate");
+
+ assert_eq!(
+ renderer_json_value(reply),
+ Some(serde_json::json!(
+ r#"{"log":["constructor","after-write",true,"microtask","following-script"],"value":"yes"}"#
+ ))
+ );
+ page.close_async()
+ .await
+ .expect("parser document.write microtask page should close");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn parser_custom_element_microtask_mutation_fails_before_validation() {
let runtime = JsRuntime::initialize();
diff --git a/moli-renderer-v8/src/script_execution.rs b/moli-renderer-v8/src/script_execution.rs
new file mode 100644
index 000000000..35e02df25
--- /dev/null
+++ b/moli-renderer-v8/src/script_execution.rs
@@ -0,0 +1,13 @@
+/// Enter JavaScript with the same native microtask nesting boundary used by
+/// Blink's V8ScriptRunner. Page isolates use Explicit policy, so the renderer
+/// still chooses when to checkpoint after returning from the outermost call.
+pub(crate) fn run<'s, R>(
+ scope: &mut v8::PinScope<'s, '_>,
+ execute: impl FnOnce(&mut v8::PinScope<'s, '_>) -> R,
+) -> R {
+ let microtasks = std::pin::pin!(v8::MicrotasksScope::new(
+ scope,
+ v8::MicrotasksScopeType::RunMicrotasks,
+ ));
+ execute(microtasks.init())
+}
diff --git a/moli-renderer-v8/src/script_vm/eval_exec.rs b/moli-renderer-v8/src/script_vm/eval_exec.rs
index 17cfc9c0e..76d3b9d26 100644
--- a/moli-renderer-v8/src/script_vm/eval_exec.rs
+++ b/moli-renderer-v8/src/script_vm/eval_exec.rs
@@ -237,7 +237,7 @@ fn execute_source_text_on_current_stack_with_completion(
SCRIPT_TURN_WATCHDOG_TIMEOUT,
);
let watchdog_timeout = watchdog.timeout();
- let run_result = script.run(&scope);
+ let run_result = crate::script_execution::run(&mut scope, |scope| script.run(scope));
let watchdog_timed_out = watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut;
scope.set_continuation_preserved_embedder_data(previous_continuation_data);
let value = run_result.ok_or_else(|| {
@@ -822,7 +822,7 @@ impl ScriptVm {
);
uncaught_script_error(report, "compile")
})?;
- let value = script.run(&scope).ok_or_else(|| {
+ let value = crate::script_execution::run(&mut scope, |scope| script.run(scope)).ok_or_else(|| {
let exception = scope.exception();
let message = scope.message();
let stack_trace = scope.stack_trace();
diff --git a/moli-renderer-v8/src/script_vm/native_module.rs b/moli-renderer-v8/src/script_vm/native_module.rs
index 5e54910d5..7d834a81e 100644
--- a/moli-renderer-v8/src/script_vm/native_module.rs
+++ b/moli-renderer-v8/src/script_vm/native_module.rs
@@ -3729,7 +3729,9 @@ impl ScriptVm {
let mut scope = try_catch.init();
let root_module = v8::Local::new(&scope, &root_module);
- let Some(value) = root_module.evaluate(&scope) else {
+ let Some(value) =
+ crate::script_execution::run(&mut scope, |scope| root_module.evaluate(scope))
+ else {
let error = scope
.exception()
.map(|exception| {
diff --git a/moli-renderer-v8/src/script_vm/native_module/child_dynamic_import.rs b/moli-renderer-v8/src/script_vm/native_module/child_dynamic_import.rs
index 3e636258d..c40f6e6b8 100644
--- a/moli-renderer-v8/src/script_vm/native_module/child_dynamic_import.rs
+++ b/moli-renderer-v8/src/script_vm/native_module/child_dynamic_import.rs
@@ -1054,7 +1054,9 @@ impl ScriptVm {
let mut scope = try_catch.init();
let root_module = v8::Local::new(&scope, &root_module);
- let Some(value) = root_module.evaluate(&scope) else {
+ let Some(value) =
+ crate::script_execution::run(&mut scope, |scope| root_module.evaluate(scope))
+ else {
let error = scope
.exception()
.map(|exception| {
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
index ffb59c59c..aa0fed6a8 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
@@ -1,6 +1,164 @@
use super::*;
use crate::custom_elements::CustomElementRegistryKey;
+#[tokio::test]
+async fn popup_classic_script_custom_element_microtasks_wait_for_outer_javascript() {
+ assert_popup_custom_element_microtask_order(false).await;
+}
+
+#[tokio::test]
+async fn popup_javascript_url_custom_element_microtasks_wait_for_outer_javascript() {
+ assert_popup_custom_element_microtask_order(true).await;
+}
+
+async fn assert_popup_custom_element_microtask_order(javascript_url: bool) {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
+ let mut vm = new_page_task_executor_test_vm_with_loader(
+ "https://popup-custom-element-microtasks.test/",
+ &loader,
+ );
+ vm.eval(
+ r#"
+ globalThis.__popupCeLog = [];
+ globalThis.PopupElement = class extends HTMLElement {
+ constructor() {
+ super();
+ __popupCeLog.push("constructor");
+ Promise.resolve().then(() => {
+ __popupCeLog.push("constructor-microtask");
+ this.setAttribute("data-constructed", "yes");
+ });
+ }
+ };
+ customElements.define("popup-microtask-element", PopupElement);
+ "ready";
+ "#,
+ )
+ .expect("popup custom element definition should register");
+
+ let source = r#"
+ Promise.resolve().then(() => opener.__popupCeLog.push("earlier-microtask"));
+ const element = opener.document.createElement("popup-microtask-element");
+ opener.__popupCeElement = element;
+ opener.__popupCeLog.push("after-create", element instanceof opener.PopupElement,
+ element.hasAttribute("data-constructed"));
+ void 0;
+ "#;
+ let navigation = if javascript_url {
+ format!("open({:?})", format!("javascript:{source}"))
+ } else {
+ let html = format!("<!doctype html><script>{source}</script>");
+ format!("open(URL.createObjectURL(new Blob([{html:?}], {{type: 'text/html'}})))")
+ };
+ vm.eval(&format!(
+ "globalThis.__popupCeWindow = {navigation}; 'queued'"
+ ))
+ .expect("host-owned popup execution should queue");
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "String(__popupCeLog.includes('constructor-microtask'))",
+ "true",
+ "popup custom element constructor microtask",
+ )
+ .await;
+
+ assert_eq!(
+ vm.eval("JSON.stringify({log: __popupCeLog, custom: __popupCeElement instanceof PopupElement, value: __popupCeElement.getAttribute('data-constructed')})")
+ .expect("popup custom element result should be observable"),
+ r#"{"log":["constructor","after-create",true,false,"earlier-microtask","constructor-microtask"],"custom":true,"value":"yes"}"#,
+ "popup source must finish before constructor microtasks (javascript URL: {javascript_url})",
+ );
+}
+
+#[test]
+fn custom_element_document_write_microtasks_wait_for_outer_javascript() {
+ let mut vm = new_storage_test_vm("https://custom-element-microtasks.test/");
+
+ let result = vm
+ .eval(
+ r#"
+ globalThis.constructorMicrotaskLog = [];
+ class WrittenElement extends HTMLElement {
+ constructor() {
+ super();
+ constructorMicrotaskLog.push("constructor");
+ Promise.resolve().then(() => {
+ constructorMicrotaskLog.push("constructor-microtask");
+ this.setAttribute("data-constructed", "yes");
+ });
+ }
+ }
+ customElements.define("microtask-written-element", WrittenElement);
+ Promise.resolve().then(() => constructorMicrotaskLog.push("earlier-microtask"));
+ document.write("<microtask-written-element></microtask-written-element>");
+ constructorMicrotaskLog.push("after-write");
+ const written = document.querySelector("microtask-written-element");
+ JSON.stringify({
+ log: constructorMicrotaskLog,
+ custom: written instanceof WrittenElement,
+ hasAttribute: written.hasAttribute("data-constructed")
+ });
+ "#,
+ )
+ .expect("document.write custom element should preserve the outer script boundary");
+
+ assert_eq!(
+ result,
+ r#"{"log":["constructor","after-write"],"custom":true,"hasAttribute":false}"#
+ );
+ assert_eq!(
+ vm.eval(
+ "JSON.stringify({log: constructorMicrotaskLog, value: written.getAttribute('data-constructed')})"
+ )
+ .expect("constructor microtasks should run after the outer script"),
+ r#"{"log":["constructor","after-write","earlier-microtask","constructor-microtask"],"value":"yes"}"#
+ );
+}
+
+#[test]
+fn custom_element_create_element_microtasks_wait_for_outer_javascript() {
+ let mut vm = new_storage_test_vm("https://custom-element-microtasks.test/");
+
+ let result = vm
+ .eval(
+ r#"
+ globalThis.constructorMicrotaskLog = [];
+ class CreatedElement extends HTMLElement {
+ constructor() {
+ super();
+ constructorMicrotaskLog.push("constructor");
+ queueMicrotask(() => {
+ constructorMicrotaskLog.push("microtask");
+ this.setAttribute("data-constructed", "yes");
+ });
+ }
+ }
+ customElements.define("microtask-created-element", CreatedElement);
+ const created = document.createElement("microtask-created-element");
+ constructorMicrotaskLog.push("after-create");
+ JSON.stringify({
+ log: constructorMicrotaskLog,
+ custom: created instanceof CreatedElement,
+ hasAttribute: created.hasAttribute("data-constructed")
+ });
+ "#,
+ )
+ .expect("createElement should preserve the outer script boundary");
+
+ assert_eq!(
+ result,
+ r#"{"log":["constructor","after-create"],"custom":true,"hasAttribute":false}"#
+ );
+ assert_eq!(
+ vm.eval(
+ "JSON.stringify({log: constructorMicrotaskLog, value: created.getAttribute('data-constructed')})"
+ )
+ .expect("constructor microtasks should run after createElement's caller"),
+ r#"{"log":["constructor","after-create","microtask"],"value":"yes"}"#
+ );
+}
+
#[test]
fn custom_elements_registry_shape_matches_chromium_probe() {
let mut vm = new_storage_test_vm("https://example.com/");
diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs
index 0aceefa3b..0ff3c387b 100644
--- a/moli-renderer-v8/src/util.rs
+++ b/moli-renderer-v8/src/util.rs
@@ -353,7 +353,7 @@ pub(super) fn call_global_bridge_method<'s>(
let bridge = global_bridge_object(scope)?;
let method = bridge.get(scope, v8_string(scope, name)?.into())?;
let method = v8::Local::<v8::Function>::try_from(method).ok()?;
- method.call(scope, bridge.into(), args)
+ crate::script_execution::run(scope, |scope| method.call(scope, bridge.into(), args))
}
/// Obtain a raw `*mut JsContextHost` pointer from the V8 global bridge.
@@ -447,7 +447,7 @@ pub(crate) fn call_script_visible_function<'s>(
action: &str,
) -> Option<v8::Local<'s, v8::Value>> {
debug_assert_script_visible_callback_outside_structural_mutation(scope, action);
- function.call(scope, receiver, args)
+ crate::script_execution::run(scope, |scope| function.call(scope, receiver, args))
}
pub(super) fn context_host_ptr_from_window_object(
diff --git a/vendor/v8-152.2.0/src/lib.rs b/vendor/v8-152.2.0/src/lib.rs
index 95cfbbe6e..338ec1c27 100644
--- a/vendor/v8-152.2.0/src/lib.rs
+++ b/vendor/v8-152.2.0/src/lib.rs
@@ -148,6 +148,7 @@ pub use locker::Locker;
pub use locker::SharedIsolate;
pub use microtask::MicrotaskQueue;
pub use microtask::MicrotaskQueueHandle;
+pub use microtask::{MicrotasksScope, MicrotasksScopeType};
pub use module::*;
pub use object::*;
pub use platform::IdleTask;
diff --git a/vendor/v8-152.2.0/src/microtask.rs b/vendor/v8-152.2.0/src/microtask.rs
index 1928f5b24..e41137727 100644
--- a/vendor/v8-152.2.0/src/microtask.rs
+++ b/vendor/v8-152.2.0/src/microtask.rs
@@ -4,16 +4,24 @@ use crate::Function;
use crate::Isolate;
use crate::Local;
use crate::MicrotasksPolicy;
+use crate::{Context, PinScope};
use crate::isolate::RealIsolate;
use crate::support::Opaque;
use crate::support::int;
use std::ops::Deref;
+use std::{marker::PhantomPinned, mem::MaybeUninit, pin::Pin};
use std::ptr::NonNull;
#[repr(C)]
struct MicrotaskQueueHandleRaw(Opaque);
unsafe extern "C" {
+ fn v8__MicrotasksScope__CONSTRUCT(
+ storage: *mut [MaybeUninit<usize>; 3],
+ context: *const Context,
+ kind: MicrotasksScopeType,
+ );
+ fn v8__MicrotasksScope__DESTRUCT(storage: *mut [MaybeUninit<usize>; 3]);
fn v8__MicrotaskQueueHandle__New(
isolate: *mut RealIsolate,
policy: MicrotasksPolicy,
@@ -39,6 +47,65 @@ unsafe extern "C" {
);
}
+/// Whether this scope participates in the depth that controls microtasks.
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub enum MicrotasksScopeType {
+ RunMicrotasks = 0,
+ DoNotRunMicrotasks = 1,
+}
+
+/// A native V8 microtask scope, borrowed from the current context's handle scope.
+///
+/// Pin this value and call [`Self::init`] before executing JavaScript. Dropping
+/// an initialized RunMicrotasks scope decrements the queue's scope depth. With
+/// Scoped policy V8 checkpoints at the outermost return; with Explicit policy
+/// the embedder remains responsible for scheduling checkpoints.
+pub struct MicrotasksScope<'a, 's, 'i> {
+ storage: [MaybeUninit<usize>; 3],
+ scope: &'a mut PinScope<'s, 'i>,
+ kind: MicrotasksScopeType,
+ initialized: bool,
+ _pinned: PhantomPinned,
+}
+
+impl<'a, 's, 'i> MicrotasksScope<'a, 's, 'i> {
+ pub fn new(scope: &'a mut PinScope<'s, 'i>, kind: MicrotasksScopeType) -> Self {
+ Self {
+ storage: [MaybeUninit::uninit(); 3],
+ scope,
+ kind,
+ initialized: false,
+ _pinned: PhantomPinned,
+ }
+ }
+
+ /// Constructs the native scope at its pinned address. May be called once.
+ pub fn init(self: Pin<&mut Self>) -> &mut PinScope<'s, 'i> {
+ // SAFETY: storage remains pinned until Drop, and borrowing the parent scope
+ // keeps both its context and isolate alive throughout the native scope.
+ let this = unsafe { self.get_unchecked_mut() };
+ assert!(!this.initialized, "MicrotasksScope is already initialized");
+ unsafe {
+ v8__MicrotasksScope__CONSTRUCT(
+ &mut this.storage,
+ &*this.scope.get_current_context(),
+ this.kind,
+ );
+ }
+ this.initialized = true;
+ this.scope
+ }
+}
+
+impl Drop for MicrotasksScope<'_, '_, '_> {
+ fn drop(&mut self) {
+ if self.initialized {
+ unsafe { v8__MicrotasksScope__DESTRUCT(&mut self.storage) };
+ }
+ }
+}
+
/// Represents the microtask queue, where microtasks are stored and processed.
/// https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue
/// https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments)
diff --git a/vendor/v8-152.2.0/src/microtasks_scope_ext.cc b/vendor/v8-152.2.0/src/microtasks_scope_ext.cc
new file mode 100644
index 000000000..d6b08dbcd
--- /dev/null
+++ b/vendor/v8-152.2.0/src/microtasks_scope_ext.cc
@@ -0,0 +1,19 @@
+#include "support.h"
+#include "v8-microtask-queue.h"
+
+using namespace support;
+
+static_assert(sizeof(v8::MicrotasksScope) == sizeof(uintptr_t) * 3);
+static_assert(alignof(v8::MicrotasksScope) == alignof(uintptr_t));
+
+extern "C" {
+void v8__MicrotasksScope__CONSTRUCT(uninit_t<v8::MicrotasksScope>* storage,
+ const v8::Context& context,
+ v8::MicrotasksScope::Type type) {
+ construct_in_place<v8::MicrotasksScope>(storage, ptr_to_local(&context), type);
+}
+
+void v8__MicrotasksScope__DESTRUCT(v8::MicrotasksScope* scope) {
+ scope->~MicrotasksScope();
+}
+}