Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(fetch): share complete RequestInit conversion across globals
ldm08e01a0a4e6f0
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rsindex 164a2c346..8e095a93d 100644--- a/moli-renderer-v8/src/network_host.rs+++ b/moli-renderer-v8/src/network_host.rs@@ -129,14 +129,14 @@ pub(crate) use self::media::{pub(in crate::network_host) use self::preflight_events::CorsPreflightNetworkObserver;pub(in crate::network_host) use self::request::normalize_request_method;pub(crate) use self::request::request_constructor_callback;-pub(crate) use self::request::{FetchArgumentError, RequestUrlError, convert_fetch_arguments};pub(crate) use self::request::{- mark_request_input_body_used_for_fetch, request_input_snapshot,- try_resolve_request_constructor_url, try_resolve_request_constructor_url_for_base,- try_resolve_request_constructor_url_for_child,+ FetchArgs, parse_fetch_init, parse_request_redirect_mode_label, request_object_credentials_mode,};+pub(crate) use self::request::{FetchArgumentError, RequestUrlError, convert_fetch_arguments};pub(crate) use self::request::{- parse_fetch_init, parse_request_redirect_mode_label, request_object_credentials_mode,+ mark_request_input_body_used_for_fetch, request_body_already_used_error,+ try_resolve_request_constructor_url, try_resolve_request_constructor_url_for_base,+ try_resolve_request_constructor_url_for_child, validate_request_method_body,};pub(in crate::network_host) use self::request_scope::{XHR_CHILD_CONTEXT_HANDLE_SLOT, active_subresource_network_partition_key,diff --git a/moli-renderer-v8/src/network_host/fetch/bindings.rs b/moli-renderer-v8/src/network_host/fetch/bindings.rsindex 9c668d788..a6107fda2 100644--- a/moli-renderer-v8/src/network_host/fetch/bindings.rs+++ b/moli-renderer-v8/src/network_host/fetch/bindings.rs@@ -152,21 +152,14 @@ pub(crate) fn window_fetch_callback<'s>(// caller's realm is still current. Besides choosing the right realm for// conversion failures, this permits getters to run; the frozen receiver// is revalidated only after all such author code has completed.- let (mut parsed, signal) = match convert_fetch_arguments(scope, |scope| {- let parsed = parse_window_fetch_input(scope, &args)?;- let signal = window_fetch_signal_value(scope, &args)?- .map(|value| validate_window_fetch_signal(scope, unsafe { &mut *host_ptr }, value))- .transpose()?- .flatten()- .map(|signal| v8::Global::new(scope, signal));- Ok((parsed, signal))- }) {- Ok(parsed) => parsed,- Err(exception) => {- rv.set(make_rejected_promise_with_value(scope, exception).into());- return;- }- };+ let mut parsed =+ match convert_fetch_arguments(scope, |scope| parse_window_fetch_input(scope, &args)) {+ Ok(parsed) => parsed,+ Err(exception) => {+ rv.set(make_rejected_promise_with_value(scope, exception).into());+ return;+ }+ };let Some(binding) = receiver.resolve_live_binding(unsafe { &*host_ptr }) else {// This also catches the subtle generation race where a RequestInit@@ -192,6 +185,7 @@ pub(crate) fn window_fetch_callback<'s>(};let relevant_context = v8::Local::new(scope, &relevant_context);let scope = &mut v8::ContextScope::new(scope, relevant_context);+ let signal = parsed.signal.take();window_fetch_callback_in_relevant_realm(scope, parsed, signal, fetch_context, rv);}@@ -342,68 +336,6 @@ fn window_fetch_callback_in_relevant_realm<'s>(rv.set(promise.into());}-fn window_fetch_signal_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,-) -> Result<Option<v8::Local<'s, v8::Value>>, crate::webidl::WebIdlError> {- let signal_key = v8str(scope, "signal");- if args.length() > 1 {- let init_arg = args.get(1);- if !init_arg.is_null_or_undefined()- && let Ok(init) = v8::Local::<v8::Object>::try_from(init_arg)- && init.has(scope, signal_key.into()).ok_or_else(|| {- crate::webidl::WebIdlError::pending_exception(crate::webidl::Context::member(- "RequestInit",- "signal",- ))- })?- {- return crate::webidl::property_result(- scope,- init,- "signal",- crate::webidl::Context::member("RequestInit", "signal"),- );- }- }-- let request_like = args.get(0);- if !request_like.is_null_or_undefined()- && request_like.is_object()- && let Ok(request_like) = v8::Local::<v8::Object>::try_from(request_like)- {- return crate::webidl::property_result(- scope,- request_like,- "signal",- crate::webidl::Context::member("Request", "signal"),- );- }-- Ok(None)-}--fn validate_window_fetch_signal<'s>(- scope: &mut v8::PinScope<'s, '_>,- host: &mut JsContextHost,- value: v8::Local<'s, v8::Value>,-) -> Result<Option<v8::Local<'s, v8::Object>>, crate::webidl::WebIdlError> {- if value.is_null_or_undefined() {- return Ok(None);- }- let Ok(signal) = v8::Local::<v8::Object>::try_from(value) else {- return Err(crate::webidl::WebIdlError::custom_message(- "Failed to execute 'fetch' on 'Window': signal must be an AbortSignal.",- ));- };- if !host.is_abort_signal(scope, signal) {- return Err(crate::webidl::WebIdlError::custom_message(- "Failed to execute 'fetch' on 'Window': signal must be an AbortSignal.",- ));- }- Ok(Some(signal))-}-fn install_window_fetch_abort_listener<'s>(scope: &mut v8::PinScope<'s, '_>,signal: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/network_host/fetch/input.rs b/moli-renderer-v8/src/network_host/fetch/input.rsindex fa2a89be2..a6d6a75a9 100644--- a/moli-renderer-v8/src/network_host/fetch/input.rs+++ b/moli-renderer-v8/src/network_host/fetch/input.rs@@ -16,6 +16,7 @@ pub(super) struct ParsedWindowFetchInput {pub(super) referrer_policy: String,pub(super) integrity: String,pub(super) keepalive: bool,+ pub(super) signal: Option<v8::Global<v8::Object>>,pub(super) request_body_owner: Option<v8::Global<v8::Object>>,}@@ -28,12 +29,14 @@ pub(super) fn parse_window_fetch_input<'s>(webidl::WebIdlError::missing_required(webidl::Context::argument("fetch", 1)).into(),);}- let arg0 = args.get(0);- let inherited = request_input_snapshot(scope, arg0)?;+ let args = webidl::try_parse_args::<crate::network_host::FetchArgs>(scope, args)?;+ let (url, inherited, source) = args.input.materialize(scope)?;if let Some(inherited) = inherited {- let req_obj = v8::Local::<v8::Object>::try_from(arg0).expect("request-like object");- let url = inherited.url.clone();- let init = parse_fetch_init(scope, args, 1)?;+ let req_obj = source.expect("request input source");+ let init = parse_fetch_init(scope, args.init)?;+ if inherited.body_unusable && !init.body_present {+ return Err(crate::network_host::request_body_already_used_error().into());+ }let request_body_owner = (!init.body_present && inherited.body.is_some()).then(|| v8::Global::new(scope, req_obj));let method = if init.method_present {@@ -60,6 +63,7 @@ pub(super) fn parse_window_fetch_input<'s>(.or_else(|| moli_fetch::RequestMode::from_str(&inherited.mode).ok()).unwrap_or(moli_fetch::RequestMode::Cors);validate_no_cors_method(request_mode, &method)?;+ crate::network_host::validate_request_method_body(&method, body.as_ref())?;if request_mode == moli_fetch::RequestMode::NoCors {headers = filter_headers_for_guard(&headers, HeadersGuard::RequestNoCors);}@@ -89,13 +93,14 @@ pub(super) fn parse_window_fetch_input<'s>(referrer_policy: init.referrer_policy.unwrap_or(inherited.referrer_policy),integrity: init.integrity.unwrap_or(inherited.integrity),keepalive: init.keepalive.unwrap_or(inherited.keepalive),+ signal: init.signal.unwrap_or(inherited.signal),request_body_owner,})} else {- let url = fetch_request_info_url(scope, arg0)?;- let init = parse_fetch_init(scope, args, 1)?;+ let init = parse_fetch_init(scope, args.init)?;let request_mode = init.request_mode.unwrap_or(moli_fetch::RequestMode::Cors);validate_no_cors_method(request_mode, &init.method)?;+ crate::network_host::validate_request_method_body(&init.method, init.body.as_ref())?;let headers = if request_mode == moli_fetch::RequestMode::NoCors {filter_headers_for_guard(&init.headers, HeadersGuard::RequestNoCors)} else {@@ -121,6 +126,7 @@ pub(super) fn parse_window_fetch_input<'s>(referrer_policy: init.referrer_policy.unwrap_or_default(),integrity: init.integrity.unwrap_or_default(),keepalive: init.keepalive.unwrap_or(false),+ signal: init.signal.flatten(),request_body_owner: None,})}@@ -140,11 +146,3 @@ fn validate_no_cors_method(}Ok(())}--fn fetch_request_info_url<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,-) -> Result<String, webidl::WebIdlError> {- webidl::convert::<webidl::UsvString>(scope, value, webidl::Context::argument("fetch", 1))- .map(Into::into)-}diff --git a/moli-renderer-v8/src/network_host/request.rs b/moli-renderer-v8/src/network_host/request.rsindex 513661816..cbea5e5c2 100644--- a/moli-renderer-v8/src/network_host/request.rs+++ b/moli-renderer-v8/src/network_host/request.rs@@ -10,13 +10,13 @@ use super::*;pub(crate) use self::bindings::request_constructor_callback;pub(crate) use self::error::{FetchArgumentError, RequestUrlError};-pub(crate) use self::init::convert_fetch_arguments;pub(in crate::network_host) use self::init::request_credentials_mode_label;+pub(crate) use self::init::{FetchArgs, convert_fetch_arguments};pub(crate) use self::init::{parse_fetch_init, request_object_credentials_mode};pub(crate) use self::init::{parse_request_redirect_mode_label, request_redirect_mode_label};pub(in crate::network_host) use self::input::normalize_request_method;pub(crate) use self::input::{- mark_request_input_body_used_for_fetch, request_input_snapshot,+ mark_request_input_body_used_for_fetch, request_body_already_used_error,try_resolve_request_constructor_url, try_resolve_request_constructor_url_for_base,- try_resolve_request_constructor_url_for_child,+ try_resolve_request_constructor_url_for_child, validate_request_method_body,};diff --git a/moli-renderer-v8/src/network_host/request/bindings.rs b/moli-renderer-v8/src/network_host/request/bindings.rsindex e46e6b2da..ff75f44c3 100644--- a/moli-renderer-v8/src/network_host/request/bindings.rs+++ b/moli-renderer-v8/src/network_host/request/bindings.rs@@ -52,6 +52,15 @@ struct RequestInstanceDeclaration<'scope> {body_used: (),}+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "Request")]+struct RequestConstructorArgs<'s> {+ #[webidl(required, converter = "raw")]+ input: super::input::RequestInfo<'s>,+ #[webidl(dictionary)]+ init: super::init::RequestInitMembers<'s>,+}+pub(crate) fn request_constructor_callback<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -65,11 +74,14 @@ pub(crate) fn request_constructor_callback<'s>(return;}+ let Some(parsed) = webidl::parse_args::<RequestConstructorArgs>(scope, &args) else {+ return;+ };let obj = args.this();let data = args.data();let child_handle = callback_child_handle(scope, data);let base_url = callback_base_url(scope, data);- let mut state = match request_initial_state(scope, &args, child_handle, base_url) {+ let mut state = match request_initial_state(scope, parsed.input, child_handle, base_url) {Ok(state) => state,Err(error) => {webidl::throw_error(scope, &error);@@ -77,11 +89,7 @@ pub(crate) fn request_constructor_callback<'s>(}};- let init_arg = args.get(1);- if !init_arg.is_null_or_undefined()- && let Ok(init) = v8::Local::<v8::Object>::try_from(init_arg)- && let Err(error) = apply_request_init_overrides(scope, init, &mut state)- {+ if let Err(error) = apply_request_init_overrides(scope, parsed.init, &mut state) {webidl::throw_error(scope, &error);return;}diff --git a/moli-renderer-v8/src/network_host/request/bindings/init.rs b/moli-renderer-v8/src/network_host/request/bindings/init.rsindex 6668e33f5..f43449389 100644--- a/moli-renderer-v8/src/network_host/request/bindings/init.rs+++ b/moli-renderer-v8/src/network_host/request/bindings/init.rs@@ -1,12 +1,10 @@use super::super::init::RequestInitMembers;use super::super::input::{normalize_request_method, normalize_request_referrer, request_body_already_used_error,- request_headers_guard_for_mode, request_input_snapshot_for_constructor, request_input_url,- request_method_allows_body, request_signal_snapshot_from_value,+ request_headers_guard_for_mode, request_method_allows_body,try_resolve_request_constructor_url_for_scope,};use super::super::*;-use crate::web_api_interfaces;use crate::webidl;use moli_fetch::{RequestMode, RequestRedirectMode};@@ -32,20 +30,11 @@ pub(super) struct RequestConstructionState {pub(super) fn request_initial_state<'s>(scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,+ input: super::super::input::RequestInfo<'s>,child_handle: Option<crate::document_runtime::DomHandle>,base_url: Option<url::Url>,) -> Result<RequestConstructionState, webidl::WebIdlError> {- if args.length() < 1 {- return Err(webidl::WebIdlError::missing_required(- webidl::Context::argument("Request", 1),- ));- }- let inherited = request_input_snapshot_for_constructor(scope, args.get(0))?;- let url_str = match inherited.as_ref() {- Some(snapshot) => snapshot.url.clone(),- None => request_input_url(scope, args.get(0))?,- };+ let (url_str, inherited, _) = input.materialize(scope)?;let url_resolved =try_resolve_request_constructor_url_for_scope(scope, &url_str, child_handle, base_url).map_err(|_| {@@ -130,26 +119,22 @@ pub(super) fn request_initial_state<'s>(pub(super) fn apply_request_init_overrides<'s>(scope: &mut v8::PinScope<'s, '_>,- init: v8::Local<'s, v8::Object>,+ parsed: RequestInitMembers<'s>,state: &mut RequestConstructionState,) -> Result<(), webidl::WebIdlError> {- let parsed = webidl::parse_dictionary_object::<RequestInitMembers>(scope, init)?;-let method_overridden = parsed.method.is_some();if let Some(method) = parsed.method {state.method = normalize_request_method(&method)?;}- let init_body_value = webidl::property_result(- scope,- init,- "body",- webidl::Context::member("RequestInit", "body"),- )?;- let init_body_is_readable_stream = init_body_value+ let init_body_is_readable_stream = parsed+ .body.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- .is_some_and(|object| web_api_interfaces::ReadableStream::is_instance(scope, object));- let body_from_init = init_body_value- .map(|value| body_init(scope, value, webidl::Context::member("RequestInit", "body")))+ .is_some_and(|object| {+ crate::web_api_interfaces::ReadableStream::is_instance(scope, object)+ });+ let body_from_init = parsed+ .body+ .map(|body| body_init(scope, body, webidl::Context::member("RequestInit", "body"))).transpose()?.flatten();if let Some(init_body) = body_from_init.as_ref() {@@ -157,7 +142,7 @@ pub(super) fn apply_request_init_overrides<'s>(state.body = Some(init_body.bytes.clone());state.inherited_body_unusable = false;}- if state.body.as_ref().is_some_and(|body| !body.is_empty())+ if state.body.is_some()&& (body_from_init.is_some() || method_overridden)&& !request_method_allows_body(&state.method){@@ -168,12 +153,8 @@ pub(super) fn apply_request_init_overrides<'s>(if let Some(headers) = parsed.headers {state.headers = headers;}- let signal_key = v8str(scope, "signal");- if init.has(scope, signal_key.into()).unwrap_or(false) {- let signal = init- .get(scope, signal_key.into())- .unwrap_or_else(|| v8::undefined(scope).into());- state.signal = request_signal_snapshot_from_value(scope, signal)?;+ if let Some(signal) = parsed.signal {+ state.signal = signal;}if let Some(mode) = parsed.mode.map(|value| value.0) {if mode == RequestMode::Navigate {diff --git a/moli-renderer-v8/src/network_host/request/init.rs b/moli-renderer-v8/src/network_host/request/init.rsindex 31f351e5c..f2eb8103e 100644--- a/moli-renderer-v8/src/network_host/request/init.rs+++ b/moli-renderer-v8/src/network_host/request/init.rs@@ -1,4 +1,4 @@-use super::input::{normalize_request_method, normalize_request_referrer};+use super::input::{RequestInfo, normalize_request_method, normalize_request_referrer};use super::*;use crate::webidl;use moli_fetch::{FetchPriorityHint, RequestCredentialsMode, RequestMode, RequestRedirectMode};@@ -49,6 +49,7 @@ pub(crate) struct ParsedFetchInit {pub(crate) referrer_policy: Option<String>,pub(crate) integrity: Option<String>,pub(crate) keepalive: Option<bool>,+ pub(crate) signal: Option<Option<v8::Global<v8::Object>>>,}impl Default for ParsedFetchInit {@@ -70,6 +71,7 @@ impl Default for ParsedFetchInit {referrer_policy: None,integrity: None,keepalive: None,+ signal: None,}}}@@ -92,22 +94,21 @@ pub(super) struct RequestPriorityWebIdl(pub(super) FetchPriorityHint);#[derive(webidl::WebIdlDictionary)]#[webidl(prefix = "RequestInit")]-pub(super) struct RequestInitMembers {- #[webidl(legacy_nullish)]+pub(crate) struct RequestInitMembers<'s> {+ // Keep the opaque BodyInit value until native extraction, matching Blink.+ #[webidl(nullable, converter = "raw")]+ pub(super) body: Option<v8::Local<'s, v8::Value>>,+ #[webidl(with = request_init_signal_member)]+ pub(super) signal: Option<Option<v8::Global<v8::Object>>>,pub(super) method: Option<String>,- #[webidl(legacy_nullish)]pub(super) cache: Option<String>,#[webidl(converter = "enum")]pub(super) mode: Option<RequestModeWebIdl>,- #[webidl(legacy_nullish, converter = "enum")]+ #[webidl(converter = "enum")]pub(super) redirect: Option<RequestRedirectModeWebIdl>,- #[webidl(legacy_nullish)]pub(super) referrer: Option<String>,- #[webidl(legacy_nullish)]pub(super) referrer_policy: Option<String>,- #[webidl(legacy_nullish)]pub(super) integrity: Option<String>,- #[webidl(legacy_nullish)]pub(super) duplex: Option<String>,#[webidl(with = request_init_headers_member)]pub(super) headers: Option<Vec<(String, String)>>,@@ -118,6 +119,27 @@ pub(super) struct RequestInitMembers {pub(super) keepalive: Option<bool>,}+fn request_init_signal_member<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ _: &str,+) -> Result<Option<Option<v8::Global<v8::Object>>>, webidl::WebIdlError> {+ let context = webidl::Context::member("RequestInit", "signal");+ let Some(value) = webidl::property_result(scope, object, "signal", context)?+ .filter(|value| !value.is_undefined())+ else {+ return Ok(None);+ };+ if value.is_null() {+ return Ok(Some(None));+ }+ let signal = v8::Local::<v8::Object>::try_from(value)+ .ok()+ .and_then(|signal| crate::abort_signal_route::ResolvedAbortSignal::resolve(scope, signal))+ .ok_or_else(|| webidl::WebIdlError::cannot_convert(context, "AbortSignal"))?;+ Ok(Some(Some(v8::Global::new(scope, signal.value()))))+}+fn request_init_headers_member<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,@@ -129,71 +151,55 @@ fn request_init_headers_member<'s>("headers",webidl::Context::member("RequestInit", "headers"),)?- .filter(|value| !value.is_null_or_undefined())+ .filter(|value| !value.is_undefined()).map(|headers| headers_entries_from_init(scope, headers).map(Some)).unwrap_or(Ok(None))}+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "fetch")]+pub(crate) struct FetchArgs<'s> {+ #[webidl(required, converter = "raw")]+ pub(crate) input: RequestInfo<'s>,+ #[webidl(dictionary)]+ pub(crate) init: RequestInitMembers<'s>,+}+pub(crate) fn parse_fetch_init<'s>(scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,- index: i32,+ init: RequestInitMembers<'s>,) -> Result<ParsedFetchInit, webidl::WebIdlError> {- if args.length() <= index {- return Ok(ParsedFetchInit::default());- }-- let Some(init_object) = webidl::optional_object_arg(args, index) else {- return Ok(ParsedFetchInit::default());- };-- let init = webidl::parse_dictionary_object::<RequestInitMembers>(scope, init_object)?;let priority = init.priority.map(|value| value.0);- let method_present = init_object- .has(scope, v8str(scope, "method").into())- .ok_or_else(|| {- webidl::WebIdlError::pending_exception(webidl::Context::member("RequestInit", "method"))- })?;+ let method_present = init.method.is_some();let method = init.method.map(|s| normalize_request_method(&s)).transpose()?.unwrap_or_else(|| "GET".to_owned());- let body_present = init_object- .has(scope, v8str(scope, "body").into())- .ok_or_else(|| {- webidl::WebIdlError::pending_exception(webidl::Context::member("RequestInit", "body"))- })?;- let prepared_body = webidl::property_result(- scope,- init_object,- "body",- webidl::Context::member("RequestInit", "body"),- )?- .map(|value| body_init(scope, value, webidl::Context::member("RequestInit", "body")))- .transpose()?- .flatten();- let body = prepared_body.as_ref().map(|body| body.bytes.clone());- let body_content_type = prepared_body- .as_ref()- .and_then(|body| body.content_type.clone());- if body.as_ref().is_some_and(|body| !body.is_empty())- && matches!(method.as_str(), "GET" | "HEAD")+ let body_present = init.body.is_some();+ if init.keepalive == Some(true)+ && init+ .body+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ .is_some_and(|object| {+ crate::web_api_interfaces::ReadableStream::is_instance(scope, object)+ }){return Err(webidl::WebIdlError::custom_message(- "Request with GET/HEAD method cannot have body",+ "Request with keepalive cannot have a ReadableStream body",));}-- let headers_present = init_object- .has(scope, v8str(scope, "headers").into())- .ok_or_else(|| {- webidl::WebIdlError::pending_exception(webidl::Context::member(- "RequestInit",- "headers",- ))- })?;+ let prepared_body = init+ .body+ .map(|body| body_init(scope, body, webidl::Context::member("RequestInit", "body")))+ .transpose()?+ .flatten();+ let body = prepared_body.as_ref().map(|body| body.bytes.clone());+ let body_content_type = prepared_body+ .as_ref()+ .and_then(|body| body.content_type.clone());+ let headers_present = init.headers.is_some();let mut extra_headers = init.headers.unwrap_or_default();append_default_body_content_type(&mut extra_headers, body_content_type.as_deref());@@ -221,6 +227,7 @@ pub(crate) fn parse_fetch_init<'s>(referrer_policy: init.referrer_policy,integrity: init.integrity,keepalive: init.keepalive,+ signal: init.signal,})}@@ -232,8 +239,13 @@ pub(crate) fn request_object_credentials_mode<'s>(return Ok(request_slot_string(scope, object, REQUEST_CREDENTIALS_SLOT).and_then(|value| RequestCredentialsMode::from_str(&value).ok()));}- webidl::parse_dictionary_object::<RequestInitMembers>(scope, object)- .map(|parsed| parsed.credentials_mode.map(|value| value.0))+ webidl::optional_member::<webidl::EnumValue<RequestCredentialsModeWebIdl>>(+ scope,+ object,+ "credentials",+ webidl::Context::member("Request", "credentials"),+ )+ .map(|value| value.map(|value| value.0.0))}pub(in crate::network_host) fn request_credentials_mode_label(diff --git a/moli-renderer-v8/src/network_host/request/input.rs b/moli-renderer-v8/src/network_host/request/input.rsindex a81ff9110..c853f61bb 100644--- a/moli-renderer-v8/src/network_host/request/input.rs+++ b/moli-renderer-v8/src/network_host/request/input.rs@@ -32,6 +32,18 @@ pub(super) fn request_method_allows_body(method: &str) -> bool {!matches!(method, "GET" | "HEAD")}+pub(crate) fn validate_request_method_body(+ method: &str,+ body: Option<&bytes::Bytes>,+) -> Result<(), webidl::WebIdlError> {+ if body.is_some() && !request_method_allows_body(method) {+ return Err(webidl::WebIdlError::custom_message(+ "Request with GET/HEAD method cannot have body",+ ));+ }+ Ok(())+}+pub(super) fn request_headers_guard_for_mode(mode: &str) -> HeadersGuard {if mode == "no-cors" {HeadersGuard::RequestNoCors@@ -40,6 +52,60 @@ pub(super) fn request_headers_guard_for_mode(mode: &str) -> HeadersGuard {}}+/// Standard RequestInfo paths retain the native Request or converted URL.+/// The boxed snapshot is confined to the existing request-like object extension.+pub(crate) enum RequestInfo<'s> {+ Native(v8::Local<'s, v8::Object>),+ Url(String),+ Legacy(v8::Local<'s, v8::Object>, Box<RequestInputSnapshot>),+}++impl<'s> webidl::WebIdlConverter<'s> for RequestInfo<'s> {+ type Options = ();+ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _: &(),+ ) -> Result<Self, webidl::WebIdlError> {+ if let Ok(object) = v8::Local::<v8::Object>::try_from(value) {+ if is_branded_request_object(scope, object) {+ return Ok(Self::Native(object));+ }+ if let Some(snapshot) = request_input_snapshot_for_constructor(scope, value)? {+ return Ok(Self::Legacy(object, Box::new(snapshot)));+ }+ }+ webidl::convert::<webidl::UsvString>(scope, value, context).map(|value| Self::Url(value.0))+ }+}++impl<'s> RequestInfo<'s> {+ pub(crate) fn materialize(+ self,+ scope: &mut v8::PinScope<'s, '_>,+ ) -> Result<+ (+ String,+ Option<RequestInputSnapshot>,+ Option<v8::Local<'s, v8::Object>>,+ ),+ webidl::WebIdlError,+ > {+ match self {+ Self::Url(url) => Ok((url, None, None)),+ Self::Legacy(source, snapshot) => {+ Ok((snapshot.url.clone(), Some(*snapshot), Some(source)))+ }+ Self::Native(source) => {+ let snapshot = request_input_snapshot_for_constructor(scope, source.into())?+ .expect("native Request snapshot");+ Ok((snapshot.url.clone(), Some(snapshot), Some(source)))+ }+ }+ }+}+pub(crate) struct RequestInputSnapshot {pub(crate) url: String,pub(crate) method: String,@@ -59,21 +125,6 @@ pub(crate) struct RequestInputSnapshot {pub(crate) signal: Option<v8::Global<v8::Object>>,}-pub(super) fn request_input_url<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,-) -> Result<String, webidl::WebIdlError> {- webidl::convert::<webidl::UsvString>(scope, value, webidl::Context::argument("Request", 1))- .map(Into::into)-}--pub(crate) fn request_input_snapshot<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,-) -> Result<Option<RequestInputSnapshot>, webidl::WebIdlError> {- request_input_snapshot_inner(scope, value, false)-}-pub(crate) fn mark_request_input_body_used_for_fetch<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,@@ -233,7 +284,7 @@ fn request_input_snapshot_from_private_slots<'s>(})}-pub(super) fn request_body_already_used_error() -> webidl::WebIdlError {+pub(crate) fn request_body_already_used_error() -> webidl::WebIdlError {webidl::WebIdlError::custom_message("Cannot construct a Request with a Request object that has already been used.",)diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rsindex 92e98bf87..98c49ed08 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs@@ -2720,12 +2720,10 @@ async fn request_and_fetch_argument_errors_preserve_exceptions_without_side_effeconst inits = [{method: {toString: throwSentinel}},{headers: {[Symbol.iterator]: throwSentinel}},- ...['method', 'body', 'headers', 'signal'].map(member => new Proxy({}, {- has(target, key) {- if (key === member) throw sentinel;- return Reflect.has(target, key);- },- })),+ {headers: new Proxy({}, {get(target, key) {+ if (key === Symbol.iterator) throw sentinel;+ return Reflect.get(target, key);+ }})},];for (const init of inits) {const input = new Request(url, {method: 'POST', body: 'kept'});@@ -2734,14 +2732,13 @@ async fn request_and_fetch_argument_errors_preserve_exceptions_without_side_effe}check(Object.is(await rejection(fetch({toString: throwSentinel})), sentinel), 'URL conversion exception identity');}- const interfaceName = typeof document === 'undefined' ? 'DedicatedWorkerGlobalScope' : 'Window';const noCorsInterface = typeof document === 'undefined' ? " on 'DedicatedWorkerGlobalScope'" : '';for (const [init, message] of [[{method: 'TRACE'}, 'Request method is forbidden'],[{method: 'GET', body: 'invalid'}, 'Request with GET/HEAD method cannot have body'],[{mode: 'invalid'}, 'RequestInit: mode is not a valid enum value of type RequestMode'],- [{signal: false}, `Failed to execute 'fetch' on '${interfaceName}': signal must be an AbortSignal.`],- [{signal: {}}, `Failed to execute 'fetch' on '${interfaceName}': signal must be an AbortSignal.`],+ [{signal: false}, 'RequestInit: signal can not be converted to AbortSignal'],+ [{signal: {}}, 'RequestInit: signal can not be converted to AbortSignal'],[{mode: 'no-cors', method: 'PATCH'}, `Failed to execute 'fetch'${noCorsInterface}: method \`PATCH\` is unsupported in no-cors mode.`],]) {const input = new Request(url, {method: 'POST', body: 'kept'});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.rsindex c7c3d00ce..034af2ff9 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@@ -51,6 +51,7 @@ mod pointer_lock;mod pointing_event_init;mod popup_hyperlinks;mod promise_rejection;+mod request_init;mod rtc_error;mod security_policy;mod security_policy_event_init;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/request_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/request_init.rsnew file mode 100644index 000000000..c948fc332--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/request_init.rs@@ -0,0 +1,13 @@+use super::*;++#[test]+fn request_and_fetch_share_complete_dictionary_conversion_before_materialization() {+ let mut vm = new_storage_html_test_vm("https://request-init-dictionary.test/");+ let source = format!(+ "globalThis.requestInitResult='pending'; ({}).then(value=>requestInitResult=value,error=>requestInitResult=String(error.stack||error));",+ include_str!("../../../../tests/fixtures/request-init-dictionary.js")+ );+ vm.eval(&source).unwrap();+ vm.eval("0").unwrap();+ assert_eq!(vm.eval("requestInitResult").unwrap(), "true");+}diff --git a/moli-renderer-v8/src/worker/global_scope/fetch.rs b/moli-renderer-v8/src/worker/global_scope/fetch.rsindex ad0c21f9f..b26eca831 100644--- a/moli-renderer-v8/src/worker/global_scope/fetch.rs+++ b/moli-renderer-v8/src/worker/global_scope/fetch.rs@@ -1781,66 +1781,6 @@ pub(in crate::worker) fn make_rejected_promise_with_value<'s>(promise}-pub(in crate::worker) fn validate_worker_fetch_signal<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,-) -> Result<Option<v8::Local<'s, v8::Object>>, webidl::WebIdlError> {- if value.is_null_or_undefined() {- return Ok(None);- }- let Ok(signal) = v8::Local::<v8::Object>::try_from(value) else {- return Err(webidl::WebIdlError::custom_message(- "Failed to execute 'fetch' on 'DedicatedWorkerGlobalScope': signal must be an AbortSignal.",- ));- };- if worker_abort_signal_id(scope, signal).is_none() {- return Err(webidl::WebIdlError::custom_message(- "Failed to execute 'fetch' on 'DedicatedWorkerGlobalScope': signal must be an AbortSignal.",- ));- }- Ok(Some(signal))-}--pub(in crate::worker) fn worker_fetch_signal_option<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,- request_like: Option<v8::Local<'s, v8::Object>>,-) -> Result<Option<v8::Local<'s, v8::Object>>, webidl::WebIdlError> {- let signal_key = v8str(scope, "signal");- if args.length() > 1 {- let init_arg = args.get(1);- if !init_arg.is_null_or_undefined()- && let Ok(init) = v8::Local::<v8::Object>::try_from(init_arg)- && init.has(scope, signal_key.into()).ok_or_else(|| {- webidl::WebIdlError::pending_exception(webidl::Context::member(- "RequestInit",- "signal",- ))- })?- {- let signal = webidl::property_result(- scope,- init,- "signal",- webidl::Context::member("RequestInit", "signal"),- )?- .unwrap_or_else(|| v8::undefined(scope).into());- return validate_worker_fetch_signal(scope, signal);- }- }- if let Some(request_like) = request_like- && let Some(signal) = webidl::property_result(- scope,- request_like,- "signal",- webidl::Context::member("Request", "signal"),- )?- {- return validate_worker_fetch_signal(scope, signal);- }- Ok(None)-}-pub(in crate::worker) struct ResolvedWorkerFetchInput<'s> {resolved_url: Url,method: String,@@ -1864,10 +1804,11 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(webidl::WebIdlError::missing_required(webidl::Context::argument("fetch", 1)).into(),);}- let arg0 = args.get(0);+ let args = webidl::try_parse_args::<crate::network_host::FetchArgs>(scope, args)?;+ let (url, inherited, source) = args.input.materialize(scope)?;let mut request_like = None;let mut consumes_request_body = false;- let inherited = request_input_snapshot(scope, arg0)?;+ let signal;let (url_input,method,@@ -1879,10 +1820,13 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(priority,metadata,) = if let Some(inherited) = inherited {- let req_obj = v8::Local::<v8::Object>::try_from(arg0).expect("request-like object");+ let req_obj = source.expect("request input source");request_like = Some(req_obj);- let url = inherited.url.clone();- let init = parse_fetch_init(scope, args, 1)?;+ let init = parse_fetch_init(scope, args.init)?;+ if inherited.body_unusable && !init.body_present {+ return Err(crate::network_host::request_body_already_used_error().into());+ }+ signal = init.signal.unwrap_or(inherited.signal);consumes_request_body = !init.body_present && inherited.body.is_some();let method = if init.method_present {init.method.clone()@@ -1908,6 +1852,7 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(.or_else(|| moli_fetch::RequestMode::from_str(&inherited.mode).ok()).unwrap_or(moli_fetch::RequestMode::Cors);validate_worker_no_cors_method(request_mode, &method)?;+ crate::network_host::validate_request_method_body(&method, body.as_ref())?;let headers = if request_mode == moli_fetch::RequestMode::NoCors {filter_headers_for_guard(&headers, HeadersGuard::RequestNoCors)} else {@@ -1945,15 +1890,11 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>(metadata,)} else {- let url = webidl::convert::<webidl::UsvString>(- scope,- arg0,- webidl::Context::argument("fetch", 1),- )- .map(String::from)?;- let init = parse_fetch_init(scope, args, 1)?;+ let init = parse_fetch_init(scope, args.init)?;+ signal = init.signal.flatten();let request_mode = init.request_mode.unwrap_or(moli_fetch::RequestMode::Cors);validate_worker_no_cors_method(request_mode, &init.method)?;+ crate::network_host::validate_request_method_body(&init.method, init.body.as_ref())?;let headers = if request_mode == moli_fetch::RequestMode::NoCors {filter_headers_for_guard(&init.headers, HeadersGuard::RequestNoCors)} else {@@ -1984,7 +1925,7 @@ pub(in crate::worker) fn resolve_worker_fetch_input<'s>()};let resolved_url = resolve_context_url(base_url, &url_input, None)?;- let signal = worker_fetch_signal_option(scope, args, request_like)?;+ let signal = signal.as_ref().map(|signal| v8::Local::new(scope, signal));if consumes_request_body && let Some(request_like) = request_like {crate::network_host::mark_request_input_body_used_for_fetch(scope, request_like);}diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rsindex bbd20d35a..83af774e2 100644--- a/moli-renderer-v8/src/worker/global_scope/mod.rs+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs@@ -75,10 +75,9 @@ use crate::network_host::{fetch_browser_subresource_raw_stream_with_preflight_headers_and_network_metadata,fetch_browser_subresource_with_preflight_headers_and_network_metadata,filter_cors_exposed_response_headers, filter_headers_for_guard, is_cors_policy_failure_message,- local_url_response_result, parse_fetch_init, request_input_snapshot,- request_object_credentials_mode, reset_xhr_response_for_request_error, resolve_context_url,- set_xhr_state_bool, set_xhr_state_number, throw_synchronous_xhr_failure,- validate_fetch_response_security_policy,+ local_url_response_result, parse_fetch_init, request_object_credentials_mode,+ reset_xhr_response_for_request_error, resolve_context_url, set_xhr_state_bool,+ set_xhr_state_number, throw_synchronous_xhr_failure, validate_fetch_response_security_policy,validate_fetch_response_security_policy_with_body_classified, xhr_author_request_headers,xhr_dispatch_progress_event, xhr_ensure_send_allowed, xhr_state_bool_property,xhr_state_number_property, xhr_state_string_property,diff --git a/moli-renderer-v8/src/worker/thread/tests/mod.rs b/moli-renderer-v8/src/worker/thread/tests/mod.rsindex 23219eb47..053bc16c1 100644--- a/moli-renderer-v8/src/worker/thread/tests/mod.rs+++ b/moli-renderer-v8/src/worker/thread/tests/mod.rs@@ -2,6 +2,7 @@ mod abort_signal_events;mod callback_execution;mod error_reporting_guard;mod event_target_prototype;+mod request_init;mod text_codecs;use std::pin::pin;use std::sync::Arc;diff --git a/moli-renderer-v8/src/worker/thread/tests/request_init.rs b/moli-renderer-v8/src/worker/thread/tests/request_init.rsnew file mode 100644index 000000000..5032d851a--- /dev/null+++ b/moli-renderer-v8/src/worker/thread/tests/request_init.rs@@ -0,0 +1,16 @@+use super::*;++#[tokio::test]+async fn worker_request_and_fetch_use_the_shared_dictionary_conversion() {+ ensure_v8();+ let source = format!(+ "({}).then(value=>postMessage(value),error=>postMessage(String(error.stack||error)));",+ include_str!("../../../../tests/fixtures/request-init-dictionary.js")+ );+ let mut handle = spawn_worker(source, "https://request-init-worker.test/worker.js".into());+ let message = timeout(TIMEOUT, handle.recv())+ .await+ .expect("worker dictionary conversion must settle")+ .expect("worker must report its result");+ assert_eq!(expect_post_json(message), "true");+}diff --git a/moli-renderer-v8/tests/fixtures/request-init-dictionary.js b/moli-renderer-v8/tests/fixtures/request-init-dictionary.jsnew file mode 100644index 000000000..16ea07b43--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/request-init-dictionary.js@@ -0,0 +1,82 @@+(async () => {+ const assert=(ok,label)=>{if(!ok) throw Error(label);};+ const members=['body','cache','credentials','duplex','headers','integrity','keepalive',+ 'method','mode','priority','redirect','referrer','referrerPolicy','signal'];+ const sentinel={original:true};+ const trace=[];+ const options={method:'POST',body:'value'};+ for(const key of members) Object.defineProperty(options,key,{configurable:true,+ get(){trace.push(key);return key==='method'?'POST':key==='body'?'value':undefined;}});+ new Request('/index.html',options);+ assert(trace.join()===members.join(),'RequestInit complete lexical order: '+trace);+ for(const stop of members) {+ trace.length=0;+ const bad=Object.create(options);+ Object.defineProperty(bad,stop,{get(){trace.push(stop);throw sentinel;}});+ let error;+ try{new Request('/index.html',bad);}catch(caught){error=caught;}+ assert(error===sentinel && trace.join()===members.slice(0,members.indexOf(stop)+1).join(),+ stop+' original exception and short circuit');+ trace.length=0;+ let promise;+ try{promise=fetch('/index.html',bad);}catch(error){throw Error('fetch conversion threw synchronously');}+ error=undefined;try{await promise;}catch(caught){error=caught;}+ assert(error===sentinel && trace.join()===members.slice(0,members.indexOf(stop)+1).join(),+ 'fetch/'+stop+' original rejection and single conversion');+ }+ for(const value of [1,true,'init',Symbol('init'),1n]) {+ let error;+ try{new Request('/index.html',value);}catch(caught){error=caught;}+ assert(error instanceof TypeError,'Request primitive dictionary');+ error=undefined;try{await fetch('/index.html',value);}catch(caught){error=caught;}+ assert(error instanceof TypeError,'fetch primitive dictionary');+ }+ const controller=new AbortController();controller.abort(sentinel);+ let gets=0;+ const hidden=new Proxy({signal:controller.signal},{has(){return false;},get(t,key){+ if(key==='signal') gets++;return Reflect.get(t,key);+ }});+ const request=new Request('/index.html',hidden);+ assert(gets===1 && request.signal!==controller.signal && request.signal.aborted &&+ request.signal.reason===sentinel,'signal uses Get once and preserves aborted state');+ let error;+ const noHas=new Proxy({signal:controller.signal},{has(t,key){+ if(['method','body','headers','signal'].includes(key)) throw sentinel;return Reflect.has(t,key);+ }});+ assert(new Request('/index.html',noHas).signal.aborted,'RequestInit does not use HasProperty');+ error=undefined;try{await fetch('/index.html',noHas);}catch(caught){error=caught;}+ assert(error===sentinel,'fetch ignores HasProperty traps and rejects with the abort reason');+ gets=0;try{await fetch('/index.html',hidden);}catch(caught){error=caught;}+ assert(gets===1 && error===sentinel,'fetch reads the same signal once and rejects with its reason');+ const inherited=new Request(request,{signal:undefined});+ const cleared=new Request(request,{signal:null});+ assert(inherited.signal.aborted && !cleared.signal.aborted,'signal missing/undefined/null distinction');+ let late=0;+ try{new Request('/index.html',{signal:{},get window(){late++;throw sentinel;}});}catch(caught){error=caught;}+ assert(error instanceof TypeError && late===0,'signal brand checked before later fields');+ try{new Request('http://%',{get method(){throw sentinel;}});}catch(caught){error=caught;}+ assert(error===sentinel,'dictionary conversion precedes URL parsing');+ const input=new Request('/index.html',{headers:{'x-snapshot':'before'}});+ const copy=new Request(input,{get signal(){input.headers.set('x-snapshot','after');return null;}});+ assert(copy.headers.get('x-snapshot')==='after','native Request state read after argument conversion');+ const bytes=new Uint8Array([65]);+ const body=new Request('/index.html',{body:bytes,get method(){bytes[0]=66;return 'POST';}});+ assert(await body.text()==='B','body bytes extracted after later getters');+ const params=new URLSearchParams('a=1');+ const form=new Request('/index.html',{body:params,get method(){params.append('b','2');return 'POST';}});+ assert(await form.text()==='a=1&b=2','native BodyInit objects retained until extraction');+ const bodyOrder=[];+ new Request('/index.html',{body:{toString(){bodyOrder.push('string');return 'text';}},+ get cache(){bodyOrder.push('cache');},method:'POST'});+ assert(bodyOrder.join()==='cache,string','BodyInit extraction waits for complete dictionary conversion');+ for(const method of ['GET','HEAD']) for(const body of ['',new Uint8Array()]) {+ let error;+ try{new Request('/index.html',{method,body});}catch(caught){error=caught;}+ assert(error instanceof TypeError,'empty non-null body is still a body');+ }+ const source=new Request('/index.html',{method:'POST',body:'source'});+ try{new Request(source,{get signal(){throw sentinel;}});}catch(caught){error=caught;}+ assert(error===sentinel && !source.bodyUsed && await source.text()==='source',+ 'failed conversion does not consume the input body');+ return true;+})()