Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(xhr): convert send bodies before request state checks

ldm0d63b4e7e5744
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs
index 55f9cf470..7f0aca1ff 100644
--- a/moli-renderer-v8/src/network_host.rs
+++ b/moli-renderer-v8/src/network_host.rs
@@ -180,15 +180,15 @@ pub(crate) use self::xhr::{
XHR_WITH_CREDENTIALS_SLOT, apply_xhr_failure, apply_xhr_response,
apply_xhr_response_body_source, apply_xhr_response_body_source_with_status_text,
apply_xhr_streaming_response_body_source, apply_xhr_streaming_response_chunk,
- apply_xhr_streaming_response_head, apply_xhr_timeout, dispatch_xhr_upload_abort_if_in_progress,
- dispatch_xhr_upload_complete, finalize_xml_http_request_event_target_realm_bindings,
+ apply_xhr_streaming_response_head, apply_xhr_timeout, convert_xhr_send_body_from_args,
+ dispatch_xhr_upload_abort_if_in_progress, dispatch_xhr_upload_complete,
+ finalize_xml_http_request_event_target_realm_bindings,
install_progress_event_template_bindings, install_window_xml_http_request_template_bindings,
install_xml_http_request_bindings, install_xml_http_request_event_target_bindings,
- prepare_xhr_send_body_from_args, progress_event_constructor_callback,
- reset_xhr_response_for_request_error, set_xhr_state_bool, set_xhr_state_number,
- throw_synchronous_xhr_failure, xhr_author_request_headers, xhr_constructor_callback,
- xhr_dispatch_progress_event, xhr_ensure_send_allowed, xhr_state_bool_property,
- xhr_state_number_property, xhr_state_string_property,
+ progress_event_constructor_callback, reset_xhr_response_for_request_error, set_xhr_state_bool,
+ set_xhr_state_number, throw_synchronous_xhr_failure, xhr_author_request_headers,
+ xhr_constructor_callback, xhr_dispatch_progress_event, xhr_ensure_send_allowed,
+ xhr_state_bool_property, xhr_state_number_property, xhr_state_string_property,
};
pub(in crate::network_host) const NETWORK_BODY_SLOT: &str = "__lmBody";
pub(in crate::network_host) const NETWORK_BODY_BYTES_SLOT: &str = "__lmBodyBytes";
diff --git a/moli-renderer-v8/src/network_host/xhr.rs b/moli-renderer-v8/src/network_host/xhr.rs
index f40b48c86..59cf9a473 100644
--- a/moli-renderer-v8/src/network_host/xhr.rs
+++ b/moli-renderer-v8/src/network_host/xhr.rs
@@ -76,8 +76,8 @@ use self::response_type::XmlHttpRequestResponseType;
#[cfg(test)]
pub(crate) use self::send::prepare_xhr_send_body;
pub(crate) use self::send::{
- PreparedXhrSendBody, dispatch_xhr_upload_abort_if_in_progress, dispatch_xhr_upload_complete,
- prepare_xhr_send_body_from_args, xhr_author_request_headers,
+ PreparedXhrSendBody, convert_xhr_send_body_from_args, dispatch_xhr_upload_abort_if_in_progress,
+ dispatch_xhr_upload_complete, xhr_author_request_headers,
};
pub(crate) fn install_progress_event_template_bindings<'s>(
diff --git a/moli-renderer-v8/src/network_host/xhr/bindings/prototype.rs b/moli-renderer-v8/src/network_host/xhr/bindings/prototype.rs
index 3178290a9..e89f85c01 100644
--- a/moli-renderer-v8/src/network_host/xhr/bindings/prototype.rs
+++ b/moli-renderer-v8/src/network_host/xhr/bindings/prototype.rs
@@ -10,7 +10,7 @@ struct XmlHttpRequestTemplateMethodsDeclaration {
#[webapi(method = "open", length = 2, callback = xhr_open_callback)]
open: (),
- #[webapi(method = "send", length = 0, callback = xhr_send_callback)]
+ #[webapi(method = "send", length = 0, callback = xhr_send_callback, receiver = web_api_interfaces::XMLHttpRequest::is_instance)]
send: (),
#[webapi(method = "abort", length = 0, callback = xhr_abort_callback)]
diff --git a/moli-renderer-v8/src/network_host/xhr/send.rs b/moli-renderer-v8/src/network_host/xhr/send.rs
index 1189b64b9..afbfbf43a 100644
--- a/moli-renderer-v8/src/network_host/xhr/send.rs
+++ b/moli-renderer-v8/src/network_host/xhr/send.rs
@@ -10,7 +10,7 @@ use self::paths::{
#[cfg(test)]
pub(crate) use self::request::prepare_xhr_send_body;
pub(crate) use self::request::{
- PreparedXhrSendBody, prepare_xhr_send_body_from_args, xhr_author_request_headers,
+ PreparedXhrSendBody, convert_xhr_send_body_from_args, xhr_author_request_headers,
};
use self::request::{
PreparedXhrSendRequest, XhrSendPrepareError, prepare_xhr_send_request,
@@ -39,9 +39,7 @@ pub(super) fn xhr_send_callback<'s>(
}
let xhr = args.this();
- let method =
- xhr_state_string_property(scope, xhr, XHR_METHOD_SLOT).unwrap_or_else(|| "GET".to_owned());
- let prepared_body = match prepare_xhr_send_body_from_args(scope, &args, &method) {
+ let body = match convert_xhr_send_body_from_args(scope, &args) {
Ok(body) => body,
Err(error) => {
crate::webidl::throw_error(scope, &error);
@@ -60,7 +58,16 @@ pub(super) fn xhr_send_callback<'s>(
return;
}
+ let method =
+ xhr_state_string_property(scope, xhr, XHR_METHOD_SLOT).unwrap_or_else(|| "GET".to_owned());
let async_request = xhr_is_async(scope, xhr);
+ let prepared_body = match body.prepare(scope, &method) {
+ Ok(body) => body,
+ Err(error) => {
+ crate::webidl::throw_error(scope, &error);
+ return;
+ }
+ };
cancel_xhr_timeout(scope, xhr);
set_xhr_state_bool(scope, xhr, XHR_SEND_FLAG_SLOT, true);
diff --git a/moli-renderer-v8/src/network_host/xhr/send/request.rs b/moli-renderer-v8/src/network_host/xhr/send/request.rs
index dc95803d1..68fc7348e 100644
--- a/moli-renderer-v8/src/network_host/xhr/send/request.rs
+++ b/moli-renderer-v8/src/network_host/xhr/send/request.rs
@@ -112,6 +112,31 @@ pub(crate) struct PreparedXhrSendBody {
pub(crate) default_content_type: Option<String>,
}
+pub(crate) enum ConvertedXhrSendBody<'s> {
+ Native(v8::Local<'s, v8::Value>),
+ Text(String),
+}
+
+impl<'s> ConvertedXhrSendBody<'s> {
+ pub(crate) fn prepare(
+ self,
+ scope: &mut v8::PinScope<'s, '_>,
+ method: &str,
+ ) -> Result<PreparedXhrSendBody, crate::webidl::WebIdlError> {
+ // Conversion precedes state checks, but GET/HEAD never extract body bytes.
+ if matches!(method, "GET" | "HEAD") {
+ return Ok(PreparedXhrSendBody::empty());
+ }
+ match self {
+ Self::Native(value) => prepare_xhr_send_body(scope, value),
+ Self::Text(text) => Ok(PreparedXhrSendBody::new(
+ text.into_bytes(),
+ Some(TEXT_CONTENT_TYPE.to_owned()),
+ )),
+ }
+ }
+}
+
impl PreparedXhrSendBody {
pub(crate) fn empty() -> Self {
Self {
@@ -156,6 +181,8 @@ pub(crate) fn prepare_xhr_send_body<'s>(
}
}
+ validate_xhr_buffer_source(value)?;
+
if let Some(bytes) = blob::buffer_source_bytes_from_value(scope, value) {
return Ok(PreparedXhrSendBody::new(bytes, None));
}
@@ -171,19 +198,42 @@ pub(crate) fn prepare_xhr_send_body<'s>(
))
}
-pub(crate) fn prepare_xhr_send_body_from_args<'s>(
+pub(crate) fn convert_xhr_send_body_from_args<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
- method: &str,
-) -> Result<PreparedXhrSendBody, crate::webidl::WebIdlError> {
+) -> Result<ConvertedXhrSendBody<'s>, crate::webidl::WebIdlError> {
let parsed = crate::webidl::try_parse_args::<XhrSendArgs<'s>>(scope, args)?;
- let Some(body) = parsed.body else {
- return Ok(PreparedXhrSendBody::empty());
- };
- if matches!(method, "GET" | "HEAD") {
- return Ok(PreparedXhrSendBody::empty());
+ let body = parsed.body.unwrap_or_else(|| v8::null(scope).into());
+ validate_xhr_buffer_source(body)?;
+ if body.is_null_or_undefined() || body.is_array_buffer() || body.is_array_buffer_view() {
+ return Ok(ConvertedXhrSendBody::Native(body));
+ }
+ if let Ok(object) = v8::Local::<v8::Object>::try_from(body)
+ && (web_api_interfaces::Blob::is_instance(scope, object)
+ || web_api_interfaces::FormData::is_instance(scope, object)
+ || web_api_interfaces::URLSearchParams::is_instance(scope, object))
+ {
+ return Ok(ConvertedXhrSendBody::Native(body));
+ }
+ let text = crate::webidl::convert::<crate::webidl::UsvString>(
+ scope,
+ body,
+ crate::webidl::Context::argument("XMLHttpRequest.send", 1),
+ )?;
+ Ok(ConvertedXhrSendBody::Text(text.0))
+}
+
+fn validate_xhr_buffer_source(
+ value: v8::Local<'_, v8::Value>,
+) -> Result<(), crate::webidl::WebIdlError> {
+ if value.is_shared_array_buffer()
+ || blob::buffer_source_has_shared_or_resizable_backing_store(value)
+ {
+ return Err(crate::webidl::WebIdlError::custom_message(
+ "XMLHttpRequest.send does not accept shared or resizable BufferSource backing stores",
+ ));
}
- prepare_xhr_send_body(scope, body)
+ Ok(())
}
fn xhr_request_headers(
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
index 888a5b0f6..224daa0ee 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/mod.rs
@@ -6,6 +6,7 @@ mod dom;
mod forms;
mod misc;
mod response_headers;
+mod send_body;
mod shadow_dom;
mod style_invalidation;
mod xhr;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/send_body.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/send_body.rs
new file mode 100644
index 000000000..cc567ab62
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/send_body.rs
@@ -0,0 +1,160 @@
+use super::*;
+
+const BODY_CONVERSION_PROBE: &str =
+ include_str!("../../../../tests/fixtures/xhr-send-body-conversion.js");
+
+fn assert_body_conversion_result(observed: &str) {
+ let result: serde_json::Value = serde_json::from_str(observed).expect("body conversion result");
+ let checks = result["checks"].as_array().expect("body conversion checks");
+ let failures: Vec<_> = checks
+ .iter()
+ .filter(|check| check["pass"] != true)
+ .collect();
+ assert!(
+ failures.is_empty(),
+ "body conversion failures: {failures:#?}"
+ );
+ assert_eq!(checks.len(), 1451);
+ assert_eq!(result["state"], "pass");
+}
+
+#[test]
+fn window_xhr_send_body_validates_buffers_before_state_and_method() {
+ let mut vm = new_storage_test_vm("https://xhr-body-conversion.test/");
+ let observed = vm
+ .eval(&format!(
+ "{BODY_CONVERSION_PROBE}\nJSON.stringify(xhrSendBodyConversionProbe())"
+ ))
+ .expect("Window body conversion probe");
+ assert_body_conversion_result(&observed);
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn worker_xhr_send_body_validates_buffers_before_state_and_method() {
+ let loader = static_http_loader(std::iter::empty::<String>());
+ let mut vm =
+ new_page_task_executor_test_vm_with_loader("https://xhr-body-conversion.test/", &loader);
+ let worker = format!(
+ "{BODY_CONVERSION_PROBE}\ntry {{ postMessage(JSON.stringify(xhrSendBodyConversionProbe())); }} catch (error) {{ postMessage(JSON.stringify({{error: String(error.stack || error)}})); }} close();"
+ );
+ vm.eval(&format!(
+ r#"
+ globalThis.bodyConversionResult = null;
+ const worker = new Worker(URL.createObjectURL(new Blob([{}], {{type: 'text/javascript'}})));
+ worker.onmessage = event => {{ bodyConversionResult = event.data; }};
+ worker.onerror = event => {{ bodyConversionResult = JSON.stringify({{error: event.message}}); event.preventDefault(); }};
+ "#,
+ serde_json::to_string(&worker).unwrap()
+ ))
+ .expect("start Worker body conversion probe");
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "bodyConversionResult !== null",
+ "true",
+ "Worker body conversion probe",
+ )
+ .await;
+ let observed = vm
+ .eval("bodyConversionResult")
+ .expect("Worker conversion result");
+ assert_body_conversion_result(&observed);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn xhr_send_body_reentrant_conversion_controls_request() {
+ for worker in [false, true] {
+ let server = StaticHttpServer::spawn_with_bodies(vec!["ok".to_owned(); 6]).await;
+ let base = server.base_url();
+ let loader = static_http_loader(std::iter::empty::<String>());
+ let mut vm = new_page_task_executor_test_vm_with_loader(base.as_str(), &loader);
+ let probe = r#"
+ (async () => {
+ const cases = [
+ {initial: 'POST', method: 'GET'},
+ {initial: 'GET', method: 'POST'},
+ {initial: 'POST', method: 'HEAD', sync: true},
+ {initial: null, method: 'POST'},
+ {initial: 'POST', method: 'POST', sync: true},
+ {initial: 'POST', method: 'POST', nested: true},
+ ];
+ for (const [index, c] of cases.entries()) {
+ const xhr = new XMLHttpRequest();
+ const url = BASE + 'echo?case=' + index;
+ let returned = false, early = false, conversions = 0;
+ const done = new Promise(resolve => xhr.onloadend = () => {
+ early = !returned; resolve();
+ });
+ if (c.initial) xhr.open(c.initial, url, true);
+ let caught;
+ try {
+ xhr.send({toString() {
+ conversions++;
+ if (c.nested) xhr.send('inner');
+ else xhr.open(c.method, url, !c.sync);
+ return 'payload';
+ }});
+ } catch (error) { caught = error; }
+ returned = true;
+ if ((caught && caught.name || null) !== (c.nested ? 'InvalidStateError' : null))
+ throw new Error('send exception: ' + index + ': ' + caught);
+ await done;
+ if (conversions !== 1 || xhr.status !== 200 || early !== !!c.sync)
+ throw new Error('conversion or completion order: ' + index);
+ }
+ return 'pass';
+ })()
+ "#
+ .replace("BASE", &serde_json::to_string(base.as_str()).unwrap());
+ let source = if worker {
+ let worker_source = format!(
+ "{probe}.then(value => {{postMessage(value); close();}}, error => {{postMessage(String(error.stack || error)); close();}});"
+ );
+ format!(
+ r#"
+ globalThis.sendReentryResult = 'pending';
+ const worker = new Worker(URL.createObjectURL(new Blob([{}], {{type: 'text/javascript'}})));
+ worker.onmessage = event => {{ sendReentryResult = event.data; }};
+ worker.onerror = event => {{ sendReentryResult = event.message; event.preventDefault(); }};
+ "#,
+ serde_json::to_string(&worker_source).unwrap()
+ )
+ } else {
+ format!(
+ "globalThis.sendReentryResult = 'pending'; {probe}.then(value => {{sendReentryResult = value;}}, error => {{sendReentryResult = String(error.stack || error);}});"
+ )
+ };
+ vm.eval(&source).expect("start reentrant send probe");
+ advance_page_task_executor_until_eval_equals(
+ &mut vm,
+ &loader,
+ "sendReentryResult !== 'pending'",
+ "true",
+ "reentrant send probe",
+ )
+ .await;
+ assert_eq!(vm.eval("sendReentryResult").unwrap(), "pass");
+ let requests = server.finish().await;
+ assert_eq!(requests.len(), 6);
+ for (index, (request, (method, length))) in requests
+ .iter()
+ .zip([
+ ("GET", None),
+ ("POST", Some("7")),
+ ("HEAD", None),
+ ("POST", Some("7")),
+ ("POST", Some("7")),
+ ("POST", Some("5")),
+ ])
+ .enumerate()
+ {
+ assert_eq!(request.target, format!("/echo?case={index}"));
+ assert_eq!(request.method, method);
+ assert_eq!(request.header_value("content-length"), length);
+ assert_eq!(
+ request.header_value("content-type"),
+ length.map(|_| "text/plain;charset=UTF-8")
+ );
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
index 7de54b9fd..8e65f8e62 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/xhr.rs
@@ -1043,13 +1043,13 @@ fn xml_http_request_send_callback_parses_webidl_body_argument() {
const get = new XMLHttpRequest();
get.open('GET', '/ignored-body');
- const ignoredGetBody = probe(() => get.send(Symbol('ignored')));
+ const getSymbolBody = probe(() => get.send(Symbol('ignored')));
const lowercaseGet = new XMLHttpRequest();
lowercaseGet.open('get', '/ignored-lower-body');
- const ignoredLowercaseGetBody = probe(() => lowercaseGet.send(Symbol('ignored')));
+ const lowercaseGetSymbolBody = probe(() => lowercaseGet.send(Symbol('ignored')));
- return [symbol, throwing, ignoredGetBody, ignoredLowercaseGetBody].join('|');
+ return [symbol, throwing, getSymbolBody, lowercaseGetSymbolBody].join('|');
})()
"#,
)
@@ -1057,7 +1057,7 @@ fn xml_http_request_send_callback_parses_webidl_body_argument() {
assert_eq!(
result,
- "throw:TypeError|throw:RangeError|undefined|undefined"
+ "throw:TypeError|throw:RangeError|throw:TypeError|throw:TypeError"
);
}
#[test]
diff --git a/moli-renderer-v8/src/worker/global_scope/mod.rs b/moli-renderer-v8/src/worker/global_scope/mod.rs
index 8ea6ed283..baeaf93ab 100644
--- a/moli-renderer-v8/src/worker/global_scope/mod.rs
+++ b/moli-renderer-v8/src/worker/global_scope/mod.rs
@@ -77,15 +77,16 @@ use crate::network_host::{
build_fetch_response_object_from_body_source_for_request_mode,
build_fetch_response_object_from_stream_for_request_mode,
build_fetch_response_object_from_subresource_body_for_request_mode,
- close_pending_network_body_stream, dispatch_xhr_upload_abort_if_in_progress,
- dispatch_xhr_upload_complete, enqueue_pending_network_body_chunk,
- error_pending_network_body_stream_with_reason, extract_subresource_auth_challenge,
+ close_pending_network_body_stream, convert_xhr_send_body_from_args,
+ dispatch_xhr_upload_abort_if_in_progress, dispatch_xhr_upload_complete,
+ enqueue_pending_network_body_chunk, error_pending_network_body_stream_with_reason,
+ extract_subresource_auth_challenge,
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, prepare_xhr_send_body_from_args,
- 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,
+ 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,
validate_fetch_response_security_policy_with_body_classified, xhr_author_request_headers,
xhr_dispatch_progress_event, xhr_ensure_send_allowed, xhr_state_bool_property,
diff --git a/moli-renderer-v8/src/worker/global_scope/xhr.rs b/moli-renderer-v8/src/worker/global_scope/xhr.rs
index 2c46b8651..eb5f7b199 100644
--- a/moli-renderer-v8/src/worker/global_scope/xhr.rs
+++ b/moli-renderer-v8/src/worker/global_scope/xhr.rs
@@ -245,15 +245,22 @@ pub(crate) fn try_worker_xhr_send_callback<'s>(
};
let xhr = args.this();
+ let body = match convert_xhr_send_body_from_args(scope, args) {
+ Ok(body) => body,
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return true;
+ }
+ };
+
if !xhr_ensure_send_allowed(scope, xhr) {
return true;
}
let async_request = xhr_state_bool_property(scope, xhr, XHR_ASYNC_SLOT).unwrap_or(true);
-
let method =
xhr_state_string_property(scope, xhr, XHR_METHOD_SLOT).unwrap_or_else(|| "GET".to_owned());
- let prepared_body = match prepare_xhr_send_body_from_args(scope, args, &method) {
+ let prepared_body = match body.prepare(scope, &method) {
Ok(body) => body,
Err(error) => {
webidl::throw_error(scope, &error);
diff --git a/moli-renderer-v8/tests/fixtures/xhr-send-body-conversion.js b/moli-renderer-v8/tests/fixtures/xhr-send-body-conversion.js
new file mode 100644
index 000000000..13dbd1652
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/xhr-send-body-conversion.js
@@ -0,0 +1,107 @@
+function xhrSendBodyConversionProbe() {
+ const checks = [];
+ const check = (label, actual, wanted) => checks.push({label, actual, wanted,
+ pass: JSON.stringify(actual) === JSON.stringify(wanted)});
+ const views = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
+ Int32Array, Uint32Array, BigInt64Array, BigUint64Array, Float16Array,
+ Float32Array, Float64Array, DataView];
+ const Shared = new WebAssembly.Memory({shared: true, initial: 1, maximum: 1}).buffer.constructor;
+ const factories = [];
+ for (const [kind, make] of [
+ ['shared', () => new Shared(32)],
+ ['growable', () => new Shared(32, {maxByteLength: 64})],
+ ['resizable', () => new ArrayBuffer(32, {maxByteLength: 64})],
+ ]) {
+ factories.push([kind + '/buffer', make]);
+ for (const View of views)
+ factories.push([kind + '/' + View.name, () => new View(make(), 8,
+ View === DataView ? 8 : 8 / View.BYTES_PER_ELEMENT)]);
+ }
+ factories.push(['empty-shared', () => new Shared(0)],
+ ['empty-resizable', () => new ArrayBuffer(0, {maxByteLength: 16})],
+ ['out-of-bounds', () => { const b = new ArrayBuffer(16, {maxByteLength: 32});
+ const view = new Uint8Array(b, 8, 8); b.resize(0); return view; }],
+ ['symbol', () => Symbol('body')], ['throwing-string', () => ({})]);
+ let nextUrlId = 0;
+ const nextDataUrl = () => 'data:text/plain,complete-' + nextUrlId++;
+ for (const phase of ['unsent', 'GET', 'HEAD', 'POST', 'pending', 'done']) {
+ for (const [kind, create] of factories) {
+ const label = phase + '/' + kind;
+ const xhr = new XMLHttpRequest();
+ if (phase === 'pending') { xhr.open('POST', nextDataUrl()); xhr.send(); }
+ else if (phase === 'done') { xhr.open('GET', nextDataUrl(), false); xhr.send(); }
+ else if (phase !== 'unsent') xhr.open(phase, nextDataUrl());
+ const before = [xhr.readyState, xhr.status, xhr.responseText];
+ let events = 0;
+ for (const type of ['readystatechange', 'loadstart', 'progress', 'load', 'error', 'loadend'])
+ xhr.addEventListener(type, () => events++);
+ let coerced = 0;
+ const marker = new RangeError('body coercion');
+ const body = create();
+ if (typeof body === 'object') {
+ Object.defineProperty(body, Symbol.toPrimitive, {value() {
+ coerced++;
+ if (kind === 'throwing-string') throw marker;
+ return 'unexpected fallback';
+ }});
+ if (ArrayBuffer.isView(body)) {
+ for (const property of ['buffer', 'byteOffset', 'byteLength'])
+ Object.defineProperty(body, property, {get() { throw marker; }});
+ }
+ }
+ let caught;
+ try { xhr.send(body); } catch (error) { caught = error; }
+ check(label + '/error', caught && caught.name || null,
+ kind === 'throwing-string' ? 'RangeError' : 'TypeError');
+ check(label + '/identity', kind === 'throwing-string' ? caught === marker : caught instanceof TypeError, true);
+ check(label + '/coercion', coerced, kind === 'throwing-string' ? 1 : 0);
+ check(label + '/state', [xhr.readyState, xhr.status, xhr.responseText], before);
+ check(label + '/events', events, 0);
+ xhr.abort();
+ }
+ }
+ for (const phase of ['unsent', 'GET', 'HEAD', 'POST', 'pending', 'done']) {
+ const xhr = new XMLHttpRequest();
+ if (phase === 'pending') { xhr.open('POST', nextDataUrl()); xhr.send(); }
+ else if (phase === 'done') { xhr.open('GET', nextDataUrl(), false); xhr.send(); }
+ else if (phase !== 'unsent') xhr.open(phase, nextDataUrl());
+ let calls = 0, error = null;
+ try { xhr.send({toString() { calls++; return 'converted'; }}); }
+ catch (caught) { error = caught.name; }
+ check(phase + '/ordinary/coercion', calls, 1);
+ check(phase + '/ordinary/error', error,
+ ['unsent', 'pending', 'done'].includes(phase) ? 'InvalidStateError' : null);
+ xhr.abort();
+ }
+ const revoked = Proxy.revocable(new XMLHttpRequest(), {}); revoked.revoke();
+ for (const [index, receiver] of [null, {}, XMLHttpRequest.prototype,
+ Object.create(XMLHttpRequest.prototype), Object.create(new XMLHttpRequest()),
+ new Proxy(new XMLHttpRequest(), {}), revoked.proxy].entries()) {
+ let calls = 0, caught;
+ try { XMLHttpRequest.prototype.send.call(receiver, {toString() { calls++; return 'converted'; }}); }
+ catch (error) { caught = error; }
+ check('receiver/' + index + '/error', caught instanceof TypeError, true);
+ check('receiver/' + index + '/coercion', calls, 0);
+ }
+ for (const kind of ['fixed', 'detached']) {
+ const buffer = new ArrayBuffer(8);
+ const view = new Uint8Array(buffer, 2, 4);
+ const dataView = new DataView(buffer, 2, 4);
+ if (kind === 'detached') buffer.transfer();
+ for (const [index, body] of [buffer, view, dataView].entries()) {
+ const xhr = new XMLHttpRequest(); xhr.open('POST', nextDataUrl(), false);
+ let error = null; try { xhr.send(body); } catch (caught) { error = caught.name; }
+ check(kind + '/' + index + '/error', error, null);
+ check(kind + '/' + index + '/status', xhr.status, 200);
+ }
+ }
+ const retry = new XMLHttpRequest(); retry.open('POST', nextDataUrl(), false);
+ let rejected = false;
+ try { retry.send(new Uint8Array(new Shared(8))); } catch (error) { rejected = error instanceof TypeError; }
+ check('retry/rejected', rejected, true);
+ let retryError = null;
+ try { retry.send(new Uint8Array([65])); } catch (error) { retryError = error.name; }
+ check('retry/error', retryError, null);
+ check('retry/status', retry.status, 200);
+ return {state: checks.every(check => check.pass) ? 'pass' : 'fail', checks};
+}