返回 CodeWhale
extract.rs
根目录 / crates / engine / src / tools / web / extract.rs
1 //! Content-type routing and readable-document extraction for web tools.
2 //!
3 //! Networking deliberately lives elsewhere. This module accepts already
4 //! fetched bytes and turns them into one normalized document so `fetch_url`
5 //! and `web.run` cannot disagree about HTML, Markdown, PDF, or media handling.
6
7 use super::adapter::{AdapterFailure, AdapterResult};
8 use super::scrape::decode_html_entities;
9 use std::sync::OnceLock;
10
11 use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};
12 use regex::Regex;
13
14 use crate::tools::spec::ToolError;
15
16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 pub enum DocumentKind {
18 Html,
19 Markdown,
20 Text,
21 Pdf,
22 Media,
23 }
24
25 #[derive(Debug, Clone)]
26 pub struct ExtractedDocument {
27 pub kind: DocumentKind,
28 pub title: Option<String>,
29 pub text: String,
30 pub markdown: String,
31 /// Readability-cleaned HTML. `web.run` consumes this to retain clickable
32 /// links while avoiding page chrome and consent-banner noise.
33 pub cleaned_html: Option<String>,
34 pub pdf_pages: Option<Vec<Vec<String>>>,
35 /// Validated extension for image/audio/video artifacts.
36 pub media_extension: Option<&'static str>,
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 struct MediaSignature {
41 extension: &'static str,
42 family: MediaFamily,
43 }
44
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 enum MediaFamily {
47 Image,
48 Audio,
49 Video,
50 }
51
52 static TITLE_RE: OnceLock<Regex> = OnceLock::new();
53 static META_RE: OnceLock<Regex> = OnceLock::new();
54 static FALLBACK_RE: OnceLock<[[Regex; 3]; 2]> = OnceLock::new();
55 static PAGE_CHROME_RE: OnceLock<[Regex; 2]> = OnceLock::new();
56 static PAGE_HEADER_RE: OnceLock<Regex> = OnceLock::new();
57 static TAG_RE: OnceLock<Regex> = OnceLock::new();
58 static WHITESPACE_RE: OnceLock<Regex> = OnceLock::new();
59
60 /// HTML's encoding declaration prescan is intentionally small. Keeping the
61 /// bound here prevents a late body string, script, or injected fragment from
62 /// changing how an already-started document is decoded.
63 const HTML_ENCODING_SNIFF_BYTES: usize = 1_024;
64
65 pub async fn extract_document(
66 url: &str,
67 content_type: Option<&str>,
68 bytes: &[u8],
69 truncated: bool,
70 context: Option<&super::super::spec::ToolContext>,
71 ) -> AdapterResult<ExtractedDocument> {
72 extract_document_with_pdf_command(
73 url,
74 content_type,
75 bytes,
76 truncated,
77 super::super::pdf::PdfTextCommand::system(context),
78 )
79 .await
80 }
81
82 pub async fn extract_document_with_pdf_command(
83 url: &str,
84 content_type: Option<&str>,
85 bytes: &[u8],
86 truncated: bool,
87 pdf_command: super::super::pdf::PdfTextCommand<'_>,
88 ) -> AdapterResult<ExtractedDocument> {
89 let context = pdf_command.context();
90 let declared = normalized_content_type(content_type);
91 let declared = declared.as_deref();
92
93 if bytes.is_empty() {
94 return Ok(ExtractedDocument {
95 kind: DocumentKind::Text,
96 title: None,
97 text: String::new(),
98 markdown: String::new(),
99 cleaned_html: None,
100 pdf_pages: None,
101 media_extension: None,
102 });
103 }
104
105 if validate_pdf_response(url, content_type, bytes)? {
106 return extract_pdf(bytes, pdf_command).await.map_err(|error| {
107 if context.is_some_and(|context| {
108 context
109 .features
110 .enabled(codewhale_runtime::features::Feature::PdfHost)
111 }) {
112 AdapterFailure::host(error)
113 } else {
114 error.into()
115 }
116 });
117 }
118
119 if let Some(signature) = sniff_media(bytes) {
120 if let Some(declared_family) = declared_media_family(declared)
121 && declared_family != signature.family
122 {
123 return Err((ToolError::execution_failed(format!(
124 "Response media type `{}` did not match its bytes",
125 declared.unwrap_or("unknown")
126 )))
127 .into());
128 }
129 return Ok(ExtractedDocument {
130 kind: DocumentKind::Media,
131 title: None,
132 text: String::new(),
133 markdown: String::new(),
134 cleaned_html: None,
135 pdf_pages: None,
136 media_extension: Some(signature.extension),
137 });
138 }
139
140 if declared_media_family(declared).is_some() {
141 return Err((ToolError::execution_failed(format!(
142 "Response claimed media type `{}`, but its bytes did not match a supported media signature",
143 declared.unwrap_or("unknown")
144 ))).into());
145 }
146
147 let sniff_html = should_sniff_html_encoding(declared, url, bytes);
148 let body = decode_response_body(bytes, content_type, sniff_html)?;
149 if sniff_html || is_html(declared, url, &body) {
150 if let Some(context) = context.filter(|context| {
151 context
152 .features
153 .enabled(codewhale_runtime::features::Feature::WebExtractHost)
154 }) {
155 return extract_html_with_host(url, &body, truncated, context).await;
156 }
157 return extract_html(url, &body, truncated).map_err(Into::into);
158 }
159 if is_markdown(declared, url) {
160 return Ok(ExtractedDocument {
161 kind: DocumentKind::Markdown,
162 title: markdown_title(&body),
163 text: body.clone(),
164 markdown: body,
165 cleaned_html: None,
166 pdf_pages: None,
167 media_extension: None,
168 });
169 }
170 if is_textual(declared, url) {
171 return Ok(ExtractedDocument {
172 kind: DocumentKind::Text,
173 title: None,
174 text: body.clone(),
175 markdown: body,
176 cleaned_html: None,
177 pdf_pages: None,
178 media_extension: None,
179 });
180 }
181
182 Err((ToolError::execution_failed(format!(
183 "Unsupported binary response type `{}`; use a dedicated download tool",
184 declared.unwrap_or("unknown")
185 )))
186 .into())
187 }
188
189 pub fn validate_pdf_response(
190 url: &str,
191 content_type: Option<&str>,
192 bytes: &[u8],
193 ) -> Result<bool, ToolError> {
194 let declared = normalized_content_type(content_type);
195 let declared = declared.as_deref();
196 let signed = looks_like_pdf(bytes);
197 if signed && declared_media_family(declared).is_some() {
198 return Err(ToolError::execution_failed(format!(
199 "Response media type `{}` did not match its PDF bytes",
200 declared.unwrap_or("unknown")
201 )));
202 }
203 let claimed = signed || declared == Some("application/pdf") || url_is_pdf(url);
204 if claimed && !signed {
205 return Err(ToolError::execution_failed(
206 "Response claimed to be a PDF, but its bytes did not contain a PDF signature",
207 ));
208 }
209 Ok(claimed)
210 }
211
212 async fn extract_html_with_host(
213 url: &str,
214 html: &str,
215 truncated: bool,
216 context: &super::super::spec::ToolContext,
217 ) -> AdapterResult<ExtractedDocument> {
218 #[derive(serde::Deserialize)]
219 #[serde(deny_unknown_fields)]
220 struct Choice {
221 kind: String,
222 candidate: Option<u8>,
223 }
224 let parsed_url = reqwest::Url::parse(url)
225 .map_err(|error| ToolError::invalid_input(format!("invalid URL: {error}")))?;
226 let candidates = main_html_candidates(html, truncated);
227 let facts=candidates.iter().map(|(id,html)| {
228 let text=html_to_plain_text(html);
229 serde_json::json!({"id":id,"non_whitespace":text.chars().filter(|value|!value.is_whitespace()).count(),"words":text.split_whitespace().count()})
230 }).collect::<Vec<_>>();
231 let budget = context
232 .turn_deadline
233 .map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now()))
234 .unwrap_or(std::time::Duration::from_secs(15));
235 let choice: Choice = super::adapter::transform(
236 crate::extension_host::StockOperation::WebExtract,
237 serde_json::json!({"candidates":facts}),
238 context,
239 budget,
240 )
241 .await?;
242 if choice.kind != "web_extract" {
243 return Err(AdapterFailure::host(ToolError::execution_failed(
244 "Web Host returned a malformed HTML region choice",
245 )));
246 }
247 let expected = candidates
248 .iter()
249 .find(|(_, html)| meaningful_html(html))
250 .map(|(id, _)| *id);
251 if choice.candidate != expected {
252 return Err(AdapterFailure::host(ToolError::execution_failed(
253 "Web Host changed mandatory readable-region order or meaningfulness",
254 )));
255 }
256 let Some(selected) = choice.candidate else {
257 return Err(js_required_error(url).into());
258 };
259 let cleaned = candidates
260 .into_iter()
261 .find(|(id, _)| *id == selected)
262 .map(|(_, html)| html)
263 .ok_or_else(|| {
264 AdapterFailure::host(ToolError::execution_failed(
265 "Web Host returned an unknown HTML region",
266 ))
267 })?;
268 document_from_html_region(url, &parsed_url, html_title(html), cleaned).map_err(Into::into)
269 }
270
271 fn extract_html(url: &str, html: &str, truncated: bool) -> Result<ExtractedDocument, ToolError> {
272 let parsed_url = reqwest::Url::parse(url)
273 .map_err(|err| ToolError::invalid_input(format!("invalid URL: {err}")))?;
274 let original_title = html_title(html);
275
276 // Readability-based extraction was removed to consolidate the HTML
277 // pipeline onto a single stack (htmd 0.5 + html5ever 0.38). The
278 // previous dual-stack (readability 0.3 / html5ever 0.26 + htmd / 0.38)
279 // compiled two incompatible html5ever/markup5ever trees. The fallback
280 // main-content regex retains the meaningful-content signal used by the
281 // tests (≥32 non-whitespace chars, ≥5 words) without the duplicate tree.
282 let cleaned_html = fallback_main_html(html, truncated).ok_or_else(|| js_required_error(url))?;
283 document_from_html_region(url, &parsed_url, original_title, cleaned_html)
284 }
285
286 fn document_from_html_region(
287 url: &str,
288 parsed_url: &reqwest::Url,
289 original_title: Option<String>,
290 cleaned_html: String,
291 ) -> Result<ExtractedDocument, ToolError> {
292 let markdown = html_to_markdown_with_base_url(&cleaned_html, parsed_url).map_err(|err| {
293 ToolError::execution_failed(format!(
294 "Failed to convert readable HTML to Markdown: {err}"
295 ))
296 })?;
297 let text = html_to_plain_text(&cleaned_html);
298
299 if !meaningful_text(&text) && !meaningful_text(&markdown) {
300 return Err(js_required_error(url));
301 }
302
303 let title = original_title;
304
305 Ok(ExtractedDocument {
306 kind: DocumentKind::Html,
307 title,
308 text,
309 markdown,
310 cleaned_html: Some(cleaned_html),
311 pdf_pages: None,
312 media_extension: None,
313 })
314 }
315
316 /// Resolve relative anchors in `htmd`'s parsed DOM, not with an HTML regex.
317 /// Absolute, fragment, non-HTTP, and malformed destinations fall through to
318 /// the built-in handler unchanged.
319 fn html_to_markdown_with_base_url(
320 html: &str,
321 base_url: &reqwest::Url,
322 ) -> Result<String, std::io::Error> {
323 let base_url = base_url.clone();
324 htmd::HtmlToMarkdown::builder()
325 .add_handler(
326 vec!["a"],
327 move |handlers: &dyn htmd::element_handler::Handlers, element: htmd::Element<'_>| {
328 let href = element.attrs.iter().find_map(|attr| {
329 (attr.name.local.as_ref() == "href").then(|| attr.value.to_string())
330 });
331 let Some(destination) = href
332 .as_deref()
333 .and_then(|href| resolve_relative_http_href(&base_url, href))
334 else {
335 return handlers.fallback(element);
336 };
337 let content = handlers.walk_children(element.node).content;
338 let trailing = &content[content.trim_end().len()..];
339 let destination = destination.replace('(', "\\(").replace(')', "\\)");
340 let title = element
341 .attrs
342 .iter()
343 .find_map(|attr| {
344 (attr.name.local.as_ref() == "title").then(|| {
345 attr.value
346 .split_whitespace()
347 .collect::<Vec<_>>()
348 .join(" ")
349 .replace('"', "\\\"")
350 })
351 })
352 .map_or_else(String::new, |title| format!(" \"{title}\""));
353 Some(format!("[{}]({destination}{title}){trailing}", content.trim()).into())
354 },
355 )
356 .build()
357 .convert(html)
358 }
359
360 fn resolve_relative_http_href(base_url: &reqwest::Url, href: &str) -> Option<String> {
361 if !matches!(base_url.scheme(), "http" | "https") {
362 return None;
363 }
364
365 let href = href.trim();
366 if href.is_empty() || href.starts_with('#') || reqwest::Url::parse(href).is_ok() {
367 return None;
368 }
369
370 base_url.join(href).ok().map(Into::into)
371 }
372
373 /// Pick the readable region of a page with bounded regexes.
374 ///
375 /// Order: every `<article>` (listing, news and forum pages carry one per
376 /// card), then `<main>`, then `<body>`. Page chrome is removed from the chosen
377 /// region; a `<header>` is chrome only at body level, because inside an
378 /// article or `<main>` it carries the title and byline. Forms are unwrapped,
379 /// not dropped: ASP.NET-style pages wrap the whole body in one `<form>`, so
380 /// only the controls themselves are stripped.
381 ///
382 /// Known limits: the lazy regexes do not balance nested same-name elements
383 /// (an `<article>` inside an `<article>` ends at the inner close tag), and no
384 /// JavaScript runs, so a client-rendered shell still yields nothing.
385 fn main_html_candidates(html: &str, truncated: bool) -> Vec<(u8, String)> {
386 let html = html
387 .rfind('<')
388 .filter(|&start| truncated && !html[start..].contains('>'))
389 .map_or(html, |start| &html[..start]);
390 let [article, main, body] = &FALLBACK_RE.get_or_init(|| {
391 [false, true].map(|open_ended| {
392 ["article", "main", "body"].map(|tag| {
393 let end = element_end(tag, open_ended);
394 Regex::new(&format!(r"(?is)<{tag}(?:\s[^>]*)?>(.*?){end}"))
395 .expect("fallback element regex")
396 })
397 })
398 })[usize::from(truncated)];
399 let articles = article
400 .captures_iter(html)
401 .filter_map(|capture| capture.get(1))
402 .map(|content| strip_page_chrome(content.as_str(), false, truncated))
403 .filter(|content| !html_to_plain_text(content).is_empty())
404 .collect::<Vec<_>>()
405 .join("\n");
406 let mut candidates = vec![(0, articles)];
407 for (id, re, strip_header) in [(1, main, false), (2, body, true)] {
408 if let Some(content) = re.captures(html).and_then(|capture| capture.get(1)) {
409 candidates.push((
410 id,
411 strip_page_chrome(content.as_str(), strip_header, truncated),
412 ));
413 }
414 }
415 candidates
416 }
417
418 fn fallback_main_html(html: &str, truncated: bool) -> Option<String> {
419 main_html_candidates(html, truncated)
420 .into_iter()
421 .find_map(|(_, html)| meaningful_html(&html).then_some(html))
422 }
423
424 fn element_end(tag: &str, open_ended: bool) -> String {
425 if open_ended {
426 format!(r"(?:</{tag}\s*>|\z)")
427 } else {
428 format!(r"</{tag}\s*>")
429 }
430 }
431
432 fn strip_page_chrome(html: &str, strip_header: bool, truncated: bool) -> String {
433 let page_chrome = &PAGE_CHROME_RE.get_or_init(|| {
434 [false, true].map(|open_ended| {
435 let block = |tag: &str| {
436 let end = element_end(tag, open_ended);
437 format!(r"<{tag}(?:\s[^>]*)?>.*?{end}")
438 };
439 Regex::new(&format!(
440 "(?is)(?:{}|{}|{}{}",
441 block("script"),
442 block("style"),
443 block("noscript"),
444 concat!(
445 r"|<nav(?:\s[^>]*)?>.*?</nav\s*>",
446 r"|<footer(?:\s[^>]*)?>.*?</footer\s*>",
447 r"|<aside(?:\s[^>]*)?>.*?</aside\s*>",
448 // Form controls, and the form tags themselves (unwrapped).
449 r"|<select(?:\s[^>]*)?>.*?</select\s*>",
450 r"|<textarea(?:\s[^>]*)?>.*?</textarea\s*>",
451 r"|<button(?:\s[^>]*)?>.*?</button\s*>",
452 r"|<input(?:\s[^>]*)?>",
453 r"|</?form(?:\s[^>]*)?>)",
454 ),
455 ))
456 .expect("page chrome regex")
457 })
458 })[usize::from(truncated)];
459 let cleaned = page_chrome.replace_all(html, "");
460 if !strip_header {
461 return cleaned.into_owned();
462 }
463 PAGE_HEADER_RE
464 .get_or_init(|| {
465 Regex::new(r"(?is)<header(?:\s[^>]*)?>.*?</header\s*>").expect("page header regex")
466 })
467 .replace_all(&cleaned, "")
468 .into_owned()
469 }
470
471 fn meaningful_html(html: &str) -> bool {
472 meaningful_text(&html_to_plain_text(html))
473 }
474
475 fn meaningful_text(text: &str) -> bool {
476 text.chars().filter(|ch| !ch.is_whitespace()).count() >= 32
477 && text.split_whitespace().count() >= 5
478 }
479
480 fn html_to_plain_text(html: &str) -> String {
481 let without_tags = TAG_RE
482 .get_or_init(|| Regex::new(r"(?s)<[^>]+>").expect("tag regex"))
483 .replace_all(html, " ");
484 normalize_text(&decode_html_entities(&without_tags))
485 }
486
487 fn normalize_text(text: &str) -> String {
488 WHITESPACE_RE
489 .get_or_init(|| Regex::new(r"\s+").expect("whitespace regex"))
490 .replace_all(text.trim(), " ")
491 .into_owned()
492 }
493
494 fn html_title(html: &str) -> Option<String> {
495 let capture = TITLE_RE
496 .get_or_init(|| {
497 Regex::new(r"(?is)<title(?:\s[^>]*)?>(.*?)</title\s*>").expect("title regex")
498 })
499 .captures(html)?;
500 let title = normalize_text(&decode_html_entities(capture.get(1)?.as_str()));
501 (!title.is_empty()).then_some(title)
502 }
503
504 pub fn head_summary(
505 url: &str,
506 content_type: Option<&str>,
507 bytes: &[u8],
508 ) -> Option<ExtractedDocument> {
509 let declared = normalized_content_type(content_type);
510 let sniff_html = should_sniff_html_encoding(declared.as_deref(), url, bytes);
511 let html = decode_response_body(bytes, content_type, sniff_html).ok()?;
512 let title = html_title(&html).or_else(|| meta_content(&html, "property", "og:title"));
513 let description = meta_content(&html, "name", "description")
514 .or_else(|| meta_content(&html, "property", "og:description"));
515 let text = [title.as_deref(), description.as_deref()]
516 .into_iter()
517 .flatten()
518 .collect::<Vec<_>>()
519 .join("\n\n");
520 if text.is_empty() {
521 return None;
522 }
523 let markdown = if title.is_some() {
524 format!("# {text}")
525 } else {
526 text.clone()
527 };
528 Some(ExtractedDocument {
529 kind: DocumentKind::Text,
530 title,
531 text,
532 markdown,
533 cleaned_html: None,
534 pdf_pages: None,
535 media_extension: None,
536 })
537 }
538
539 fn meta_content(html: &str, attribute: &str, key: &str) -> Option<String> {
540 META_RE
541 .get_or_init(|| Regex::new(r"(?is)<meta\s[^>]*>").expect("meta regex"))
542 .find_iter(html)
543 .find_map(|tag| {
544 let tag = tag.as_str();
545 html_attribute_value(tag, attribute)
546 .filter(|value| value.eq_ignore_ascii_case(key))
547 .and_then(|_| html_attribute_value(tag, "content"))
548 .map(|content| normalize_text(&decode_html_entities(&content)))
549 .filter(|content| !content.is_empty())
550 })
551 }
552
553 fn markdown_title(body: &str) -> Option<String> {
554 body.lines().find_map(|line| {
555 let title = line.trim().strip_prefix("# ")?.trim();
556 (!title.is_empty()).then(|| title.to_string())
557 })
558 }
559
560 /// Stable prefix for "the response parsed, but carried no readable body".
561 ///
562 /// The fetch pipeline matches on this to decide whether a cache-busting
563 /// re-fetch is worth one more request, and to attach the role-aware recovery
564 /// text. Extraction itself has no `ToolContext`, so it cannot know which
565 /// escalation the calling role actually owns; it states the fact and leaves
566 /// the remedy to [`super::fetch`].
567 pub const JS_SHELL_MARKER: &str = "No readable page content was found at";
568
569 /// Whether `error` is the JS-shell extraction failure (a parsed response whose
570 /// body held no readable content), as opposed to a transport or type failure.
571 pub fn is_js_shell_error(error: &ToolError) -> bool {
572 error.to_string().contains(JS_SHELL_MARKER)
573 }
574
575 fn js_required_error(url: &str) -> ToolError {
576 ToolError::execution_failed(format!(
577 "{JS_SHELL_MARKER} {url}; the response parsed but its body held no readable content, so the page may require JavaScript."
578 ))
579 }
580
581 /// Decode one response body without guessing from language statistics.
582 ///
583 /// Precedence is receipt-grade and deterministic: BOM, recognized transport
584 /// charset, an HTML-only bounded meta prescan, then UTF-8. Unknown transport
585 /// labels deliberately fall through to a valid HTML declaration. `html_sniff`
586 /// must come from MIME/URL/ASCII markup evidence; JSON and plain text callers
587 /// pass `false`, so a body string cannot impersonate an HTML declaration.
588 pub fn decode_response_body(
589 bytes: &[u8],
590 content_type: Option<&str>,
591 html_sniff: bool,
592 ) -> Result<String, ToolError> {
593 if let Some((encoding, bom_len)) = Encoding::for_bom(bytes) {
594 let (decoded, _) = encoding.decode_without_bom_handling(&bytes[bom_len..]);
595 reject_binary_nul(bytes, encoding, &decoded)?;
596 return Ok(decoded.into_owned());
597 }
598
599 let transport_encoding = content_type.and_then(content_type_encoding);
600 let encoding = transport_encoding
601 .or_else(|| html_sniff.then(|| html_meta_encoding(bytes)).flatten())
602 .unwrap_or(UTF_8);
603 let (decoded, _) = encoding.decode_without_bom_handling(bytes);
604 reject_binary_nul(bytes, encoding, &decoded)?;
605 Ok(decoded.into_owned())
606 }
607
608 fn reject_binary_nul(
609 bytes: &[u8],
610 encoding: &'static Encoding,
611 decoded: &str,
612 ) -> Result<(), ToolError> {
613 // UTF-16 uses zero bytes structurally for many characters, so inspect its
614 // decoded scalar values. Every other encoding must be NUL-free across the
615 // complete response; neither a BOM nor a late byte may bypass the guard.
616 let contains_nul = if encoding == UTF_16LE || encoding == UTF_16BE {
617 decoded.contains('\0')
618 } else {
619 bytes.contains(&0)
620 };
621 if contains_nul {
622 return Err(ToolError::execution_failed(
623 "Unsupported binary response contained NUL bytes",
624 ));
625 }
626 Ok(())
627 }
628
629 /// Parse only exact semicolon-delimited `charset` parameters. A random
630 /// `charset=` substring inside another parameter is not transport authority.
631 fn content_type_encoding(value: &str) -> Option<&'static Encoding> {
632 value.split(';').skip(1).find_map(|parameter| {
633 let (name, raw_value) = parameter.split_once('=')?;
634 if !name.trim().eq_ignore_ascii_case("charset") {
635 return None;
636 }
637 let value = raw_value.trim();
638 let value = match (value.as_bytes().first(), value.as_bytes().last()) {
639 (Some(b'"'), Some(b'"')) | (Some(b'\''), Some(b'\'')) if value.len() >= 2 => {
640 &value[1..value.len() - 1]
641 }
642 _ if value.contains('"') || value.contains('\'') => return None,
643 _ => value,
644 };
645 let label = value.trim();
646 (!label.is_empty())
647 .then(|| Encoding::for_label(label.as_bytes()))
648 .flatten()
649 })
650 }
651
652 fn should_sniff_html_encoding(content_type: Option<&str>, url: &str, bytes: &[u8]) -> bool {
653 match content_type {
654 Some("text/html" | "application/xhtml+xml") => true,
655 // Explicit non-HTML text and structured formats never consult markup
656 // embedded in their body.
657 Some(value) if value.starts_with("text/") || is_structured_text_type(value) => false,
658 Some("application/octet-stream") | None => {
659 url_path_ends_with(url, &[".html", ".htm"]) || looks_like_html_bytes(bytes)
660 }
661 Some(_) => false,
662 }
663 }
664
665 fn is_structured_text_type(content_type: &str) -> bool {
666 content_type.contains("json")
667 || content_type.contains("xml")
668 || content_type.contains("yaml")
669 || content_type.contains("javascript")
670 }
671
672 fn looks_like_html_bytes(bytes: &[u8]) -> bool {
673 let start = Encoding::for_bom(bytes).map_or(0, |(_, length)| length);
674 let end = bytes
675 .len()
676 .min(start.saturating_add(HTML_ENCODING_SNIFF_BYTES));
677 let ascii = ascii_lowercase_projection(&bytes[start..end]);
678 let Some(prefix) = html_prefix_after_leading_declarations(&ascii) else {
679 return false;
680 };
681 prefix.starts_with("<!doctype html")
682 || prefix.starts_with("<html")
683 || prefix.starts_with("<head")
684 || prefix.starts_with("<meta")
685 }
686
687 fn html_prefix_after_leading_declarations(mut prefix: &str) -> Option<&str> {
688 loop {
689 prefix = prefix.trim_start();
690 if let Some(comment) = prefix.strip_prefix("<!--") {
691 let end = comment.find("-->")?;
692 prefix = &comment[end + 3..];
693 continue;
694 }
695 if let Some(declaration) = prefix.strip_prefix("<?xml") {
696 let end = declaration.find("?>")?;
697 prefix = &declaration[end + 2..];
698 continue;
699 }
700 return Some(prefix);
701 }
702 }
703
704 fn html_meta_encoding(bytes: &[u8]) -> Option<&'static Encoding> {
705 let sniff_len = bytes.len().min(HTML_ENCODING_SNIFF_BYTES);
706 let html = ascii_lowercase_projection(&bytes[..sniff_len]);
707 let mut cursor = 0usize;
708
709 while let Some(relative) = html[cursor..].find('<') {
710 let start = cursor + relative;
711 if html[start..].starts_with("<!--") {
712 cursor = html[start + 4..]
713 .find("-->")
714 .map_or(html.len(), |end| start + 4 + end + 3);
715 continue;
716 }
717 if tag_starts_at(&html, start, "script") || tag_starts_at(&html, start, "style") {
718 let name = if tag_starts_at(&html, start, "script") {
719 "script"
720 } else {
721 "style"
722 };
723 let close = format!("</{name}");
724 cursor = html[start..]
725 .find(&close)
726 .and_then(|close_start| {
727 html[start + close_start..]
728 .find('>')
729 .map(|end| start + close_start + end + 1)
730 })
731 .unwrap_or(html.len());
732 continue;
733 }
734 if !tag_starts_at(&html, start, "meta") {
735 cursor = start + 1;
736 continue;
737 }
738 let relative_end = html[start..].find('>')?;
739 let end = start + relative_end + 1;
740 let tag = &html[start..end];
741 if let Some(label) = html_attribute_value(tag, "charset")
742 && let Some(encoding) = Encoding::for_label(label.as_bytes())
743 {
744 return Some(normalize_meta_encoding(encoding));
745 }
746 let is_content_type = html_attribute_value(tag, "http-equiv")
747 .is_some_and(|value| value.eq_ignore_ascii_case("content-type"));
748 if is_content_type
749 && let Some(content) = html_attribute_value(tag, "content")
750 && let Some(encoding) = content_type_encoding(&content)
751 {
752 return Some(normalize_meta_encoding(encoding));
753 }
754 cursor = end;
755 }
756 None
757 }
758
759 fn normalize_meta_encoding(encoding: &'static Encoding) -> &'static Encoding {
760 if encoding == UTF_16LE || encoding == UTF_16BE {
761 UTF_8
762 } else {
763 encoding
764 }
765 }
766
767 fn ascii_lowercase_projection(bytes: &[u8]) -> String {
768 bytes
769 .iter()
770 .map(|byte| {
771 if byte.is_ascii() {
772 char::from(byte.to_ascii_lowercase())
773 } else {
774 ' '
775 }
776 })
777 .collect()
778 }
779
780 fn tag_starts_at(html: &str, start: usize, name: &str) -> bool {
781 let Some(after_name) = html.get(start + 1 + name.len()..) else {
782 return false;
783 };
784 html[start + 1..].starts_with(name)
785 && after_name
786 .chars()
787 .next()
788 .is_some_and(|ch| ch.is_ascii_whitespace() || matches!(ch, '/' | '>'))
789 }
790
791 fn html_attribute_value(tag: &str, wanted: &str) -> Option<String> {
792 let bytes = tag.as_bytes();
793 let mut cursor = 1usize;
794 while cursor < bytes.len() && !bytes[cursor].is_ascii_whitespace() && bytes[cursor] != b'>' {
795 cursor += 1;
796 }
797 while cursor < bytes.len() {
798 while cursor < bytes.len() && (bytes[cursor].is_ascii_whitespace() || bytes[cursor] == b'/')
799 {
800 cursor += 1;
801 }
802 if cursor >= bytes.len() || bytes[cursor] == b'>' {
803 break;
804 }
805 let name_start = cursor;
806 while cursor < bytes.len()
807 && !bytes[cursor].is_ascii_whitespace()
808 && !matches!(bytes[cursor], b'=' | b'/' | b'>')
809 {
810 cursor += 1;
811 }
812 let name = &tag[name_start..cursor];
813 while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
814 cursor += 1;
815 }
816 if cursor >= bytes.len() || bytes[cursor] != b'=' {
817 continue;
818 }
819 cursor += 1;
820 while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
821 cursor += 1;
822 }
823 if cursor >= bytes.len() {
824 break;
825 }
826 let (value_start, value_end) = if matches!(bytes[cursor], b'"' | b'\'') {
827 let quote = bytes[cursor];
828 cursor += 1;
829 let start = cursor;
830 while cursor < bytes.len() && bytes[cursor] != quote {
831 cursor += 1;
832 }
833 let end = cursor;
834 cursor = cursor.saturating_add(1);
835 (start, end)
836 } else {
837 let start = cursor;
838 while cursor < bytes.len()
839 && !bytes[cursor].is_ascii_whitespace()
840 && bytes[cursor] != b'>'
841 {
842 cursor += 1;
843 }
844 (start, cursor)
845 };
846 if name.eq_ignore_ascii_case(wanted) {
847 return Some(tag[value_start..value_end].trim().to_string());
848 }
849 }
850 None
851 }
852
853 fn normalized_content_type(content_type: Option<&str>) -> Option<String> {
854 content_type
855 .and_then(|value| value.split(';').next())
856 .map(str::trim)
857 .filter(|value| !value.is_empty())
858 .map(str::to_ascii_lowercase)
859 }
860
861 fn is_html(content_type: Option<&str>, url: &str, body: &str) -> bool {
862 matches!(content_type, Some("text/html" | "application/xhtml+xml"))
863 || url_path_ends_with(url, &[".html", ".htm"])
864 || {
865 let prefix = body.trim_start().chars().take(64).collect::<String>();
866 let prefix = prefix.to_ascii_lowercase();
867 prefix.contains("<!doctype html") || prefix.contains("<html")
868 }
869 }
870
871 fn is_markdown(content_type: Option<&str>, url: &str) -> bool {
872 matches!(
873 content_type,
874 Some("text/markdown" | "text/x-markdown" | "application/markdown")
875 ) || url_path_ends_with(url, &[".md", ".markdown"])
876 }
877
878 fn is_textual(content_type: Option<&str>, url: &str) -> bool {
879 content_type.is_some_and(|value| {
880 value.starts_with("text/")
881 || value.contains("json")
882 || value.contains("xml")
883 || value.contains("yaml")
884 || value.contains("javascript")
885 || value == "application/sql"
886 }) || url_path_ends_with(
887 url,
888 &[
889 ".txt", ".json", ".jsonl", ".xml", ".yaml", ".yml", ".csv", ".tsv", ".rs", ".py",
890 ".js", ".ts", ".toml",
891 ],
892 )
893 }
894
895 fn url_is_pdf(url: &str) -> bool {
896 url_path_ends_with(url, &[".pdf"])
897 }
898
899 fn url_path_ends_with(url: &str, extensions: &[&str]) -> bool {
900 reqwest::Url::parse(url)
901 .ok()
902 .map(|parsed| parsed.path().to_ascii_lowercase())
903 .is_some_and(|path| extensions.iter().any(|extension| path.ends_with(extension)))
904 }
905
906 fn looks_like_pdf(bytes: &[u8]) -> bool {
907 bytes.starts_with(b"%PDF-")
908 }
909
910 fn declared_media_family(content_type: Option<&str>) -> Option<MediaFamily> {
911 let content_type = content_type?;
912 if content_type.starts_with("image/") {
913 Some(MediaFamily::Image)
914 } else if content_type.starts_with("audio/") {
915 Some(MediaFamily::Audio)
916 } else if content_type.starts_with("video/") {
917 Some(MediaFamily::Video)
918 } else {
919 None
920 }
921 }
922
923 fn sniff_media(bytes: &[u8]) -> Option<MediaSignature> {
924 let trimmed = bytes
925 .iter()
926 .position(|byte| !byte.is_ascii_whitespace())
927 .map(|start| &bytes[start..])
928 .unwrap_or(bytes);
929 let signature = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
930 MediaSignature {
931 extension: "png",
932 family: MediaFamily::Image,
933 }
934 } else if bytes.starts_with(b"\xff\xd8\xff") {
935 MediaSignature {
936 extension: "jpg",
937 family: MediaFamily::Image,
938 }
939 } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
940 MediaSignature {
941 extension: "gif",
942 family: MediaFamily::Image,
943 }
944 } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
945 MediaSignature {
946 extension: "webp",
947 family: MediaFamily::Image,
948 }
949 } else if bytes.starts_with(b"ID3") || bytes.starts_with(b"\xff\xfb") {
950 MediaSignature {
951 extension: "mp3",
952 family: MediaFamily::Audio,
953 }
954 } else if bytes.starts_with(b"fLaC") {
955 MediaSignature {
956 extension: "flac",
957 family: MediaFamily::Audio,
958 }
959 } else if bytes.starts_with(b"OggS") {
960 MediaSignature {
961 extension: "ogg",
962 family: MediaFamily::Audio,
963 }
964 } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" {
965 MediaSignature {
966 extension: "wav",
967 family: MediaFamily::Audio,
968 }
969 } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
970 MediaSignature {
971 extension: "mp4",
972 family: MediaFamily::Video,
973 }
974 } else if bytes.starts_with(b"\x1aE\xdf\xa3") {
975 MediaSignature {
976 extension: "webm",
977 family: MediaFamily::Video,
978 }
979 } else if trimmed.starts_with(b"<svg")
980 || (trimmed.starts_with(b"<?xml")
981 && trimmed
982 .windows(4)
983 .take(1_024)
984 .any(|window| window.eq_ignore_ascii_case(b"<svg")))
985 {
986 MediaSignature {
987 extension: "svg",
988 family: MediaFamily::Image,
989 }
990 } else {
991 return None;
992 };
993 Some(signature)
994 }
995
996 async fn extract_pdf(
997 bytes: &[u8],
998 command: super::super::pdf::PdfTextCommand<'_>,
999 ) -> Result<ExtractedDocument, ToolError> {
1000 let text = super::super::pdf::extract_bytes(bytes, None, command)
1001 .await
1002 .map_err(super::super::pdf::into_tool_error)?;
1003 let pages = split_pdf_pages(&text);
1004 let text = pages
1005 .iter()
1006 .map(|page| page.join("\n"))
1007 .collect::<Vec<_>>()
1008 .join("\n\n");
1009 Ok(ExtractedDocument {
1010 kind: DocumentKind::Pdf,
1011 title: Some("PDF Document".to_string()),
1012 markdown: text.clone(),
1013 text,
1014 cleaned_html: None,
1015 pdf_pages: Some(pages),
1016 media_extension: None,
1017 })
1018 }
1019
1020 fn split_pdf_pages(text: &str) -> Vec<Vec<String>> {
1021 text.split('\x0C')
1022 .map(|page| {
1023 page.lines()
1024 .map(str::trim)
1025 .filter(|line| !line.is_empty())
1026 .map(ToOwned::to_owned)
1027 .collect::<Vec<_>>()
1028 })
1029 .collect()
1030 }
1031
1032 #[cfg(test)]
1033 mod tests {
1034 use super::*;
1035
1036 #[test]
1037 fn html_to_plain_text_does_not_double_decode_escaped_entities() {
1038 assert_eq!(
1039 html_to_plain_text("<p>Use &amp;lt;br&amp;gt; here</p>"),
1040 "Use &lt;br&gt; here"
1041 );
1042 assert_eq!(
1043 html_title("<title>&amp;quot;quoted&amp;quot;</title>").as_deref(),
1044 Some("&quot;quoted&quot;")
1045 );
1046 }
1047
1048 #[tokio::test]
1049 async fn html_becomes_readable_markdown_without_page_chrome() {
1050 let html = br#"<!doctype html><html><head><title>Whale &amp; Signal</title></head><body>
1051 <nav>Products Pricing Log in Cookies</nav>
1052 <article><h1>Fetch once</h1><p>This is the important article body with enough words to be useful.</p>
1053 <a href="/proof">Read the proof</a></article>
1054 <footer>Privacy Cookies Terms</footer></body></html>"#;
1055 let document = extract_document(
1056 "https://example.com/post",
1057 Some("text/html"),
1058 html,
1059 false,
1060 None,
1061 )
1062 .await
1063 .expect("extract html");
1064
1065 assert_eq!(document.kind, DocumentKind::Html);
1066 assert_eq!(document.title.as_deref(), Some("Whale & Signal"));
1067 assert!(document.markdown.contains("Fetch once") || document.title.is_some());
1068 assert!(
1069 document
1070 .markdown
1071 .contains("[Read the proof](https://example.com/proof)")
1072 );
1073 assert!(!document.markdown.contains("Products Pricing"));
1074 assert!(!document.markdown.contains("Privacy Cookies"));
1075 }
1076
1077 #[test]
1078 fn relative_http_href_resolution_preserves_other_destination_kinds() {
1079 let base = reqwest::Url::parse("https://example.com/guides/page").expect("base URL");
1080 assert_eq!(
1081 resolve_relative_http_href(&base, "../proof?q=1#receipt").as_deref(),
1082 Some("https://example.com/proof?q=1#receipt")
1083 );
1084 for href in [
1085 "#receipt",
1086 "mailto:maintainer@example.com",
1087 "data:text/plain,proof",
1088 "codewhale:session/123",
1089 "https://other.example/proof",
1090 "http://[::1",
1091 "",
1092 ] {
1093 assert_eq!(
1094 resolve_relative_http_href(&base, href),
1095 None,
1096 "destination must be left to htmd unchanged: {href:?}"
1097 );
1098 }
1099 let file = reqwest::Url::parse("file:///tmp/page").expect("file URL");
1100 assert!(resolve_relative_http_href(&file, "proof").is_none());
1101 }
1102
1103 #[tokio::test]
1104 async fn sparse_document_uses_article_fallback() {
1105 let html = br#"<html><head><title>Fallback</title></head><body><nav>cookie banner</nav>
1106 <article><h2>Small source</h2><p>Five useful words survive this compact article fallback path.</p></article>
1107 </body></html>"#;
1108 let document = extract_document(
1109 "https://example.com/short",
1110 Some("text/html"),
1111 html,
1112 false,
1113 None,
1114 )
1115 .await
1116 .expect("extract fallback");
1117
1118 assert!(document.markdown.contains("## Small source"));
1119 assert!(!document.markdown.contains("cookie banner"));
1120 }
1121
1122 #[tokio::test]
1123 async fn javascript_shell_returns_actionable_error() {
1124 let error = extract_document(
1125 "https://example.com/app",
1126 Some("text/html"),
1127 b"<html><body><div id='root'></div><script>boot()</script></body></html>",
1128 false,
1129 None,
1130 )
1131 .await
1132 .expect_err("empty app shell must fail");
1133
1134 let message = error.to_string();
1135 assert!(message.contains("may require JavaScript"), "{message}");
1136 assert!(
1137 message.contains("https://example.com/app"),
1138 "the shell failure must name the URL: {message}"
1139 );
1140 assert!(
1141 is_js_shell_error(&error.error),
1142 "the fetch pipeline recognizes this failure by marker: {message}"
1143 );
1144 assert!(
1145 !is_js_shell_error(&ToolError::execution_failed("connection reset")),
1146 "transport failures must not look like a JS shell"
1147 );
1148 }
1149
1150 #[tokio::test]
1151 async fn markdown_passes_through_unchanged() {
1152 let body = b"# Release note\n\nA complete markdown response remains intact.\n";
1153 let document = extract_document(
1154 "https://example.com/release.md",
1155 Some("text/markdown; charset=utf-8"),
1156 body,
1157 false,
1158 None,
1159 )
1160 .await
1161 .expect("extract markdown");
1162
1163 assert_eq!(document.kind, DocumentKind::Markdown);
1164 assert_eq!(document.markdown.as_bytes(), body);
1165 assert_eq!(document.title.as_deref(), Some("Release note"));
1166 }
1167
1168 #[tokio::test]
1169 async fn media_requires_matching_magic_bytes() {
1170 let error = extract_document(
1171 "https://example.com/not-image.png",
1172 Some("image/png"),
1173 b"<html>not really an image</html>",
1174 false,
1175 None,
1176 )
1177 .await
1178 .expect_err("spoofed media must fail");
1179 assert!(error.to_string().contains("did not match"));
1180
1181 let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
1182 png.extend_from_slice(b"fake test payload");
1183 let document = extract_document(
1184 "https://example.com/image",
1185 Some("application/octet-stream"),
1186 &png,
1187 false,
1188 None,
1189 )
1190 .await
1191 .expect("sniff png");
1192 assert_eq!(document.kind, DocumentKind::Media);
1193 assert_eq!(document.media_extension, Some("png"));
1194 }
1195
1196 #[tokio::test]
1197 async fn arbitrary_binary_is_rejected() {
1198 let error = extract_document(
1199 "https://example.com/archive.bin",
1200 Some("application/octet-stream"),
1201 b"PK\x03\x04archive bytes",
1202 false,
1203 None,
1204 )
1205 .await
1206 .expect_err("archive must be rejected");
1207 assert!(error.to_string().contains("Unsupported binary response"));
1208 }
1209
1210 #[tokio::test]
1211 async fn empty_success_body_is_valid_text() {
1212 let document = extract_document(
1213 "https://example.com/no-content",
1214 Some("application/octet-stream"),
1215 b"",
1216 false,
1217 None,
1218 )
1219 .await
1220 .expect("empty body");
1221 assert_eq!(document.kind, DocumentKind::Text);
1222 assert!(document.text.is_empty());
1223 }
1224
1225 #[tokio::test]
1226 async fn content_type_matching_is_case_insensitive() {
1227 let document = extract_document(
1228 "https://example.com/document",
1229 Some("Application/JSON; Charset=UTF-8"),
1230 br#"{"status":"ok"}"#,
1231 false,
1232 None,
1233 )
1234 .await
1235 .expect("mixed-case JSON content type");
1236
1237 assert_eq!(document.kind, DocumentKind::Text);
1238 assert_eq!(document.text, r#"{"status":"ok"}"#);
1239 }
1240
1241 #[test]
1242 fn bom_wins_over_conflicting_transport_and_is_removed() {
1243 let mut utf8 = b"\xef\xbb\xbf".to_vec();
1244 utf8.extend_from_slice("café".as_bytes());
1245 assert_eq!(
1246 decode_response_body(&utf8, Some("text/html; charset=windows-1252"), true)
1247 .expect("UTF-8 BOM"),
1248 "café"
1249 );
1250
1251 let mut utf16 = vec![0xff, 0xfe];
1252 for unit in "BOM 日本語".encode_utf16() {
1253 utf16.extend_from_slice(&unit.to_le_bytes());
1254 }
1255 assert_eq!(
1256 decode_response_body(&utf16, Some("text/plain; charset=windows-1252"), false)
1257 .expect("UTF-16 BOM"),
1258 "BOM 日本語"
1259 );
1260 }
1261
1262 #[test]
1263 fn content_type_charset_is_exact_recognized_and_order_independent() {
1264 let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode("café");
1265 for content_type in [
1266 "text/plain; charset=windows-1252",
1267 "TEXT/PLAIN; boundary=x; CHARSET = \"windows-1252\"; q=1",
1268 "text/plain; q=1; charset='windows-1252'",
1269 ] {
1270 assert_eq!(
1271 decode_response_body(&bytes, Some(content_type), false).expect("declared charset"),
1272 "café",
1273 "{content_type}"
1274 );
1275 }
1276
1277 for malformed in [
1278 "text/plain; note=charset=windows-1252",
1279 "text/plain; charset=\"windows-1252",
1280 "text/plain; charset=definitely-not-an-encoding",
1281 ] {
1282 let decoded =
1283 decode_response_body(&bytes, Some(malformed), false).expect("UTF-8 fallback");
1284 assert!(decoded.contains('\u{fffd}'), "{malformed}: {decoded}");
1285 }
1286 }
1287
1288 #[test]
1289 fn invalid_header_falls_through_to_direct_and_legacy_html_meta() {
1290 let direct = r#"<html><head><meta charset="gbk"></head><body>中文</body></html>"#;
1291 let (direct_bytes, _, _) = encoding_rs::GBK.encode(direct);
1292 assert!(
1293 decode_response_body(&direct_bytes, Some("text/html; charset=not-real"), true,)
1294 .expect("direct meta")
1295 .contains("中文")
1296 );
1297
1298 let legacy = r#"<html><head><meta content="text/html; charset=windows-1252" http-equiv="Content-Type"></head><body>café</body></html>"#;
1299 let (legacy_bytes, _, _) = encoding_rs::WINDOWS_1252.encode(legacy);
1300 assert!(
1301 decode_response_body(&legacy_bytes, Some("text/html"), true)
1302 .expect("legacy meta")
1303 .contains("café")
1304 );
1305 }
1306
1307 #[test]
1308 fn recognized_transport_charset_beats_conflicting_meta() {
1309 let html = r#"<html><head><meta charset="shift_jis"></head><body>中文</body></html>"#;
1310 let (bytes, _, _) = encoding_rs::GBK.encode(html);
1311 let decoded = decode_response_body(&bytes, Some("text/html; charset=gbk"), true)
1312 .expect("transport charset");
1313 assert!(decoded.contains("中文"), "{decoded}");
1314 }
1315
1316 #[test]
1317 fn html_prescan_ignores_comments_scripts_and_late_meta() {
1318 let cases = [
1319 "<!-- <meta charset=windows-1252> --><html><body>café</body></html>".to_string(),
1320 "<script>\"<meta charset=windows-1252>\"</script><html><body>café</body></html>"
1321 .to_string(),
1322 format!(
1323 "<html><head>{}<meta charset=windows-1252></head><body>café</body></html>",
1324 " ".repeat(HTML_ENCODING_SNIFF_BYTES)
1325 ),
1326 ];
1327 for html in cases {
1328 let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode(&html);
1329 let decoded = decode_response_body(&bytes, Some("text/html"), true)
1330 .expect("bounded HTML fallback");
1331 assert!(
1332 decoded.contains('\u{fffd}'),
1333 "late/ignored meta changed decoding: {decoded}"
1334 );
1335 }
1336 }
1337
1338 #[test]
1339 fn non_html_bodies_never_sniff_meta_markup() {
1340 let plain = "literal <meta charset=windows-1252> café";
1341 let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode(plain);
1342 for content_type in ["text/plain", "application/json"] {
1343 let decoded = decode_response_body(&bytes, Some(content_type), false)
1344 .expect("non-HTML UTF-8 fallback");
1345 assert!(decoded.contains('\u{fffd}'), "{content_type}: {decoded}");
1346 }
1347 }
1348
1349 #[test]
1350 fn declared_gbk_shift_jis_and_windows_1252_decode_deterministically() {
1351 let cases = [
1352 (encoding_rs::GBK, "中文", "gbk"),
1353 (encoding_rs::SHIFT_JIS, "日本語", "shift_jis"),
1354 (encoding_rs::WINDOWS_1252, "café", "windows-1252"),
1355 ];
1356 for (encoding, text, label) in cases {
1357 let (bytes, _, had_errors) = encoding.encode(text);
1358 assert!(!had_errors, "fixture must be representable in {label}");
1359 assert_eq!(
1360 decode_response_body(&bytes, Some(&format!("text/plain; charset={label}")), false,)
1361 .expect("decode declared encoding"),
1362 text
1363 );
1364 }
1365 }
1366
1367 #[test]
1368 fn nul_binary_is_rejected_but_utf16_bom_text_is_not() {
1369 let error = decode_response_body(b"PK\0\x03\x04archive", Some("text/plain"), false)
1370 .expect_err("NUL binary must fail");
1371 assert!(error.to_string().contains("NUL bytes"));
1372
1373 let bom_binary = b"\xef\xbb\xbfapparently text\0binary";
1374 let error = decode_response_body(bom_binary, Some("text/plain"), false)
1375 .expect_err("a BOM must not bypass the NUL guard");
1376 assert!(error.to_string().contains("NUL bytes"));
1377
1378 let mut late_binary = vec![b'x'; 8_193];
1379 late_binary.push(0);
1380 let error = decode_response_body(&late_binary, Some("text/plain"), false)
1381 .expect_err("a late NUL must not bypass the full-body guard");
1382 assert!(error.to_string().contains("NUL bytes"));
1383
1384 let utf16 = [0xff, 0xfe, b'O', 0, b'K', 0];
1385 assert_eq!(
1386 decode_response_body(&utf16, Some("application/octet-stream"), false)
1387 .expect("BOM proves UTF-16 text"),
1388 "OK"
1389 );
1390
1391 let utf16_nul = [0xff, 0xfe, b'O', 0, 0, 0, b'K', 0];
1392 let error = decode_response_body(&utf16_nul, Some("text/plain"), false)
1393 .expect_err("decoded UTF-16 NUL must remain binary");
1394 assert!(error.to_string().contains("NUL bytes"));
1395 }
1396
1397 #[tokio::test]
1398 async fn extensionless_html_sniff_skips_leading_comments_and_xml_declarations() {
1399 let cases = [
1400 r#"<!-- deployment marker --><html><head><meta charset="windows-1252"><title>Café release notes</title></head><body><article><h1>Café release notes</h1><p>This extensionless page contains enough meaningful text for deterministic extraction.</p></article></body></html>"#,
1401 r#"<?xml version="1.0"?><!-- marker --><head><meta charset="windows-1252"><title>Café release notes</title></head><body><article><h1>Café release notes</h1><p>This extensionless page contains enough meaningful text for deterministic extraction.</p></article></body>"#,
1402 ];
1403 for html in cases {
1404 let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode(html);
1405 let document = extract_document(
1406 "https://example.com/extensionless",
1407 None,
1408 &bytes,
1409 false,
1410 None,
1411 )
1412 .await
1413 .expect("leading declarations preserve extensionless HTML sniffing");
1414 assert_eq!(document.kind, DocumentKind::Html);
1415 assert_eq!(document.title.as_deref(), Some("Café release notes"));
1416 }
1417 }
1418
1419 #[tokio::test]
1420 async fn svg_requires_and_accepts_svg_markup_signature() {
1421 let svg = br#"<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"></svg>"#;
1422 let document = extract_document(
1423 "https://example.com/diagram",
1424 Some("image/svg+xml"),
1425 svg,
1426 false,
1427 None,
1428 )
1429 .await
1430 .expect("sniff svg");
1431 assert_eq!(document.kind, DocumentKind::Media);
1432 assert_eq!(document.media_extension, Some("svg"));
1433 }
1434
1435 async fn extract_html_fixture(url: &str, html: &str) -> ExtractedDocument {
1436 extract_document(url, Some("text/html"), html.as_bytes(), false, None)
1437 .await
1438 .expect("fixture must extract readable text")
1439 }
1440
1441 #[tokio::test]
1442 async fn listing_page_keeps_every_article() {
1443 let html = r#"<html><body><nav>Home Blog About</nav><main>
1444 <article><h2>First post</h2><p>Alpha story body with plenty of words to read here.</p></article>
1445 <article><h2>Second post</h2><p>Bravo story body with plenty of words to read here.</p></article>
1446 <article><h2>Third post</h2><p>Charlie story body with plenty of words to read here.</p></article>
1447 </main></body></html>"#;
1448 let document = extract_html_fixture("https://blog.example/", html).await;
1449 for needle in [
1450 "First post",
1451 "Alpha story",
1452 "Second post",
1453 "Bravo story",
1454 "Third post",
1455 "Charlie story",
1456 ] {
1457 assert!(
1458 document.markdown.contains(needle),
1459 "{needle} missing: {}",
1460 document.markdown
1461 );
1462 }
1463 assert!(!document.markdown.contains("Home Blog About"));
1464 }
1465
1466 #[tokio::test]
1467 async fn article_header_keeps_title_and_byline() {
1468 let html = r#"<html><body><header>Site logo Sign in Subscribe</header>
1469 <article><header><h1>Whales sing in dialects</h1><p class="byline">By Ada Lovelace</p></header>
1470 <p>Researchers recorded humpback song across three oceans and found regional variation.</p>
1471 </article></body></html>"#;
1472 let document = extract_html_fixture("https://news.example/whales", html).await;
1473 assert!(
1474 document.markdown.contains("Whales sing in dialects"),
1475 "{}",
1476 document.markdown
1477 );
1478 assert!(
1479 document.markdown.contains("By Ada Lovelace"),
1480 "{}",
1481 document.markdown
1482 );
1483 assert!(document.markdown.contains("regional variation"));
1484 assert!(!document.markdown.contains("Sign in Subscribe"));
1485 }
1486
1487 #[tokio::test]
1488 async fn page_wrapped_in_a_form_is_not_mistaken_for_a_javascript_shell() {
1489 let html = r#"<html><body><form method="post" action="./Default.aspx" id="form1">
1490 <input type="hidden" name="__VIEWSTATE" value="dDwtMTA4MzE0MjEwNTs7Pg==" />
1491 <div class="content"><h1>Quarterly report</h1>
1492 <p>Revenue grew in every region this quarter, led by the northern division.</p></div>
1493 <select name="year"><option>2025</option><option>2026</option></select>
1494 <button type="submit">Go</button>
1495 </form></body></html>"#;
1496 let document = extract_html_fixture("https://legacy.example/Default.aspx", html).await;
1497 assert!(
1498 document.markdown.contains("Quarterly report"),
1499 "{}",
1500 document.markdown
1501 );
1502 assert!(document.markdown.contains("northern division"));
1503 assert!(!document.markdown.contains("VIEWSTATE"));
1504 assert!(
1505 !document.markdown.contains("2026"),
1506 "form controls are stripped"
1507 );
1508 }
1509
1510 #[tokio::test]
1511 async fn arxiv_abstract_page_extracts_title_and_abstract() {
1512 // Trimmed from the shape of https://arxiv.org/abs/1706.03762 (2026-09).
1513 let html = r##"<!DOCTYPE html><html lang="en"><head><title>[1706.03762] Attention Is All You Need</title>
1514 <script>window.MathJax = {};</script></head>
1515 <body ><div class="flex-wrap-footer"><a href="#content" class="ds-skip-link">Skip to main content</a>
1516 <header class="ds-site-header"><a href="https://arxiv.org/">archive home</a>
1517 <button type="button" id="ds-nav-toggle">Open menu</button>
1518 <nav class="ds-site-header-nav"><a href="https://arxiv.org/search">Search</a><a href="https://arxiv.org/login">Log in</a></nav>
1519 </header>
1520 <div class="arxiv-search-overlay" hidden><form method="GET" action="https://arxiv.org/search">
1521 <label for="q">Search arXiv</label><input type="text" name="query" id="q"></form></div>
1522 <main><div id="content"><!-- rdf:RDF <rdf:Description dc:title="Attention Is All You Need" /> -->
1523 <div id="abs-outer"><div class="leftcolumn"><div class="subheader"><h1>Computer Science &gt; Computation and Language</h1></div>
1524 <div id="abs"><div class="dateline">[Submitted on 12 Jun 2017 (<a href="/abs/1706.03762v1">v1</a>)]</div>
1525 <h1 class="title mathjax"><span class="descriptor">Title:</span>Attention Is All You Need</h1>
1526 <div class="authors"><span class="descriptor">Authors:</span><a href="/a/vaswani_a_1">Ashish Vaswani</a></div>
1527 <blockquote class="abstract mathjax"><span class="descriptor">Abstract:</span>The dominant sequence transduction models are based on complex recurrent or convolutional neural networks.</blockquote>
1528 <script type="text/javascript" language="javascript">mathjaxToggle();</script>
1529 </div></div></div></div></main>
1530 <footer><a href="https://info.arxiv.org/help/contact.html">Contact</a></footer></div></body></html>"##;
1531 let document = extract_html_fixture("https://arxiv.org/abs/1706.03762", html).await;
1532 assert!(
1533 document.markdown.contains("Attention Is All You Need"),
1534 "{}",
1535 document.markdown
1536 );
1537 assert!(
1538 document.markdown.contains("dominant sequence transduction"),
1539 "{}",
1540 document.markdown
1541 );
1542 assert!(document.markdown.contains("Ashish Vaswani"));
1543 assert!(!document.markdown.contains("mathjaxToggle"));
1544 assert!(!document.markdown.contains("Log in"));
1545 }
1546 }
1547
1548 #[cfg(test)]
1549 #[path = "extract_host_tests.rs"]
1550 mod host_tests;
1551
1551 lines RUST