Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(dom): unify HTML serialization traversal
ldm0689fc8278b06
diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rsindex bd360d3fa..4d2f9217d 100644--- a/moli-dom/src/native/host/mutation/tree.rs+++ b/moli-dom/src/native/host/mutation/tree.rs@@ -548,6 +548,15 @@ impl DomHost {self.dom.inner_html(handle)}+ pub fn inner_html_with_scripting_enabled(+ &self,+ handle: DomHandle,+ scripting_enabled: bool,+ ) -> Option<String> {+ self.dom+ .inner_html_with_scripting_enabled(handle, scripting_enabled)+ }+pub fn node_metadata(&self, handle: DomHandle) -> Option<LiveDomNodeMetadata> {self.dom.node_metadata(handle)}diff --git a/moli-dom/src/native/host/serialize.rs b/moli-dom/src/native/host/serialize.rsindex 9aa2a50e1..3021cc8b1 100644--- a/moli-dom/src/native/host/serialize.rs+++ b/moli-dom/src/native/host/serialize.rs@@ -1,6 +1,7 @@use super::*;use crate::native::serialize::{- escape_html_attribute, escape_html_text, is_void_html_element, serialize_cdata_section,+ HtmlSerializationOptions, HtmlSerializationTarget, HtmlSerializedShadowRoot,+ escape_html_attribute, serialize_html_into_sink,};pub type ShadowRootRegistryAttributePolicy<'a> =@@ -25,45 +26,23 @@ impl ShadowRootInclusion<'_> {}}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum HtmlSerializationTarget {- IncludeNode,- ChildrenOnly,-}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum ShadowRootMarkupProfile {WebApi,Inspector,}-enum HostHtmlSerializationFrame<'a> {- Node {- handle: DomHandle,- raw_text_parent: bool,- },- Children {- handle: DomHandle,- raw_text_parent: bool,- },- ShadowRootTemplate {- host: DomHandle,- shadow_root: DomHandle,- init: ShadowRootInit,- },- CloseElement(&'a str),- CloseShadowRootTemplate,-}-impl DomHost {pub fn get_html(&self,handle: DomHandle,+ scripting_enabled: bool,serializable_shadow_roots: bool,explicit_shadow_roots: &[DomHandle],) -> Option<String> {self.get_html_with_shadow_root_registry_attribute_policy(handle,+ scripting_enabled,serializable_shadow_roots,explicit_shadow_roots,None,@@ -73,6 +52,7 @@ impl DomHost {pub fn get_html_with_shadow_root_registry_attribute_policy(&self,handle: DomHandle,+ scripting_enabled: bool,serializable_shadow_roots: bool,explicit_shadow_roots: &[DomHandle],registry_attribute_policy: Option<&ShadowRootRegistryAttributePolicy<'_>>,@@ -80,6 +60,7 @@ impl DomHost {self.serialize_html_with_shadow_roots(handle,HtmlSerializationTarget::ChildrenOnly,+ scripting_enabled,ShadowRootInclusion::SerializableOrExplicit {serializable: serializable_shadow_roots,explicit: explicit_shadow_roots,@@ -91,12 +72,14 @@ impl DomHost {pub fn outer_html_with_shadow_roots(&self,handle: DomHandle,+ scripting_enabled: bool,shadow_root_inclusion: ShadowRootInclusion<'_>,registry_attribute_policy: Option<&ShadowRootRegistryAttributePolicy<'_>>,) -> Option<String> {self.serialize_html_with_shadow_roots(handle,HtmlSerializationTarget::IncludeNode,+ scripting_enabled,shadow_root_inclusion,registry_attribute_policy,)@@ -106,231 +89,28 @@ impl DomHost {&self,handle: DomHandle,target: HtmlSerializationTarget,+ scripting_enabled: bool,shadow_root_inclusion: ShadowRootInclusion<'_>,registry_attribute_policy: Option<&ShadowRootRegistryAttributePolicy<'_>>,) -> Option<String> {- let node = self.node(handle)?;- let mut html = String::new();- let stack = match target {- HtmlSerializationTarget::IncludeNode => vec![HostHtmlSerializationFrame::Node {- handle,- raw_text_parent: false,- }],- HtmlSerializationTarget::ChildrenOnly => {- if node.as_element().is_some_and(|element| {- is_void_html_element(element.namespace(), element.local_name())- }) {- return Some(String::new());- }- let mut stack = vec![HostHtmlSerializationFrame::Children {- handle,- raw_text_parent: false,- }];- if node.as_element().is_some()- && let Some((shadow_root, init)) =- self.serialized_shadow_root_for_host(handle, shadow_root_inclusion)- {- stack.push(HostHtmlSerializationFrame::ShadowRootTemplate {- host: handle,- shadow_root,- init,- });- }- stack- }- };- self.serialize_html_frames(- &mut html,- stack,- shadow_root_inclusion,- registry_attribute_policy,- );- Some(html)- }-- fn serialize_html_frames<'a>(- &'a self,- out: &mut String,- mut stack: Vec<HostHtmlSerializationFrame<'a>>,- shadow_root_inclusion: ShadowRootInclusion<'_>,- registry_attribute_policy: Option<&ShadowRootRegistryAttributePolicy<'_>>,- ) {- while let Some(frame) = stack.pop() {- match frame {- HostHtmlSerializationFrame::Node {- handle,- raw_text_parent,- } => self.serialize_html_node_frame(- handle,- out,- raw_text_parent,- shadow_root_inclusion,- &mut stack,- ),- HostHtmlSerializationFrame::Children {- handle,- raw_text_parent,- } => self.push_html_child_frames(handle, raw_text_parent, &mut stack),- HostHtmlSerializationFrame::ShadowRootTemplate {- host,- shadow_root,- init,- } => {- self.write_shadow_root_template_start(- host,- shadow_root,- &init,- shadow_root_inclusion.markup_profile(),- out,- registry_attribute_policy,- );- stack.push(HostHtmlSerializationFrame::CloseShadowRootTemplate);- stack.push(HostHtmlSerializationFrame::Children {- handle: shadow_root,- raw_text_parent: false,- });- }- HostHtmlSerializationFrame::CloseElement(local_name) => {- out.push_str("</");- out.push_str(local_name);- out.push('>');- }- HostHtmlSerializationFrame::CloseShadowRootTemplate => {- out.push_str("</template>");- }- }- }- }-- fn push_html_child_frames<'a>(- &self,- handle: DomHandle,- raw_text_parent: bool,- stack: &mut Vec<HostHtmlSerializationFrame<'a>>,- ) {- let Some(node) = self.node(handle) else {- return;- };- if let Some(template_contents) = node- .as_element()- .and_then(|element| element.template_contents())- {- let raw_text_child = node.as_element().is_some_and(|element| {- is_raw_text_element(element.namespace(), element.local_name())- });- stack.push(HostHtmlSerializationFrame::Children {- handle: template_contents,- raw_text_parent: raw_text_child,- });- return;- }- stack.extend(self.child_handles_reversed(handle).map(|handle| {- HostHtmlSerializationFrame::Node {- handle,- raw_text_parent,- }- }));- }-- fn serialize_html_node_frame<'a>(- &'a self,- handle: DomHandle,- out: &mut String,- raw_text_parent: bool,- shadow_root_inclusion: ShadowRootInclusion<'_>,- stack: &mut Vec<HostHtmlSerializationFrame<'a>>,- ) {- let Some(node) = self.node(handle) else {- return;+ let shadow_root_provider = |host| {+ let (shadow_root, init) =+ self.serialized_shadow_root_for_host(host, shadow_root_inclusion)?;+ let mut template_start = String::new();+ self.write_shadow_root_template_start(+ host,+ shadow_root,+ &init,+ shadow_root_inclusion.markup_profile(),+ &mut template_start,+ registry_attribute_policy,+ );+ Some(HtmlSerializedShadowRoot::new(shadow_root, template_start))};- match node.data() {- NodeData::Document(_) | NodeData::DocumentFragment(_) => {- stack.push(HostHtmlSerializationFrame::Children {- handle,- raw_text_parent,- });- }- NodeData::DocumentType(document_type) => {- out.push_str("<!DOCTYPE ");- out.push_str(document_type.name());- if !document_type.public_id().is_empty() || !document_type.system_id().is_empty() {- out.push_str(" PUBLIC \"");- out.push_str(document_type.public_id());- out.push_str("\" \"");- out.push_str(document_type.system_id());- out.push('"');- }- out.push('>');- }- NodeData::Element(element) => {- out.push('<');- out.push_str(element.local_name());- if let Some(is_name) = element.custom_element_is_name()- && !element.has_attribute("is")- {- out.push_str(" is=\"");- escape_html_attribute(is_name, out);- out.push('"');- }- for attribute in element.attributes() {- out.push(' ');- attribute.push_html_serialized_name(|part| out.push_str(part));- out.push_str("=\"");- escape_html_attribute(attribute.value(), out);- out.push('"');- }- out.push('>');-- let raw_text_child = is_raw_text_element(element.namespace(), element.local_name());- if !is_void_html_element(element.namespace(), element.local_name()) {- stack.push(HostHtmlSerializationFrame::CloseElement(- element.local_name(),- ));- stack.push(HostHtmlSerializationFrame::Children {- handle,- raw_text_parent: raw_text_child,- });- if let Some((shadow_root, init)) =- self.serialized_shadow_root_for_host(handle, shadow_root_inclusion)- {- stack.push(HostHtmlSerializationFrame::ShadowRootTemplate {- host: handle,- shadow_root,- init,- });- }- }- }- NodeData::Text(text) => {- if raw_text_parent {- out.push_str(text.data());- } else {- escape_html_text(text.data(), out);- }- }- NodeData::CDataSection(cdata) => {- serialize_cdata_section(- cdata.data(),- out,- raw_text_parent,- self.node_document_is_html_document(handle).unwrap_or(false),- );- }- NodeData::Comment(comment) => {- out.push_str("<!--");- out.push_str(comment.data());- out.push_str("-->");- }- NodeData::ProcessingInstruction(processing_instruction) => {- out.push_str("<?");- out.push_str(processing_instruction.target());- if !processing_instruction.data().is_empty() {- out.push(' ');- out.push_str(processing_instruction.data());- }- out.push_str("?>");- }- }+ let options = HtmlSerializationOptions::new(target, scripting_enabled)+ .with_shadow_root_provider(&shadow_root_provider);+ let mut html = String::new();+ serialize_html_into_sink(&self.dom, handle, options, &mut html).then_some(html)}fn serialized_shadow_root_for_host(@@ -406,11 +186,6 @@ impl DomHost {}}-fn is_raw_text_element(namespace: &str, local_name: &str) -> bool {- namespace == "http://www.w3.org/1999/xhtml"- && matches!(local_name, "script" | "style" | "textarea" | "title")-}-#[cfg(test)]mod tests {use super::*;@@ -444,7 +219,7 @@ mod tests {assert!(host.append_child(element, light_text));assert_eq!(- host.outer_html_with_shadow_roots(element, ShadowRootInclusion::None, None)+ host.outer_html_with_shadow_roots(element, true, ShadowRootInclusion::None, None).as_deref(),Some("<section id=\"host\">light & more</section>"));@@ -453,6 +228,7 @@ mod tests {assert_eq!(host.outer_html_with_shadow_roots(element,+ true,ShadowRootInclusion::AllAuthorForInspector,Some(&include_registry),)@@ -468,6 +244,7 @@ mod tests {assert_eq!(host.get_html_with_shadow_root_registry_attribute_policy(element,+ true,false,&[shadow_root],Some(&include_registry),@@ -507,13 +284,14 @@ mod tests {assert!(host.append_child(outer_host, outer_light));assert_eq!(- host.outer_html_with_shadow_roots(outer_host, ShadowRootInclusion::None, None)+ host.outer_html_with_shadow_roots(outer_host, true, ShadowRootInclusion::None, None).as_deref(),Some("<x-outer>outer-light</x-outer>"));assert_eq!(host.outer_html_with_shadow_roots(outer_host,+ true,ShadowRootInclusion::SerializableOrExplicit {serializable: false,explicit: &[outer_root],@@ -534,6 +312,7 @@ mod tests {assert_eq!(host.outer_html_with_shadow_roots(outer_host,+ true,ShadowRootInclusion::AllAuthorForInspector,None,)@@ -543,6 +322,7 @@ mod tests {assert_eq!(host.outer_html_with_shadow_roots(host.document_node_id(),+ true,ShadowRootInclusion::AllAuthorForInspector,None,)@@ -552,6 +332,7 @@ mod tests {assert_eq!(host.outer_html_with_shadow_roots(outer_root,+ true,ShadowRootInclusion::AllAuthorForInspector,None,)@@ -584,12 +365,17 @@ mod tests {assert!(host.append_child(shadow_host, leaf));assert_eq!(- host.outer_html_with_shadow_roots(root, ShadowRootInclusion::None, None)+ host.outer_html_with_shadow_roots(root, true, ShadowRootInclusion::None, None).as_deref(),Some("<div></div>"));let html = host- .outer_html_with_shadow_roots(root, ShadowRootInclusion::AllAuthorForInspector, None)+ .outer_html_with_shadow_roots(+ root,+ true,+ ShadowRootInclusion::AllAuthorForInspector,+ None,+ ).expect("deep inspector outer HTML");assert_eq!(html.matches("<template shadowrootmode=").count(), DEPTH);assert!(html.starts_with("<div><template shadowrootmode=\"open\"><div>"));@@ -656,7 +442,7 @@ mod tests {fragment_child,] {assert_eq!(- host.outer_html_with_shadow_roots(handle, ShadowRootInclusion::None, None),+ host.outer_html_with_shadow_roots(handle, true, ShadowRootInclusion::None, None),host.dom().outer_html(handle),"shadow-excluding host serializer diverged for {handle:?}");diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rsindex e1f44c828..9a6d4eefb 100644--- a/moli-dom/src/native/mod.rs+++ b/moli-dom/src/native/mod.rs@@ -3198,7 +3198,7 @@ mod tests {);let html = host- .get_html(root, false, &[shadow_root])+ .get_html(root, true, false, &[shadow_root]).expect("shadow-including HTML");assert!(html.contains("<template shadowrootmode=\"open\">"));assert!(html.contains("</template></article><script></script>"));diff --git a/moli-dom/src/native/node/mod.rs b/moli-dom/src/native/node/mod.rsindex 98ff0bca1..556d34d61 100644--- a/moli-dom/src/native/node/mod.rs+++ b/moli-dom/src/native/node/mod.rs@@ -9,10 +9,6 @@ use std::num::NonZeroU32;use super::NativeDom;use super::element::Element;-use super::serialize::{- HtmlSerializationSink, escape_html_attribute, escape_html_text, is_void_html_element,- serialize_cdata_section,-};#[derive(Clone, Copy, PartialEq, Eq, Hash)]pub struct NativeNodeId(NonZeroU32);@@ -598,47 +594,6 @@ impl Node {}}- pub fn serialize_into(&self, dom: &NativeDom, out: &mut String, raw_text_parent: bool) {- self.serialize_into_sink(dom, out, raw_text_parent);- }-- pub(super) fn serialize_with_limit(- &self,- dom: &NativeDom,- raw_text_parent: bool,- max_bytes: usize,- ) -> Result<String, super::serialize::HtmlSerializationLimitExceeded> {- let mut out = BoundedHtmlSerialization::new(max_bytes);- self.serialize_into_sink(dom, &mut out, raw_text_parent);- out.finish()- }-- fn serialize_into_sink<'a, S>(&'a self, dom: &'a NativeDom, out: &mut S, raw_text_parent: bool)- where- S: HtmlSerializationSink,- {- let mut stack = vec![HtmlSerializationFrame::Node {- node_id: self.id(),- raw_text_parent,- }];- while !out.limit_exceeded() {- let Some(frame) = stack.pop() else {- break;- };- match frame {- HtmlSerializationFrame::Node {- node_id,- raw_text_parent,- } => serialize_html_node_frame(dom, node_id, out, raw_text_parent, &mut stack),- HtmlSerializationFrame::CloseElement(local_name) => {- out.push_str("</");- out.push_str(local_name);- out.push('>');- }- }- }- }-pub fn set_first_child(&mut self, first_child: Option<NativeNodeId>) {self.first_child = first_child;}@@ -719,185 +674,6 @@ impl Node {}}-struct BoundedHtmlSerialization {- output: String,- max_bytes: usize,- exceeded: bool,-}--impl BoundedHtmlSerialization {- fn new(max_bytes: usize) -> Self {- Self {- output: String::new(),- max_bytes,- exceeded: false,- }- }-- fn finish(self) -> Result<String, super::serialize::HtmlSerializationLimitExceeded> {- if self.exceeded {- Err(super::serialize::HtmlSerializationLimitExceeded {- max_bytes: self.max_bytes,- })- } else {- Ok(self.output)- }- }-}--impl HtmlSerializationSink for BoundedHtmlSerialization {- fn push_str(&mut self, value: &str) {- if self.exceeded {- return;- }- if self- .output- .len()- .checked_add(value.len())- .is_none_or(|length| length > self.max_bytes)- {- self.exceeded = true;- return;- }- self.output.push_str(value);- }-- fn push(&mut self, value: char) {- if self.exceeded {- return;- }- if self- .output- .len()- .checked_add(value.len_utf8())- .is_none_or(|length| length > self.max_bytes)- {- self.exceeded = true;- return;- }- self.output.push(value);- }-- fn limit_exceeded(&self) -> bool {- self.exceeded- }-}--enum HtmlSerializationFrame<'a> {- Node {- node_id: NativeNodeId,- raw_text_parent: bool,- },- CloseElement(&'a str),-}--fn serialize_html_node_frame<'a, S>(- dom: &'a NativeDom,- node_id: NativeNodeId,- out: &mut S,- raw_text_parent: bool,- stack: &mut Vec<HtmlSerializationFrame<'a>>,-) where- S: HtmlSerializationSink,-{- let Some(node) = dom.node(node_id) else {- return;- };- match node.data() {- NodeData::Document(_) => {- push_child_html_serialization_frames(dom, node_id, false, stack);- }- NodeData::DocumentType(document_type) => {- out.push_str("<!DOCTYPE ");- out.push_str(document_type.name());- if !document_type.public_id().is_empty() || !document_type.system_id().is_empty() {- out.push_str(" PUBLIC \"");- out.push_str(document_type.public_id());- out.push_str("\" \"");- out.push_str(document_type.system_id());- out.push('"');- }- out.push('>');- }- NodeData::Element(element) => {- out.push('<');- out.push_str(element.local_name());- if let Some(is_name) = element.custom_element_is_name()- && !element.has_attribute("is")- {- out.push_str(" is=\"");- escape_html_attribute(is_name, out);- out.push('"');- }- for attribute in element.attributes() {- if out.limit_exceeded() {- return;- }- out.push(' ');- attribute.push_html_serialized_name(|part| out.push_str(part));- out.push_str("=\"");- escape_html_attribute(attribute.value(), out);- out.push('"');- }- out.push('>');-- let raw_text_child = is_raw_text_element(element.namespace(), element.local_name());- let children_root = element.template_contents().unwrap_or(node_id);- if !is_void_html_element(element.namespace(), element.local_name()) {- stack.push(HtmlSerializationFrame::CloseElement(element.local_name()));- push_child_html_serialization_frames(dom, children_root, raw_text_child, stack);- }- }- NodeData::Text(text) => {- if raw_text_parent {- out.push_str(text.data());- } else {- escape_html_text(text.data(), out);- }- }- NodeData::CDataSection(cdata) => {- serialize_cdata_section(- cdata.data(),- out,- raw_text_parent,- dom.node_document_is_html_document(node_id).unwrap_or(false),- );- }- NodeData::Comment(comment) => {- out.push_str("<!--");- out.push_str(comment.data());- out.push_str("-->");- }- NodeData::ProcessingInstruction(processing_instruction) => {- out.push_str("<?");- out.push_str(processing_instruction.target());- if !processing_instruction.data().is_empty() {- out.push(' ');- out.push_str(processing_instruction.data());- }- out.push_str("?>");- }- NodeData::DocumentFragment(_) => {- push_child_html_serialization_frames(dom, node_id, raw_text_parent, stack);- }- }-}--fn push_child_html_serialization_frames<'a>(- dom: &NativeDom,- parent: NativeNodeId,- raw_text_parent: bool,- stack: &mut Vec<HtmlSerializationFrame<'a>>,-) {- stack.extend(- dom.child_ids_reversed(parent)- .map(|node_id| HtmlSerializationFrame::Node {- node_id,- raw_text_parent,- }),- );-}-fn node_data_is_equal(left: &Node, right: &Node) -> bool {if left.node_type() != right.node_type() {return false;@@ -977,8 +753,3 @@ fn sibling_document_order(dom: &NativeDom, left: NativeNodeId, right: NativeNode}0}--fn is_raw_text_element(namespace: &str, local_name: &str) -> bool {- namespace == "http://www.w3.org/1999/xhtml"- && matches!(local_name, "script" | "style" | "noscript")-}diff --git a/moli-dom/src/native/serialize.rs b/moli-dom/src/native/serialize.rsindex 121640c8a..098838377 100644--- a/moli-dom/src/native/serialize.rs+++ b/moli-dom/src/native/serialize.rs@@ -1,5 +1,5 @@use super::NativeDom;-use super::node::{NativeNodeId, Node};+use super::node::{NativeNodeId, Node, NodeData};/// A bounded serialization stopped before appending bytes past its limit.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -25,6 +25,70 @@ pub(super) trait HtmlSerializationSink {fn limit_exceeded(&self) -> bool;}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum HtmlSerializationTarget {+ IncludeNode,+ ChildrenOnly,+}++pub(super) struct HtmlSerializedShadowRoot {+ root: NativeNodeId,+ template_start: String,+}++impl HtmlSerializedShadowRoot {+ pub(super) fn new(root: NativeNodeId, template_start: String) -> Self {+ Self {+ root,+ template_start,+ }+ }+}++pub(super) trait HtmlShadowRootProvider {+ fn serialized_shadow_root_for_host(+ &self,+ host: NativeNodeId,+ ) -> Option<HtmlSerializedShadowRoot>;+}++impl<F> HtmlShadowRootProvider for F+where+ F: Fn(NativeNodeId) -> Option<HtmlSerializedShadowRoot>,+{+ fn serialized_shadow_root_for_host(+ &self,+ host: NativeNodeId,+ ) -> Option<HtmlSerializedShadowRoot> {+ self(host)+ }+}++#[derive(Clone, Copy)]+pub(super) struct HtmlSerializationOptions<'a> {+ target: HtmlSerializationTarget,+ scripting_enabled: bool,+ shadow_root_provider: Option<&'a dyn HtmlShadowRootProvider>,+}++impl<'a> HtmlSerializationOptions<'a> {+ pub(super) const fn new(target: HtmlSerializationTarget, scripting_enabled: bool) -> Self {+ Self {+ target,+ scripting_enabled,+ shadow_root_provider: None,+ }+ }++ pub(super) const fn with_shadow_root_provider(+ mut self,+ shadow_root_provider: &'a dyn HtmlShadowRootProvider,+ ) -> Self {+ self.shadow_root_provider = Some(shadow_root_provider);+ self+ }+}+impl HtmlSerializationSink for String {fn push_str(&mut self, value: &str) {String::push_str(self, value);@@ -121,14 +185,290 @@ pub(super) fn is_void_html_element(namespace: &str, local_name: &str) -> bool {)}+enum HtmlSerializationFrame<'a> {+ Node(NativeNodeId),+ Children(NativeNodeId),+ ShadowRootTemplate(HtmlSerializedShadowRoot),+ CloseElement(&'a str),+ CloseShadowRootTemplate,+}++pub(super) fn serialize_html_into_sink<S>(+ dom: &NativeDom,+ node_id: NativeNodeId,+ options: HtmlSerializationOptions<'_>,+ out: &mut S,+) -> bool+where+ S: HtmlSerializationSink,+{+ let Some(node) = dom.node(node_id) else {+ return false;+ };+ if options.target == HtmlSerializationTarget::ChildrenOnly+ && node+ .as_element()+ .is_some_and(|element| is_void_html_element(element.namespace(), element.local_name()))+ {+ return true;+ }++ let mut stack = match options.target {+ HtmlSerializationTarget::IncludeNode => vec![HtmlSerializationFrame::Node(node_id)],+ HtmlSerializationTarget::ChildrenOnly => {+ let mut stack = vec![HtmlSerializationFrame::Children(node_id)];+ push_shadow_root_frame(node_id, options.shadow_root_provider, &mut stack);+ stack+ }+ };++ while !out.limit_exceeded() {+ let Some(frame) = stack.pop() else {+ break;+ };+ match frame {+ HtmlSerializationFrame::Node(node_id) => {+ serialize_html_node_frame(dom, node_id, options, out, &mut stack);+ }+ HtmlSerializationFrame::Children(node_id) => {+ push_child_html_serialization_frames(dom, node_id, &mut stack);+ }+ HtmlSerializationFrame::ShadowRootTemplate(shadow_root) => {+ out.push_str(&shadow_root.template_start);+ stack.push(HtmlSerializationFrame::CloseShadowRootTemplate);+ stack.push(HtmlSerializationFrame::Children(shadow_root.root));+ }+ HtmlSerializationFrame::CloseElement(local_name) => {+ out.push_str("</");+ out.push_str(local_name);+ out.push('>');+ }+ HtmlSerializationFrame::CloseShadowRootTemplate => {+ out.push_str("</template>");+ }+ }+ }+ true+}++fn serialize_html_node_frame<'a, S>(+ dom: &'a NativeDom,+ node_id: NativeNodeId,+ options: HtmlSerializationOptions<'_>,+ out: &mut S,+ stack: &mut Vec<HtmlSerializationFrame<'a>>,+) where+ S: HtmlSerializationSink,+{+ let Some(node) = dom.node(node_id) else {+ return;+ };+ match node.data() {+ NodeData::Document(_) | NodeData::DocumentFragment(_) => {+ stack.push(HtmlSerializationFrame::Children(node_id));+ }+ NodeData::DocumentType(document_type) => {+ out.push_str("<!DOCTYPE ");+ out.push_str(document_type.name());+ if !document_type.public_id().is_empty() || !document_type.system_id().is_empty() {+ out.push_str(" PUBLIC \"");+ out.push_str(document_type.public_id());+ out.push_str("\" \"");+ out.push_str(document_type.system_id());+ out.push('"');+ }+ out.push('>');+ }+ NodeData::Element(element) => {+ out.push('<');+ out.push_str(element.local_name());+ if let Some(is_name) = element.custom_element_is_name()+ && !element.has_attribute("is")+ {+ out.push_str(" is=\"");+ escape_html_attribute(is_name, out);+ out.push('"');+ }+ for attribute in element.attributes() {+ if out.limit_exceeded() {+ return;+ }+ out.push(' ');+ attribute.push_html_serialized_name(|part| out.push_str(part));+ out.push_str("=\"");+ escape_html_attribute(attribute.value(), out);+ out.push('"');+ }+ out.push('>');++ if !is_void_html_element(element.namespace(), element.local_name()) {+ stack.push(HtmlSerializationFrame::CloseElement(element.local_name()));+ stack.push(HtmlSerializationFrame::Children(node_id));+ push_shadow_root_frame(node_id, options.shadow_root_provider, stack);+ }+ }+ NodeData::Text(text) => {+ if text_data_serializes_literally(dom, node_id, options.scripting_enabled) {+ out.push_str(text.data());+ } else {+ escape_html_text(text.data(), out);+ }+ }+ NodeData::CDataSection(cdata) => {+ serialize_cdata_section(+ cdata.data(),+ out,+ text_data_serializes_literally(dom, node_id, options.scripting_enabled),+ dom.node_document_is_html_document(node_id).unwrap_or(false),+ );+ }+ NodeData::Comment(comment) => {+ out.push_str("<!--");+ out.push_str(comment.data());+ out.push_str("-->");+ }+ NodeData::ProcessingInstruction(processing_instruction) => {+ out.push_str("<?");+ out.push_str(processing_instruction.target());+ if !processing_instruction.data().is_empty() {+ out.push(' ');+ out.push_str(processing_instruction.data());+ }+ out.push_str("?>");+ }+ }+}++fn push_child_html_serialization_frames<'a>(+ dom: &NativeDom,+ node_id: NativeNodeId,+ stack: &mut Vec<HtmlSerializationFrame<'a>>,+) {+ let children_root = dom+ .node(node_id)+ .and_then(Node::as_element)+ .and_then(|element| element.template_contents())+ .unwrap_or(node_id);+ stack.extend(+ dom.child_ids_reversed(children_root)+ .map(HtmlSerializationFrame::Node),+ );+}++fn push_shadow_root_frame(+ host: NativeNodeId,+ shadow_root_provider: Option<&dyn HtmlShadowRootProvider>,+ stack: &mut Vec<HtmlSerializationFrame<'_>>,+) {+ let Some(shadow_root) =+ shadow_root_provider.and_then(|provider| provider.serialized_shadow_root_for_host(host))+ else {+ return;+ };+ stack.push(HtmlSerializationFrame::ShadowRootTemplate(shadow_root));+}++fn text_data_serializes_literally(+ dom: &NativeDom,+ node_id: NativeNodeId,+ scripting_enabled: bool,+) -> bool {+ if !dom.node_document_is_html_document(node_id).unwrap_or(false) {+ return false;+ }+ let Some(parent) = dom+ .parent_node(node_id)+ .and_then(|parent| dom.node(parent))+ .and_then(Node::as_element)+ else {+ return false;+ };+ if parent.namespace() != "http://www.w3.org/1999/xhtml" {+ return false;+ }+ matches!(+ parent.local_name(),+ "style" | "script" | "xmp" | "iframe" | "noembed" | "noframes" | "plaintext"+ ) || scripting_enabled && parent.local_name() == "noscript"+}++struct BoundedHtmlSerialization {+ output: String,+ max_bytes: usize,+ exceeded: bool,+}++impl BoundedHtmlSerialization {+ fn new(max_bytes: usize) -> Self {+ Self {+ output: String::new(),+ max_bytes,+ exceeded: false,+ }+ }++ fn finish(self) -> Result<String, HtmlSerializationLimitExceeded> {+ if self.exceeded {+ Err(HtmlSerializationLimitExceeded {+ max_bytes: self.max_bytes,+ })+ } else {+ Ok(self.output)+ }+ }+}++impl HtmlSerializationSink for BoundedHtmlSerialization {+ fn push_str(&mut self, value: &str) {+ if self.exceeded {+ return;+ }+ if self+ .output+ .len()+ .checked_add(value.len())+ .is_none_or(|length| length > self.max_bytes)+ {+ self.exceeded = true;+ return;+ }+ self.output.push_str(value);+ }++ fn push(&mut self, value: char) {+ if self.exceeded {+ return;+ }+ if self+ .output+ .len()+ .checked_add(value.len_utf8())+ .is_none_or(|length| length > self.max_bytes)+ {+ self.exceeded = true;+ return;+ }+ self.output.push(value);+ }++ fn limit_exceeded(&self) -> bool {+ self.exceeded+ }+}+impl NativeDom {pub fn serialize_document(&self) -> String {+ self.serialize_document_with_scripting_enabled(true)+ }++ pub fn serialize_document_with_scripting_enabled(&self, scripting_enabled: bool) -> String {let mut html = String::new();- for child in self.child_ids(self.document_node_id) {- if let Some(child) = self.node(child) {- child.serialize_into(self, &mut html, false);- }- }+ serialize_html_into_sink(+ self,+ self.document_node_id,+ HtmlSerializationOptions::new(HtmlSerializationTarget::ChildrenOnly, scripting_enabled),+ &mut html,+ );html}@@ -146,10 +486,22 @@ impl NativeDom {}pub fn outer_html(&self, node_id: NativeNodeId) -> Option<String> {- let node = self.node(node_id)?;+ self.outer_html_with_scripting_enabled(node_id, true)+ }++ pub fn outer_html_with_scripting_enabled(+ &self,+ node_id: NativeNodeId,+ scripting_enabled: bool,+ ) -> Option<String> {let mut html = String::new();- node.serialize_into(self, &mut html, false);- Some(html)+ serialize_html_into_sink(+ self,+ node_id,+ HtmlSerializationOptions::new(HtmlSerializationTarget::IncludeNode, scripting_enabled),+ &mut html,+ )+ .then_some(html)}/// Serializes one subtree without ever growing the output beyond `max_bytes`.@@ -162,44 +514,35 @@ impl NativeDom {node_id: NativeNodeId,max_bytes: usize,) -> Result<Option<String>, HtmlSerializationLimitExceeded> {- let Some(node) = self.node(node_id) else {+ let mut out = BoundedHtmlSerialization::new(max_bytes);+ if !serialize_html_into_sink(+ self,+ node_id,+ HtmlSerializationOptions::new(HtmlSerializationTarget::IncludeNode, true),+ &mut out,+ ) {return Ok(None);- };- node.serialize_with_limit(self, false, max_bytes).map(Some)+ }+ out.finish().map(Some)}pub fn inner_html(&self, node_id: NativeNodeId) -> Option<String> {- let node = self.node(node_id)?;- if node- .as_element()- .is_some_and(|element| is_void_html_element(element.namespace(), element.local_name()))- {- return Some(String::new());- }+ self.inner_html_with_scripting_enabled(node_id, true)+ }++ pub fn inner_html_with_scripting_enabled(+ &self,+ node_id: NativeNodeId,+ scripting_enabled: bool,+ ) -> Option<String> {let mut html = String::new();- let raw_text_child = node.as_element().is_some_and(|element| {- element.namespace() == "http://www.w3.org/1999/xhtml"- && matches!(element.local_name(), "script" | "style" | "noscript")- });- if let Some(template_contents) = node- .as_element()- .and_then(|element| element.template_contents())- {- if let Some(fragment) = self.node(template_contents) {- for child in fragment.child_ids(self) {- if let Some(child) = self.node(child) {- child.serialize_into(self, &mut html, raw_text_child);- }- }- }- } else {- for child in node.child_ids(self) {- if let Some(child) = self.node(child) {- child.serialize_into(self, &mut html, raw_text_child);- }- }- }- Some(html)+ serialize_html_into_sink(+ self,+ node_id,+ HtmlSerializationOptions::new(HtmlSerializationTarget::ChildrenOnly, scripting_enabled),+ &mut html,+ )+ .then_some(html)}pub fn script_handles(&self) -> Vec<NativeNodeId> {@@ -307,11 +650,98 @@ mod tests {let param = host.create_element("param");assert!(host.append_child(container, param));assert_eq!(- host.get_html(container, false, &[]).as_deref(),+ host.get_html(container, true, false, &[]).as_deref(),Some(format!("{expected}<param>").as_str()));for element in void_elements {- assert_eq!(host.get_html(element, false, &[]).as_deref(), Some(""));+ assert_eq!(+ host.get_html(element, true, false, &[]).as_deref(),+ Some("")+ );+ }+ }++ #[test]+ fn html_text_serialization_uses_the_actual_parent_and_scripting_mode() {+ let mut dom = NativeDom::new_html(test_url());+ let container = dom.create_element("main");+ let mut cases = Vec::new();+ for (local_name, literal_with_scripting, literal_without_scripting) in [+ ("style", true, true),+ ("script", true, true),+ ("xmp", true, true),+ ("iframe", true, true),+ ("noembed", true, true),+ ("noframes", true, true),+ ("plaintext", true, true),+ ("noscript", true, false),+ ("textarea", false, false),+ ("title", false, false),+ ("div", false, false),+ ] {+ let element = dom.create_element(local_name);+ let text = dom.create_text_node("<&");+ assert!(dom.append_child(element, text));+ assert!(dom.append_child(container, element));+ cases.push((+ element,+ local_name,+ literal_with_scripting,+ literal_without_scripting,+ ));+ }++ for &(element, _, literal_with_scripting, literal_without_scripting) in &cases {+ assert_eq!(+ dom.inner_html_with_scripting_enabled(element, true)+ .as_deref(),+ Some(if literal_with_scripting {+ "<&"+ } else {+ "<&"+ })+ );+ assert_eq!(+ dom.inner_html_with_scripting_enabled(element, false)+ .as_deref(),+ Some(if literal_without_scripting {+ "<&"+ } else {+ "<&"+ })+ );+ }++ let host = DomHost::from_dom(dom);+ for &(element, local_name, literal_with_scripting, literal_without_scripting) in &cases {+ for (scripting_enabled, literal) in [+ (true, literal_with_scripting),+ (false, literal_without_scripting),+ ] {+ let contents = if literal { "<&" } else { "<&" };+ assert_eq!(+ host.get_html_with_shadow_root_registry_attribute_policy(+ element,+ scripting_enabled,+ false,+ &[],+ None,+ )+ .as_deref(),+ Some(contents),+ "children-only serialization diverged for {local_name}"+ );+ assert_eq!(+ host.outer_html_with_shadow_roots(+ element,+ scripting_enabled,+ crate::native::ShadowRootInclusion::None,+ None,+ ),+ Some(format!("<{local_name}>{contents}</{local_name}>")),+ "node serialization diverged for {local_name}"+ );+ }}}@@ -379,7 +809,7 @@ mod tests {let host = DomHost::from_dom(dom);assert_eq!(- host.get_html(container, false, &[]).as_deref(),+ host.get_html(container, true, false, &[]).as_deref(),Some(expected));}@@ -427,7 +857,7 @@ mod tests {let host = DomHost::from_dom(html_dom);assert_eq!(- host.get_html(html_svg, false, &[]).as_deref(),+ host.get_html(html_svg, true, false, &[]).as_deref(),Some("<img>&"));}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rsindex 839690dd6..837837247 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs@@ -66,9 +66,12 @@ impl JsContextHost {.then_some(binding.root)}).collect::<Vec<_>>();- let markup = self- .dom_host()- .get_html(document_handle, false, &explicit_shadow_roots)?;+ let markup = self.dom_host().get_html(+ document_handle,+ self.child_browsing_context_scripting_enabled(handle),+ false,+ &explicit_shadow_roots,+ )?;Some(ChildBrowsingContextDocumentSnapshot {url: url.as_str().to_owned(),markup,diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rsindex e123e686c..fa047b6c4 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs@@ -736,6 +736,17 @@ impl JsContextHost {.unwrap_or(false)}+ pub(crate) fn node_document_scripting_enabled(&self, handle: DomHandle) -> bool {+ let Some(document_handle) = self+ .dom_host()+ .document_identity_handle(handle)+ .and_then(|identity| self.dom_host().owner_document_handle(identity))+ else {+ return false;+ };+ self.document_scripting_enabled(document_handle)+ }+pub(crate) fn owner_scripting_enabled(&self, owner: OwnerDispatchScope) -> bool {match owner {OwnerDispatchScope::Top => {diff --git a/moli-renderer-v8/src/native_bridge/element/content.rs b/moli-renderer-v8/src/native_bridge/element/content.rsindex dda6f36c5..0e90fb7c7 100644--- a/moli-renderer-v8/src/native_bridge/element/content.rs+++ b/moli-renderer-v8/src/native_bridge/element/content.rs@@ -833,7 +833,9 @@ fn node_inner_text(}fn node_inner_html(runtime: &JsContextHost, handle: DomHandle) -> Option<String> {- runtime.dom_host().inner_html(handle)+ runtime+ .dom_host()+ .inner_html_with_scripting_enabled(handle, runtime.node_document_scripting_enabled(handle))}fn is_element_or_shadow_root_receiver(runtime: &JsContextHost, handle: DomHandle) -> bool {@@ -898,7 +900,7 @@ pub(in crate::native_bridge) fn node_outer_html_getter_function<'s>(let value = runtime.dom_host().dom()- .outer_html(handle)+ .outer_html_with_scripting_enabled(handle, runtime.node_document_scripting_enabled(handle)).unwrap_or_default();let Some(value) = v8_string(scope, &value) else {rv.set_null();@@ -1055,6 +1057,7 @@ pub(in crate::native_bridge) fn node_get_html_callback<'s>(.dom_host().get_html_with_shadow_root_registry_attribute_policy(handle,+ runtime.node_document_scripting_enabled(handle),serializable_shadow_roots,&explicit_shadow_roots,Some(&should_serialize_registry_attribute),diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex 12411619d..817eb0556 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -1333,6 +1333,7 @@ impl ScriptVm {};host.dom_host().outer_html_with_shadow_roots(handle,+ host.node_document_scripting_enabled(handle),shadow_root_inclusion,Some(&should_serialize_registry_attribute),)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 2481a2ab1..204060e1b 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@@ -21,18 +21,32 @@ fn detached_domparser_parses_noscript_with_scripting_disabled() {created.body.innerHTML ="<noscript><span id='created-fallback'></span></noscript>";+ const raw = doc.createElement("noscript");+ raw.textContent = "<em>fallback&</em>";+return [doc.getElementById("fallback") !== null,doc.querySelector("noscript")?.children.length,doc.getElementById("fragment-fallback") !== null,- created.getElementById("created-fallback") !== null+ created.getElementById("created-fallback") !== null,+ raw.innerHTML,+ raw.getHTML(),+ raw.outerHTML].join("|");})()"#,).expect("detached DOMParser noscript probe should evaluate");- assert_eq!(result, "true|1|true|true");+ assert_eq!(+ result,+ concat!(+ "true|1|true|true|",+ "<em>fallback&</em>|",+ "<em>fallback&</em>|",+ "<noscript><em>fallback&</em></noscript>"+ )+ );}#[test]diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rsindex 871bc7a61..1f636adad 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs@@ -3376,6 +3376,7 @@ fn get_html_serializes_shadow_roots_when_requested() {explicitHost.getHTML({ shadowRoots: [explicitRoot] }),nestedHost.getHTML({ shadowRoots: [nestedOuter] }),nestedHost.getHTML({ serializableShadowRoots: true, shadowRoots: [nestedOuter] }),+ rawWrapper.getHTML() === rawWrapper.innerHTML,rawWrapper.getHTML()].join('|');})()@@ -3398,8 +3399,8 @@ fn get_html_serializes_shadow_roots_when_requested() {"<template shadowrootmode=\"open\"><section id=\"inner-host\">","<template shadowrootmode=\"open\" shadowrootserializable=\"\"><i>nested</i>","</template></section></template>|",- "<title><title&></title><textarea><textarea&></textarea>",- "<noscript><p>noscript&</p></noscript>"+ "true|<title><title&></title><textarea><textarea&></textarea>",+ "<noscript><p>noscript&</p></noscript>"));}