html-to-markdown-rs 3.22.0

High-performance HTML to Markdown converter using the astral-html tokenizer. Part of the Xberg ecosystem.
Documentation
//! Output serialization and formatting.
//!
//! Utilities for serializing HTML elements back to string format, used for preserving
//! original HTML for elements like SVG, math, and custom elements.

use crate::converter::utility::content::normalized_tag_name;
use crate::options::conversion::NATIVE_STACK_SAFE_DEPTH;
use std::borrow::Cow;

/// Escape a reconstructed HTML attribute value for safe interpolation into a `"..."`-quoted
/// attribute.
///
/// The reconstruction always re-quotes with `"` regardless of the source HTML's original quote
/// character, so a value that legitimately contained a literal `"` (valid and common inside a
/// single-quoted HTML attribute, e.g. `title='He said "hi"'`) must have that `"` escaped —
/// otherwise it terminates the reconstructed attribute early and whatever follows in the
/// original value is reinterpreted as new, unintended attributes (audit #24).
pub fn escape_html_attribute_value(value: &str) -> Cow<'_, str> {
    if value.contains('"') {
        Cow::Owned(value.replace('"', "&quot;"))
    } else {
        Cow::Borrowed(value)
    }
}

fn serialize_attributes(tag: &crate::dom::HTMLTag<'_>, tag_name: &str, output: &mut String) {
    if tag_name == "script" {
        // ~keep A repaired-script owner temporarily promotes the parser's inline attributes to a randomized map.
        let mut attributes: Vec<_> = tag.attributes().iter().collect();
        attributes.sort_unstable_by(|left, right| left.0.cmp(&right.0));
        write_attributes(attributes.into_iter(), output);
    } else {
        write_attributes(tag.attributes().iter(), output);
    }
}

/// Write an opening tag with source attributes.
pub fn serialize_open_tag(tag: &crate::dom::HTMLTag<'_>, name: &str, output: &mut String) {
    output.push('<');
    output.push_str(name);
    serialize_attributes(tag, name, output);
    output.push('>');
}

fn write_attributes<'a>(attributes: impl Iterator<Item = (Cow<'a, str>, Option<Cow<'a, str>>)>, output: &mut String) {
    for (key, value) in attributes {
        output.push(' ');
        output.push_str(&key);
        if let Some(value) = value {
            output.push_str("=\"");
            output.push_str(&escape_html_attribute_value(&value));
            output.push('"');
        }
    }
}

/// Serialize an element to HTML string (for SVG and Math elements).
///
/// Depth-guarded by [`NATIVE_STACK_SAFE_DEPTH`] (see [`serialize_element_at_depth`]): none
/// of this module's callers track an ambient DOM depth to pass in, so the conservative
/// native-stack-safe ceiling is applied unconditionally rather than the caller-configurable
/// `effective_max_depth`.
#[allow(clippy::trivially_copy_pass_by_ref)]
// ~keep reason: used only when the visitor feature is active (PreserveHtml path) or
// ~keep inline-images feature is active (SVG serialization).
#[allow(dead_code)]
pub fn serialize_element(node_handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser) -> String {
    serialize_element_at_depth(node_handle, parser, 0)
}

/// Serialize a node to HTML string.
///
/// See [`serialize_element`] for the depth-guard contract.
#[allow(clippy::trivially_copy_pass_by_ref)]
// ~keep reason: used only when the visitor feature is active (PreserveHtml path).
#[allow(dead_code)]
pub fn serialize_node(node_handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser) -> String {
    serialize_node_at_depth(node_handle, parser, 0)
}

/// Serialize an element to HTML string, stopping descent once `depth` reaches
/// [`NATIVE_STACK_SAFE_DEPTH`].
///
/// Mutually recursive with [`serialize_node_at_depth`] over `tag.children()`, with no depth
/// bound previously — a pathologically nested "preserve raw HTML" subtree (reachable from
/// ~20 call sites across the crate, e.g. visitor `PreserveHtml` results) could overflow the
/// stack (audit #23). The element's own opening tag and attributes are always emitted; only
/// its descendants are dropped once the budget is exhausted.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn serialize_element_at_depth(
    node_handle: &crate::dom::NodeHandle,
    parser: &crate::dom::Parser,
    depth: usize,
) -> String {
    if let Some(crate::dom::Node::Tag(tag)) = node_handle.get(parser) {
        let tag_name = normalized_tag_name(tag.name().as_utf8_str());
        let mut html = String::with_capacity(256);
        html.push('<');
        html.push_str(&tag_name);

        serialize_attributes(tag, &tag_name, &mut html);

        let has_children = !tag.children().top().is_empty();
        if has_children {
            html.push('>');
            if depth >= NATIVE_STACK_SAFE_DEPTH {
                tracing::warn!(
                    target: "html_to_markdown::convert",
                    max_depth = NATIVE_STACK_SAFE_DEPTH,
                    tag = %tag_name,
                    "raw HTML serialization reached the effective depth limit; descendants were skipped"
                );
            } else {
                let children = tag.children();
                for child_handle in children.top() {
                    html.push_str(&serialize_node_at_depth(child_handle, parser, depth + 1));
                }
            }
            html.push_str("</");
            html.push_str(&tag_name);
            html.push('>');
        } else {
            html.push_str(" />");
        }
        return html;
    }
    String::new()
}

