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(dom): make native document content type authoritative
ldm0594cb9041c03
diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rsindex 89b173931..7b467a714 100644--- a/moli-renderer-v8/src/native_bridge/document.rs+++ b/moli-renderer-v8/src/native_bridge/document.rs@@ -208,7 +208,7 @@ pub(in crate::native_bridge) use detached_objects::{pub(in crate::native_bridge) use detached_objects::{detached_shadow_root_active_element_value, detached_shadow_root_selection_value,};-pub(in crate::native_bridge::document) use detached_surface::detached_document_content_type_value;+pub(in crate::native_bridge::document) use detached_surface::set_detached_document_content_type;pub(super) use detached_surface::{bridge_adopt_node_into_document_callback, bridge_clone_node_into_document_callback,bridge_create_cdata_section_not_supported_callback, bridge_create_detached_comment_callback,@@ -839,63 +839,6 @@ fn document_ready_state_getter_function<'s>(set_document_string_return_value(scope, &mut rv, &ready_state);}-fn document_content_type_for_receiver<'s>(- scope: &mut v8::PinScope<'s, '_>,- receiver: v8::Local<'s, v8::Object>,- runtime: &JsContextHost,- handle: DomHandle,-) -> String {- if let Some(content_type) =- detached_state_string(scope, receiver, "contentType").filter(|value| !value.is_empty())- {- return content_type;- }- let Some(document) = runtime.dom_host().node(handle).and_then(Node::as_document) else {- return runtime- .dom_host()- .document_content_type_for_handle(handle)- .map(ToOwned::to_owned)- .unwrap_or_else(|| "application/xml".to_owned());- };- if document.is_html_document() {- let content_type = document.content_type();- return if content_type.is_empty() {- "text/html".to_owned()- } else {- content_type.to_owned()- };- }- if let Some(creation_namespace) = detached_state_string(scope, receiver, "creationNamespace")- .filter(|value| !value.is_empty())- {- if creation_namespace == XHTML_NS {- return "application/xhtml+xml".to_owned();- }- if creation_namespace == SVG_NS {- return "image/svg+xml".to_owned();- }- }- if let Some(content_type) = runtime.dom_host().document_content_type_for_handle(handle) {- return content_type.to_owned();- }- let root_namespace = document- .document_element_handle(runtime.dom_host().dom(), handle)- .and_then(|root| runtime.dom_host().node(root))- .and_then(Node::as_element)- .map(|element| element.namespace().to_owned());- if root_namespace.as_deref() == Some(XHTML_NS) {- "application/xhtml+xml".to_owned()- } else if root_namespace.as_deref() == Some(SVG_NS) {- "image/svg+xml".to_owned()- } else {- runtime- .dom_host()- .document_content_type_for_handle(handle)- .map(ToOwned::to_owned)- .unwrap_or_else(|| "application/xml".to_owned())- }-}-fn document_content_type_getter_function<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -907,8 +850,11 @@ fn document_content_type_getter_function<'s>(return;};let runtime = unsafe { &*runtime_ptr };- let content_type = document_content_type_for_receiver(scope, receiver, runtime, handle);- set_document_string_return_value(scope, &mut rv, &content_type);+ let Some(content_type) = runtime.dom_host().document_content_type_for_handle(handle) else {+ rv.set_undefined();+ return;+ };+ set_document_string_return_value(scope, &mut rv, content_type);}fn document_character_set_getter_function<'s>(diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rsindex 24efac9d6..a52958314 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs@@ -93,6 +93,7 @@ fn set_detached_document_url_state<'s>(fn new_detached_document_shell<'s>(scope: &mut v8::PinScope<'s, '_>,kind: &str,+ content_type: &str,url: Url,) -> Option<v8::Local<'s, v8::Object>> {let to_string_tag = if kind == "html" {@@ -116,9 +117,9 @@ fn new_detached_document_shell<'s>();set_detached_document_url_state(scope, state, &url)?;define_detached_state(scope, document, state);- if let Some(handle) = create_native_detached_document_handle_with_url(scope, kind, url) {- define_detached_native_handle(scope, document, handle);- }+ let handle = create_native_detached_document_handle_with_url(scope, kind, url)?;+ define_detached_native_handle(scope, document, handle);+ set_detached_document_content_type(scope, document, content_type)?;install_detached_document_instance_properties(scope, document, kind);let _ = ensure_detached_document_implementation(scope, document);Some(document)@@ -200,22 +201,16 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>character_set: Option<&str>,) -> Option<v8::Local<'s, v8::Object>> {let url = detached_document_url(&parsed);- let document = new_detached_document_shell(scope, kind, url)?;- if let Some(state) = detached_state_object(scope, document) {- if let Some(content_type) = content_type {- let _ = state.set(- scope,- v8str(scope, "contentType").into(),- v8_string(scope, content_type)?.into(),- );- }- if let Some(character_set) = character_set {- let _ = state.set(- scope,- v8str(scope, "characterSet").into(),- v8_string(scope, character_set)?.into(),- );- }+ let content_type = content_type.unwrap_or(parsed.dom().document()?.content_type());+ let document = new_detached_document_shell(scope, kind, content_type, url)?;+ if let Some(state) = detached_state_object(scope, document)+ && let Some(character_set) = character_set+ {+ let _ = state.set(+ scope,+ v8str(scope, "characterSet").into(),+ v8_string(scope, character_set)?.into(),+ );}import_detached_document_children_from_host(scope, document, &parsed)?;Some(document)@@ -309,6 +304,7 @@ pub(in crate::native_bridge::document) fn build_detached_html_document_object<'slet document = new_detached_document_shell(scope,"html",+ "text/html",Url::parse("about:blank").expect("static about:blank parses"),)?;populate_native_html_document_shell(scope, document, title)?;@@ -325,22 +321,17 @@ pub(in crate::native_bridge::document) fn build_detached_document_object<'s>(if kind == "html" {return build_detached_html_document_object(scope, None);}+ let content_type = match namespace_uri.as_deref() {+ Some(XHTML_NS) => "application/xhtml+xml",+ Some(SVG_NS) => "image/svg+xml",+ _ => "application/xml",+ };let document = new_detached_document_shell(scope,kind,+ content_type,Url::parse("about:blank").expect("static about:blank parses"),)?;- if kind == "xml"- && let Some(namespace_uri) = namespace_uri.as_deref()- && let Some(state) = detached_state_object(scope, document)- {- let _ = state.set(- scope,- v8str(scope, "creationNamespace").into(),- v8_string(scope, namespace_uri)?.into(),- );- }-if let Some(doctype) = doctype {let doctype = if detached_is_node(scope, doctype) {doctypediff --git a/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/clone_adopt.rs b/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/clone_adopt.rsindex ec1ef2b78..063b8b1ad 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/clone_adopt.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/clone_adopt.rs@@ -37,7 +37,7 @@ fn detached_document_root_local_name<'s>(scope: &mut v8::PinScope<'s, '_>,document: v8::Local<'s, v8::Object>,) -> Option<String> {- let root = object_property_as_object(scope, document, "documentElement")?;+ let root = detached_document_element_object(scope, document)?;detached_native_element_local_name(scope, root).or_else(|| object_string_property(scope, root, "localName"))}@@ -64,6 +64,8 @@ fn clone_detached_document_shell<'s>(};let cloned = call_global_bridge_method(scope, helper, &[]).and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;+ let content_type = detached_document_content_type_value(scope, document)?;+ set_detached_document_content_type(scope, cloned, &content_type)?;if html_shell {for child in detached_child_node_objects(scope, cloned) {detached_detach_from_parent(scope, child);diff --git a/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/document_methods.rs b/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/document_methods.rsindex 8a4799ad2..53c1508a4 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/document_methods.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_surface/creation/document_methods.rs@@ -231,10 +231,8 @@ pub(in crate::native_bridge) fn bridge_detached_create_element_callback<'s>(if namespace_uri.is_none()&& validation != Some("qualified")&& document_kind == "xml"- && detached_document_element_object(scope, document)- .and_then(|root| detached_element_namespace_uri(scope, root))- .as_deref()- == Some(XHTML_NS)+ && detached_document_content_type_value(scope, document).as_deref()+ == Some("application/xhtml+xml"){namespace_uri = Some(XHTML_NS.to_owned());}diff --git a/moli-renderer-v8/src/native_bridge/document/detached_surface/document_state.rs b/moli-renderer-v8/src/native_bridge/document/detached_surface/document_state.rsindex a265cb3cf..7b02b5d1b 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_surface/document_state.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_surface/document_state.rs@@ -220,37 +220,36 @@ pub(in crate::native_bridge) fn bridge_detached_document_content_type_callback<'rv.set_empty_string();return;};- let content_type = detached_document_content_type_value(scope, document);+ let Some(content_type) = detached_document_content_type_value(scope, document) else {+ rv.set_empty_string();+ return;+ };set_string_return_value(scope, &mut rv, &content_type);}pub(in crate::native_bridge::document) fn detached_document_content_type_value<'a>(scope: &mut v8::PinScope<'a, '_>,document: v8::Local<'a, v8::Object>,-) -> String {- let explicit_content_type = detached_document_state_string(scope, document, "contentType", "");- if !explicit_content_type.is_empty() {- return explicit_content_type;- }+) -> Option<String> {+ let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;+ let handle = detached_native_handle_for_runtime(scope, runtime_ptr, document)?;+ unsafe { &*runtime_ptr }+ .dom_host()+ .document_content_type_for_handle(handle)+ .map(str::to_owned)+}- let document_kind = detached_document_state_string(scope, document, "documentKind", "xml");- let root_namespace = detached_document_element_object(scope, document)- .and_then(|root| detached_element_namespace_uri(scope, root))- .or_else(|| {- let namespace =- detached_document_state_string(scope, document, "creationNamespace", "");- (!namespace.is_empty()).then_some(namespace)- });- if document_kind.eq_ignore_ascii_case("html") {- "text/html"- } else if root_namespace.as_deref() == Some(XHTML_NS) {- "application/xhtml+xml"- } else if root_namespace.as_deref() == Some(SVG_NS) {- "image/svg+xml"- } else {- "application/xml"- }- .to_owned()+pub(in crate::native_bridge::document) fn set_detached_document_content_type<'a>(+ scope: &mut v8::PinScope<'a, '_>,+ document: v8::Local<'a, v8::Object>,+ content_type: &str,+) -> Option<()> {+ let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;+ let handle = detached_native_handle_for_runtime(scope, runtime_ptr, document)?;+ let dom_host = unsafe { &mut *runtime_ptr }.dom_host_mut();+ dom_host.document_content_type_for_handle(handle)?;+ dom_host.set_document_content_type_for_handle(handle, content_type);+ Some(())}pub(in crate::native_bridge) fn bridge_detached_document_character_set_callback<'a>(diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rsindex a69d83ef1..90c206d0c 100644--- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs+++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs@@ -4,8 +4,7 @@ use super::super::node::{remove_child_in_reaction_scope,};use super::{- JsContextHost, detached_document_content_type_value, detached_native_handle_for_runtime,- is_html_document, throw_dom_exception,+ JsContextHost, detached_native_handle_for_runtime, is_html_document, throw_dom_exception,};use crate::native_bridge::element::{contenteditable_editing_host, dispatch_text_control_event, is_text_control,@@ -415,9 +414,7 @@ fn editing_command_document<'s>(|| runtime.dom_host().document_content_type_for_handle(document_handle)- .is_some_and(|content_type| content_type.eq_ignore_ascii_case("application/xhtml+xml"))- || detached_document_content_type_value(scope, args.this())- .eq_ignore_ascii_case("application/xhtml+xml");+ .is_some_and(|content_type| content_type.eq_ignore_ascii_case("application/xhtml+xml"));if !supports_editing_commands {throw_dom_exception(scope, "InvalidStateError", 11, non_html_message);return None;diff --git a/moli-renderer-v8/src/script_vm/detached_document_native_handle_tests.rs b/moli-renderer-v8/src/script_vm/detached_document_native_handle_tests.rsindex c14963968..498ad3506 100644--- a/moli-renderer-v8/src/script_vm/detached_document_native_handle_tests.rs+++ b/moli-renderer-v8/src/script_vm/detached_document_native_handle_tests.rs@@ -361,7 +361,7 @@ fn detached_document_shell_child_lists_materialize_from_native_tree() {}#[test]-fn detached_xhtml_document_uses_native_root_namespace_after_property_tamper() {+fn detached_xhtml_document_uses_native_content_type_after_property_tamper() {let status = eval(r#"(() => {@@ -390,6 +390,77 @@ fn detached_xhtml_document_uses_native_root_namespace_after_property_tamper() {);}+#[test]+fn detached_document_content_type_changes_in_native_metadata_reach_all_wrappers() {+ let (status, mut vm) = eval_with_vm(+ r#"+ globalThis.nativeContentTypeDocument = new DOMParser().parseFromString(+ '<root id="native-content-type-root"/>',+ 'text/xml'+ );+ nativeContentTypeDocument.contentType+ "#,+ );+ assert_eq!(status, "text/xml");++ let root = element_handle_by_id(&vm, "native-content-type-root");+ let document = vm+ .document_runtime+ .dom_host()+ .dom()+ .parent_node(root)+ .unwrap();+ assert_eq!(+ vm.document_runtime+ .dom_host()+ .document_content_type_for_handle(document),+ Some("text/xml")+ );+ vm.document_runtime+ .dom_host_mut()+ .set_document_content_type_for_handle(document, "application/xhtml+xml");++ let status = vm+ .eval(+ r#"+ (() => {+ const doc = nativeContentTypeDocument;+ doc.removeChild(doc.documentElement);+ const contentType = Object.getOwnPropertyDescriptor(+ Document.prototype, 'contentType'+ ).get;+ const values = [+ doc.contentType,+ contentType.call(doc),+ doc.createElement('MiXeD').namespaceURI,+ Document.prototype.createElement.call(doc, 'MiXeD').namespaceURI+ ];+ let reads = 0;+ Object.defineProperty(doc, 'contentType', {+ get() { reads++; return 'tampered/type'; }+ });+ for (const deep of [false, true]) {+ const clone = doc.cloneNode(deep);+ const node = clone.createElement('MiXeD');+ values.push(clone.contentType, node.namespaceURI, node.localName);+ }+ values.push(reads);+ return values.join('|');+ })()+ "#,+ )+ .expect("native content type should determine document behavior");+ assert_eq!(+ status,+ concat!(+ "application/xhtml+xml|application/xhtml+xml|",+ "http://www.w3.org/1999/xhtml|http://www.w3.org/1999/xhtml|",+ "application/xhtml+xml|http://www.w3.org/1999/xhtml|MiXeD|",+ "application/xhtml+xml|http://www.w3.org/1999/xhtml|MiXeD|0"+ )+ );+}+#[test]fn detached_document_url_query_encoding_does_not_inherit_main_document_legacy_charset() {let mut vm = new_vm();diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rsindex fce5aa097..483ee2d9c 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs@@ -8755,6 +8755,19 @@ fn detached_domparser_adopted_nodes_follow_live_tree_for_children_text_and_mutat);}+#[test]+fn detached_document_content_type_controls_element_creation_after_root_mutations_and_cloning() {+ let mut vm = new_storage_test_vm("https://document-create-element-content-type.test/");+ let fixture =+ include_str!("../../../../tests/fixtures/document-create-element-content-type.js");+ let result = vm+ .eval(&format!("JSON.stringify({fixture})"))+ .expect("Document content type and element creation probe should evaluate");+ let result: serde_json::Value = serde_json::from_str(&result).unwrap();+ assert_eq!(result["failures"], serde_json::json!([]), "{result}");+ assert_eq!(result["checks"], 689);+}+#[test]fn domparser_xml_preserves_requested_content_type_for_success_and_error_documents() {let mut vm = new_storage_test_vm("https://domparser-xml-content-type.test/");diff --git a/moli-renderer-v8/tests/fixtures/document-create-element-content-type.js b/moli-renderer-v8/tests/fixtures/document-create-element-content-type.jsnew file mode 100644index 000000000..a27950412--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/document-create-element-content-type.js@@ -0,0 +1,71 @@+(() => {+ const html = "http://www.w3.org/1999/xhtml";+ const svg = "http://www.w3.org/2000/svg";+ const parser = new DOMParser();+ const contentType = Object.getOwnPropertyDescriptor(Document.prototype, "contentType").get;+ const factories = [+ ["HTML implementation", () => document.implementation.createHTMLDocument(""), "text/html"],+ ["HTML parser", () => parser.parseFromString("", "text/html"), "text/html"],+ ["XHTML no namespace", () => parser.parseFromString("<html/>", "application/xhtml+xml"), "application/xhtml+xml"],+ ["XHTML SVG root", () => parser.parseFromString('<svg xmlns="' + svg + '"/>', "application/xhtml+xml"), "application/xhtml+xml"],+ ["XHTML parser error", () => parser.parseFromString("", "application/xhtml+xml"), "application/xhtml+xml"],+ ["XML XHTML root", () => parser.parseFromString('<html xmlns="' + html + '"/>', "application/xml"), "application/xml"],+ ["text XML XHTML root", () => parser.parseFromString('<html xmlns="' + html + '"/>', "text/xml"), "text/xml"],+ ["SVG XHTML root", () => parser.parseFromString('<html xmlns="' + html + '"/>', "image/svg+xml"), "image/svg+xml"],+ ["XHTML implementation", () => document.implementation.createDocument(html, "html"), "application/xhtml+xml"],+ ["rootless XHTML implementation", () => document.implementation.createDocument(html, ""), "application/xhtml+xml"],+ ["SVG implementation", () => document.implementation.createDocument(svg, "svg"), "image/svg+xml"],+ ["XML implementation", () => document.implementation.createDocument(null, "root"), "application/xml"],+ ["Document constructor", () => new Document(), "application/xml"],+ ];+ const failures = [];+ let checks = 0;+ function equal(label, actual, expected) {+ checks++;+ if (actual !== expected) failures.push({label, actual, expected});+ }+ for (const [label, factory, type] of factories) {+ const doc = factory();+ const namespace = type === "text/html" || type === "application/xhtml+xml" ? html : null;+ function check(phase) {+ const prefix = label + ": " + phase;+ equal(prefix + " contentType", contentType.call(doc), type);+ const node = doc.createElement("MiXeD");+ equal(prefix + " namespace", node.namespaceURI, namespace);+ equal(prefix + " name", node.localName, type === "text/html" ? "mixed" : "MiXeD");+ equal(prefix + " owner", node.ownerDocument === doc, true);+ equal(prefix + " null namespace", doc.createElementNS(null, "MiXeD").namespaceURI, null);+ equal(prefix + " empty namespace", doc.createElementNS("", "MiXeD").namespaceURI, null);+ equal(prefix + " SVG namespace", doc.createElementNS(svg, "g").namespaceURI, svg);+ equal(prefix + " borrowed method", Document.prototype.createElement.call(doc, "x").namespaceURI, namespace);+ }+ check("initial");+ if (doc.documentElement) doc.removeChild(doc.documentElement);+ check("root removed");+ const root = doc.createElementNS(html, "html");+ doc.appendChild(root);+ check("HTML root");+ doc.replaceChild(doc.createElementNS(svg, "svg"), root);+ check("SVG root");+ function checkClones(phase) {+ for (const deep of [false, true]) {+ const clone = doc.cloneNode(deep);+ const node = clone.createElement("MiXeD");+ equal(label + ": " + phase + " clone " + deep + " contentType", clone.contentType, type);+ equal(label + ": " + phase + " clone " + deep + " namespace", node.namespaceURI, namespace);+ equal(label + ": " + phase + " clone " + deep + " owner", node.ownerDocument === clone, true);+ }+ }+ checkClones("SVG root");+ let reads = 0;+ for (const property of ["contentType", "documentElement"]) {+ Object.defineProperty(doc, property, {+ get() { reads++; return property === "contentType" ? "tampered/type" : null; }+ });+ }+ check("public getters replaced");+ checkClones("public getters replaced");+ equal(label + ": no public getter reads", reads, 0);+ }+ return {checks, failures};+})()