Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ All notable changes to crawlberg are documented here.
front matter now shows the decoded address, `https://example.com/it's/`. (#103)
- **A `<graphic>` embedded in the page copied its whole encoded data into the markdown.** The
`data:` rule for `<img>` now covers the addresses of `<graphic>` too. (#113)
- **Links, images and the base address were read from raw text, and a comment opener in raw text
hid the real markup after it.** A browser reads the contents of `script`, `style`, `title`,
`textarea`, `xmp`, `iframe`, `noembed`, `noframes` and `plaintext` as text. `tl` parses them as
markup, so `<script>document.write('<a href="/x">')</script>` added `/x` to the links list and a
`<base href>` inside title text changed the base for the whole page. In the other direction a
`<!--` in that text started a comment for the parser, which then swallowed every tag up to the
next `-->`: real links after it were missing from the links list altogether, not merely
mis-resolved. The `<` characters inside raw-text content are now masked before the page is
parsed, at the places an HTML parser finds that content, so link, image, feed, favicon,
heading, meta-tag and `<meta http-equiv="refresh">` extraction all see the document a browser
sees. Inside `svg` and `math` these elements are markup, as in a browser, except under svg's
`foreignObject`, `desc` and `title`; MathML's text integration points `mi`, `mo`, `mn`, `ms` and
`mtext`; and its `annotation-xml` HTML integration point. Link extraction reads `<noscript>` as
markup, as a browser without scripting does; the markdown reads it as text, as the converter
does. The base address is the first `<base href>` an HTML parser puts in the document, so one in
raw text or in `<template>` contents does not count. Title text and JSON-LD payloads are
unchanged unless they contain a literal `<`, which valid HTML writes as `&lt;`. (#124, #125,
#201)

## [1.8.0] - 2026-09-27

Expand Down
2 changes: 1 addition & 1 deletion crates/crawlberg/src/browser_detect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) fn detect_js_render_needed(body: &str, word_count: usize) -> bool {
}

let parsed_html = crate::html::mask_raw_text_markup(body);
let Ok(dom) = tl::parse(&parsed_html, ParserOptions::default()) else {
let Ok(dom) = tl::parse(&parsed_html.text, ParserOptions::default()) else {
return false;
};
let parser = dom.parser();
Expand Down
2 changes: 1 addition & 1 deletion crates/crawlberg/src/engine/crawl_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ pub(super) fn blocking_extract_page(
// ~keep Parse the masked source, never `body`: `tl` reads the contents of raw-text elements
// ~keep as markup, which both invents tags and hides real ones.
let parsed_html = mask_raw_text_markup(&body);
let (extraction, robots) = if let Ok(doc) = tl::parse(&parsed_html, ParserOptions::default()) {
let (extraction, robots) = if let Ok(doc) = tl::parse(&parsed_html.text, ParserOptions::default()) {
(
extract_page_data(&doc, &parsed_html, &parsed_url, is_html && !is_binary && !is_pdf, false),
header_robots.with_meta_tags(&doc),
Expand Down
2 changes: 1 addition & 1 deletion crates/crawlberg/src/engine/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ fn meta_refresh_target(resp: &crate::tower::CrawlResponse, current_url: &str) ->
// ~keep A `<meta http-equiv="refresh">` written inside script or style text is not a
// ~keep redirect a browser would follow, so mask raw text before looking for one.
let parsed_html = mask_raw_text_markup(&resp.body);
let target = tl::parse(&parsed_html, ParserOptions::default())
let target = tl::parse(&parsed_html.text, ParserOptions::default())
.ok()
.and_then(|doc| detect_meta_refresh(&doc))?;
Some(resolve_redirect(current_url, &target))
Expand Down
11 changes: 6 additions & 5 deletions crates/crawlberg/src/html/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use crate::types::{FeedInfo, ImageInfo, JsonLdEntry, LinkInfo, PageMetadata};
use super::feeds::{extract_favicons, extract_feeds, extract_headings, extract_hreflangs};
use super::images::extract_images;
use super::json_ld::extract_json_ld;
use super::links::extract_links;
use super::links::{effective_base_url, extract_links};
use super::metadata::extract_metadata;
use super::raw_text::MaskedHtml;

/// All data extracted from an HTML document in a single pass.
pub(crate) struct HtmlExtraction {
Expand All @@ -20,14 +21,14 @@ pub(crate) struct HtmlExtraction {
pub(crate) json_ld: Vec<JsonLdEntry>,
}

/// Extract all structured data from a parsed HTML document.
/// Extract all structured data from a parsed HTML document, `dom` parsed from `page.text`.
///
/// When `is_html` is false, returns defaults for all fields.
/// When `include_extended` is true, also extracts hreflangs, favicons,
/// headings, and word count into the metadata.
pub(crate) fn extract_page_data(
dom: &VDom<'_>,
body: &str,
page: &MaskedHtml<'_>,
base_url: &Url,
is_html: bool,
include_extended: bool,
Expand All @@ -42,7 +43,7 @@ pub(crate) fn extract_page_data(
};
}

let mut metadata = extract_metadata(dom, body);
let mut metadata = extract_metadata(dom, &page.text);

if include_extended {
let hreflangs = extract_hreflangs(dom);
Expand All @@ -60,7 +61,7 @@ pub(crate) fn extract_page_data(
metadata.word_count = Some(super::content::compute_word_count(dom));
}

let links = extract_links(dom, base_url);
let links = extract_links(dom, &effective_base_url(page.base_href.as_deref(), base_url));
let images = extract_images(dom, base_url);
let feeds = extract_feeds(dom, base_url);
let json_ld = extract_json_ld(dom);
Expand Down
80 changes: 45 additions & 35 deletions crates/crawlberg/src/html/link_targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use tracing::debug;
use url::Url;

use super::links::effective_base_url;
use super::start_tags::real_start_tags;
use super::raw_text::mask;
use super::start_tags::{RealTags, scan};

/// How an attribute holds its address.
#[derive(Clone, Copy)]
Expand Down Expand Up @@ -76,15 +77,20 @@ const INLINE_DATA_ELEMENTS: &[&str] = &["img", "video", "audio", "iframe", "sour
/// text inside `<title>`, `<textarea>`, `<script>` and the like stays as written. Every byte
/// outside a rewritten attribute is kept.
pub(crate) fn resolve_link_targets<'h>(html: &'h str, document_url: &Url) -> Cow<'h, str> {
// ~keep Scripting on, as the converter reads `<noscript>` (it drops the element).
// ~keep tl reads every `<name ...>` as a tag, even inside `<title>`, `<script>` or another
// ~keep tag's quoted value. A tag is rewritten only when this scan also ends a start tag of
// ~keep the same name at the same `>`, and the rewrite reads the scan's values.
let read = scan(html, true, |name| rewritten_attributes(name.as_bytes()));
// ~keep Parse the masked source, as link extraction does: `tl` reads raw-text content as
// ~keep markup, which both invents tags and hides real ones. Masking keeps every byte
// ~keep offset, so a span found in the masked source addresses the same bytes in `html`.
let masked = super::mask_raw_text_markup(html);
let masked = mask(html, &read.raw_text);
let Ok(dom) = tl::parse(&masked, ParserOptions::default()) else {
return Cow::Borrowed(html);
};
let base = effective_base_url(&dom, document_url);
let mut edits = collect_edits(&dom, &masked, html, &base);
let base = effective_base_url(read.base_href.as_deref(), document_url);
let mut edits = collect_edits(&dom, &masked, html, &base, &read.tags);
if edits.is_empty() {
return Cow::Borrowed(html);
}
Expand All @@ -104,16 +110,18 @@ pub(crate) fn resolve_link_targets<'h>(html: &'h str, document_url: &Url) -> Cow
/// The byte span of each attribute value that needs rewriting, with its encoded replacement.
///
/// The tags come from `dom`, parsed from `masked`, and each edit addresses `html` at the same
/// span.
/// span. Only the tags in `real_tags` are rewritten.
///
/// ~keep One pass over tl's flat node list rather than a selector query per element name:
/// ~keep each query walks the whole tree, and there are eight element names to look for.
fn collect_edits(dom: &VDom<'_>, masked: &str, html: &str, base: &Url) -> Vec<(Range<usize>, String)> {
fn collect_edits(
dom: &VDom<'_>,
masked: &str,
html: &str,
base: &Url,
real_tags: &RealTags,
) -> Vec<(Range<usize>, String)> {
let mut edits = Vec::new();
// ~keep tl reads every `<name ...>` as a tag, even inside `<title>`, `<script>` or another
// ~keep tag's quoted value. A tag is rewritten only when a real HTML parser also ends a start
// ~keep tag of the same name at the same `>`, and the rewrite reads that parser's values.
let real_tags = real_start_tags(html, |name| rewritten_attributes(name.as_bytes()));
// ~keep html-to-markdown-rs copies the base into the front matter without decoding it
// ~keep (`head_metadata.rs`, 3.14.3), so the base is written unencoded between double quotes.
// ~keep A serialized URL can hold `"`, `<` and `>` (in a host or an opaque path), and those
Expand Down Expand Up @@ -194,8 +202,7 @@ fn value_edit(html: &str, span: Range<usize>, rewritten: &str) -> (Range<usize>,
///
/// ~keep The converter reads the first copy of a repeated attribute, so a copy left after the
/// ~keep first is removed would take its place, payload and all. The spans are found in
/// ~keep `masked`, the bytes tl parsed: where the masking scan misreads a tag, the source can
/// ~keep hold a `<` there that tl read as a space, and a name looked up in the source is missed.
/// ~keep `masked`, the bytes tl parsed, where the value's span was found.
fn attribute_removals(masked: &str, span: Range<usize>, attr: &str, tag_end: usize) -> Vec<(Range<usize>, String)> {
let Some(first) = attribute_removal(masked, span.clone(), attr) else {
debug!(offset = span.start, attr, "no attribute name before a value to remove");
Expand Down Expand Up @@ -284,7 +291,7 @@ fn rewritten_attributes(element: &[u8]) -> Option<&'static [(&'static str, Shape
/// The byte span in `masked` of the attribute `attr` on the tl tag, with the value the real
/// parser gives it: decoded, with CR and CRLF made LF and NUL made U+FFFD, as a browser reads it.
///
/// ~keep The value is never read from `masked`: where the masking scan and tl disagree on where
/// ~keep The value is never read from `masked`: where the HTML parser and tl disagree on where
/// ~keep a tag ends, the masked bytes of a value can hold a masked `<`.
fn parsed_value<'p>(
tag: &tl::HTMLTag<'_>,
Expand Down Expand Up @@ -440,7 +447,6 @@ fn encode_attribute_value(value: &str, quoted: bool) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::html::decode_attr_value;

fn resolve(html: &str, document_url: &str) -> String {
let url = Url::parse(document_url).expect("valid document URL");
Expand Down Expand Up @@ -504,11 +510,6 @@ mod tests {
);
}

#[test]
fn decoding_keeps_a_double_quote_in_the_value() {
assert_eq!(decode_attr_value(r#"a"b&amp;c&#150;"#), "a\"b&c\u{2013}");
}

#[test]
fn decodes_the_base_href_before_joining() {
assert_eq!(
Expand Down Expand Up @@ -718,19 +719,6 @@ mod tests {
);
}

#[test]
fn removes_an_attribute_where_the_masking_scan_misreads_the_tag() {
// ~keep The masking scan opens a quote at the `'` of `x'y`, reads `<title>` as a tag and
// ~keep masks the `<` of `src<=`, so the bytes `tl` parsed there differ from the source.
assert_eq!(
resolve(
r#"<img b=x'y alt="'><title>" src<="data:image/png,A" x="</title>" src="data:image/png,B">"#,
"https://example.com/"
),
r#"<img b=x'y alt="'><title>" x="</title>" >"#
);
}

#[test]
fn an_equals_sign_inside_an_unquoted_value_does_not_open_a_quote() {
assert_eq!(
Expand Down Expand Up @@ -784,9 +772,9 @@ mod tests {
}

#[test]
fn a_value_is_read_from_the_source_where_the_masking_scan_misreads_a_quote() {
// ~keep The masking scan opens a quote at the `'` of `x'y` and masks `t<i` as title
// ~keep text, while `tl`, like a browser, reads all of it as the `href` value.
fn a_quote_in_an_unquoted_value_opens_no_quote() {
// ~keep The `'` of `x'y` is part of an unquoted value, so `<title>t<i</title>` sits inside
// ~keep the quoted `href` value and is not masked as title text.
assert_eq!(
resolve(
r#"<a b=x'y href="d'><title>t<i</title>">x</a>"#,
Expand All @@ -796,6 +784,28 @@ mod tests {
);
}

#[test]
fn a_quote_in_an_unquoted_value_does_not_hide_later_links() {
assert_eq!(
resolve(
r#"<p b=x'y>one</p><i c='><title>' >two</i><p>Go <a href="leaf.html">leaf</a> <img alt="icon" src="data:image/png;base64,iVBORw0KGgo="></p>"#,
"https://example.com/dir/"
),
r#"<p b=x'y>one</p><i c='><title>' >two</i><p>Go <a href="https://example.com/dir/leaf.html">leaf</a> <img alt="icon" ></p>"#
);
}

#[test]
fn a_base_inside_noscript_does_not_count() {
assert_eq!(
resolve(
r#"<head><noscript><base href="/ns/"></noscript></head><a href="leaf.html">x</a>"#,
"https://example.com/dir/page.html"
),
r#"<head><noscript><base href="/ns/"></noscript></head><a href="https://example.com/dir/leaf.html">x</a>"#
);
}

#[test]
fn resolves_each_srcset_candidate_and_keeps_its_descriptor() {
let base = Url::parse("https://example.com/p/").expect("valid URL");
Expand Down
32 changes: 16 additions & 16 deletions crates/crawlberg/src/html/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use url::Url;

use crate::types::{LinkInfo, LinkType};

use super::get_attr;
use super::selectors::SEL_A_HREF;
use super::{decode_attr_value, elements_named, get_attr};

/// Document file extensions used for link classification.
static DOCUMENT_EXTENSIONS: &[&str] = &[
Expand Down Expand Up @@ -44,22 +44,20 @@ pub(crate) fn classify_link(href: &str, base_url: &Url) -> LinkType {
}
}

/// The URL a document's relative references resolve against: the `href` of its first `<base>`
/// that has one, decoded and joined to the document URL, or the document URL itself.
pub(super) fn effective_base_url(dom: &VDom<'_>, document_url: &Url) -> Url {
elements_named(dom, "base")
.find_map(|tag| tag.attributes().get("href"))
.map(|value| value.and_then(|v| v.try_as_utf8_str()).unwrap_or(""))
// ~keep A `<base href>` is often site-relative (e.g. "/en/"); resolve it against
// the document URL instead of requiring it to already be absolute.
.and_then(|href| document_url.join(&decode_attr_value(href)).ok())
/// The URL a document's relative references resolve against: its decoded `<base href>` joined to
/// the document URL, or the document URL itself.
///
/// ~keep A `<base href>` is often site-relative (e.g. "/en/"); resolve it against the document
/// ~keep URL instead of requiring it to already be absolute.
pub(crate) fn effective_base_url(base_href: Option<&str>, document_url: &Url) -> Url {
base_href
.and_then(|href| document_url.join(href).ok())
.unwrap_or_else(|| document_url.clone())
}

/// Extract all links from a parsed HTML document.
pub(crate) fn extract_links(dom: &VDom<'_>, base_url: &Url) -> Vec<LinkInfo> {
/// Extract all links from a parsed HTML document, resolved against `effective_base`.
pub(crate) fn extract_links(dom: &VDom<'_>, effective_base: &Url) -> Vec<LinkInfo> {
let parser = dom.parser();
let effective_base = effective_base_url(dom, base_url);

let mut links = Vec::new();

Expand All @@ -84,7 +82,7 @@ pub(crate) fn extract_links(dom: &VDom<'_>, base_url: &Url) -> Vec<LinkInfo> {

// ~keep `Url::join` already resolves protocol-relative ("//host/path") references
// per the WHATWG URL spec, so no special-casing is needed here.
let link_type = classify_link(href, &effective_base);
let link_type = classify_link(href, effective_base);

let resolved_url = if let Ok(u) = effective_base.join(href) {
u.to_string()
Expand Down Expand Up @@ -113,11 +111,13 @@ mod tests {
use tl::ParserOptions;

use super::*;
use crate::html::mask_raw_text_markup;

fn extract(html: &str, base: &str) -> Vec<LinkInfo> {
let dom = tl::parse(html, ParserOptions::default()).expect("valid HTML");
let masked = mask_raw_text_markup(html);
let dom = tl::parse(&masked.text, ParserOptions::default()).expect("valid HTML");
let base_url = Url::parse(base).expect("valid base URL");
extract_links(&dom, &base_url)
extract_links(&dom, &effective_base_url(masked.base_href.as_deref(), &base_url))
}

#[test]
Expand Down
Loading