/// Serialize a node to HTML string, stopping descent once `depth` reaches
/// [`NATIVE_STACK_SAFE_DEPTH`]. See [`serialize_element_at_depth`] for the depth-guard
/// contract.
fn serialize_node_at_depth(node_handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser, depth: usize) -> String {
    if let Some(node) = node_handle.get(parser) {
        match node {
            crate::dom::Node::Raw(bytes) => bytes.as_utf8_str().to_string(),
            crate::dom::Node::Tag(_) => serialize_element_at_depth(node_handle, parser, depth),
            _ => String::new(),
        }
    } else {
        String::new()
    }
}

/// Serialize a tag to HTML, wrapping `serialize_node_to_html`.
pub fn serialize_tag_to_html(handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser) -> String {
    let mut html = String::new();
    serialize_node_to_html(handle, parser, &mut html);
    html
}

/// Recursively serialize a node to HTML.
///
/// Depth-guarded by [`NATIVE_STACK_SAFE_DEPTH`]; see [`serialize_element_at_depth`] for the
/// rationale.
#[allow(clippy::trivially_copy_pass_by_ref)]
// ~keep reason: used only when the visitor feature is active (PreserveHtml path).
#[allow(dead_code)]
pub fn serialize_node_to_html(handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser, output: &mut String) {
    serialize_node_to_html_at_depth(handle, parser, output, 0);
}

fn serialize_node_to_html_at_depth(
    handle: &crate::dom::NodeHandle,
    parser: &crate::dom::Parser,
    output: &mut String,
    depth: usize,
) {
    match handle.get(parser) {
        Some(crate::dom::Node::Tag(tag)) => {
            let tag_name = normalized_tag_name(tag.name().as_utf8_str());

            serialize_open_tag(tag, &tag_name, output);

            if depth >= NATIVE_STACK_SAFE_DEPTH {
                tracing::warn!(
                    target: "html_to_markdown::convert",
                    max_depth = NATIVE_STACK_SAFE_DEPTH,
                    tag = %tag_name,
                    "raw HTML serialization reached the effective depth limit; descendants were skipped"
                );
            } else {
                let children = tag.children();
                for child_handle in children.top() {
                    serialize_node_to_html_at_depth(child_handle, parser, output, depth + 1);
                }
            }

            if !matches!(
                tag_name.as_ref(),
                "br" | "hr"
                    | "img"
                    | "input"
                    | "meta"
                    | "link"
                    | "area"
                    | "base"
                    | "col"
                    | "embed"
                    | "param"
                    | "source"
                    | "track"
                    | "wbr"
            ) {
                output.push_str("</");
                output.push_str(&tag_name);
                output.push('>');
            }
        }
        Some(crate::dom::Node::Raw(bytes)) => {
            if let Ok(text) = std::str::from_utf8(bytes.as_bytes()) {
                output.push_str(text);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::{serialize_element, serialize_tag_to_html};

    /// ~keep audit #24 finding 3: the source HTML's `"` is valid, inert content inside a
    /// single-quoted attribute (e.g. `title='x" onclick="alert(1)" y='`). Reconstructing it
    /// into a double-quoted attribute without escaping manufactures a real `onclick` that
    /// never existed as an attribute in the original document.
    const QUOTE_BREAKING_HTML: &str = r#"<foo title='x" onclick="alert(1)" y=' data-safe="1">"#;

    #[test]
    fn should_serialize_closed_script_attributes_in_key_order_on_both_paths() {
        for _ in 0..60 {
            let dom = crate::dom::parse(
                "<script type='application/ld+json' nonce='n' data-x='v'>{}</script>",
                crate::dom::ParserOptions,
            )
            .expect("closed script");
            let handle = dom.children()[0];
            let expected = "<script data-x=\"v\" nonce=\"n\" type=\"application/ld+json\">{}</script>";
            assert_eq!(serialize_element(&handle, dom.parser()), expected);
            assert_eq!(serialize_tag_to_html(&handle, dom.parser()), expected);
        }
    }

    #[test]
    fn should_escape_a_quote_inside_serialize_element_attribute_reconstruction() {
        let dom = crate::dom::parse(QUOTE_BREAKING_HTML, crate::dom::ParserOptions).unwrap();
        let parser = dom.parser();
        let node_handle = dom
            .children()
            .iter()
            .find(|handle| matches!(handle.get(parser), Some(crate::dom::Node::Tag(_))))
            .expect("tag node");
        let result = serialize_element(node_handle, parser);
        assert_eq!(
            result,
            "<foo title=\"x&quot; onclick=&quot;alert(1)&quot; y=\" data-safe=\"1\" />"
        );
    }

    #[test]
    fn should_escape_a_quote_inside_serialize_tag_to_html_attribute_reconstruction() {
        let dom = crate::dom::parse(QUOTE_BREAKING_HTML, crate::dom::ParserOptions).unwrap();
        let parser = dom.parser();
        let node_handle = dom
            .children()
            .iter()
            .find(|handle| matches!(handle.get(parser), Some(crate::dom::Node::Tag(_))))
            .expect("tag node");
        let result = serialize_tag_to_html(node_handle, parser);
        assert_eq!(
            result,
            "<foo title=\"x&quot; onclick=&quot;alert(1)&quot; y=\" data-safe=\"1\"></foo>"
        );
    }
}