spider_transformations 2.39.0

Transformation utils to use for spider
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/// Chunking utils.
pub mod chunking;
/// Content utils.
pub mod content;
/// Office document (xlsx, docx, pptx) conversion.
#[cfg(feature = "document")]
pub mod document;
/// Audio file metadata extraction.
#[cfg(feature = "audio")]
pub mod audio;
/// Text extraction.
pub mod text_extract;

#[cfg(test)]
mod tests {
    use std::vec;

    use crate::transformation::content::{self, ReturnFormat, SelectorConfiguration};
    use maud::PreEscaped;
    use spider::{
        page::build_with_parse,
        tokio::{self, fs::File},
        utils::PageResponse,
    };

    /// the template to re-use
    fn template() -> PreEscaped<String> {
        use maud::{html, DOCTYPE};

        let page_title = "Transform Test";
        let page_h1 = "Fun is fun";

        let markup = html! {
            (DOCTYPE)
            meta charset="utf-8";
            title { (page_title) }
            h1 { (page_h1) }
            a href="https://spider.cloud" { "Spider Cloud"};
            pre {
                r#"The content is ready"#
            }
            script {
                r#"document.querySelector("pre")"#
            }
        };

        markup
    }

    #[test]
    fn test_transformations() {
        let markup = template().into_string();
        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();

        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Markdown;

        let content = content::transform_content(&page, &conf, &None, &None, &None);

        assert!(
            content
                .contains(&"Transform Test# Fun is fun\n[Spider Cloud](https://spider.cloud)\n```\nThe content is ready\n```"),
            "The tranform to markdown is invalid"
        );

        conf.return_format = ReturnFormat::Html2Text;

        let content = content::transform_content(&page, &conf, &None, &None, &None);

        assert!(
            content
                .contains(& "# Fun is fun\n\n[Spider Cloud][1]\nThe content is ready\n\n[1]: https://spider.cloud\n"),
            "The tranform to html2text is invalid"
        );

        conf.return_format = ReturnFormat::Bytes;
        conf.readability = true;

        let content = content::transform_content(&page, &conf, &None, &None, &None);

        assert!(
            content
                .contains(&"<html class=\"paper\"><head>\n<meta name=\"disabled-adaptations\" content=\"watch\">\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<meta name=\"viewport\" content=\"initial-scale=1\">\n<base href=\"https://spider.cloud/\">\n<title>Transform Test</title>\n<script>window.isReaderPage = true;</script>\n</head><body>\n<h1>Fun is fun</h1><a href=\"https://spider.cloud\">Spider Cloud</a><pre>The content is ready</pre></body></html>"),
            "The tranform to bytes is invalid"
        );

        conf.return_format = ReturnFormat::XML;
        let content = content::transform_content(&page, &conf, &Some("UTF-8".into()), &None, &None);
        assert!(
            content
                == r#"<html xmlns="http://www.w3.org/1999/xhtml" class="paper"><head>
<meta name="disabled-adaptations" content="watch" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1" />
<base href="https://spider.cloud/" />
<title>Transform Test</title>
<script><![CDATA[window.isReaderPage = true;]]></script>
</head><body>
<h1>Fun is fun</h1><a href="https://spider.cloud">Spider Cloud</a><pre>The content is ready</pre></body></html>"#,
            "The tranform to xml is invalid"
        );
    }

    #[test]
    fn test_xml_transformations() {
        let markup = template().into_string();

        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();
        conf.return_format = ReturnFormat::XML;
        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);
        let content = content::transform_content(&page, &conf, &None, &None, &None);
        assert!(
            content
                == r#"<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta charset="utf-8" /><title>Transform Test</title></head><body><h1>Fun is fun</h1><a href="https://spider.cloud">Spider Cloud</a><pre>The content is ready</pre><script><![CDATA[document.querySelector(&amp;quot;pre&amp;quot;)]]></script></body></html>"#,
            "The tranform to xml is invalid"
        );
    }

    #[test]
    fn test_transformations_root_selector() {
        let markup = template().into_string();
        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();

        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Markdown;

        let mut select_config = SelectorConfiguration::default();

        select_config.root_selector = Some("pre".into());

        let content = content::transform_content(&page, &conf, &None, &Some(select_config), &None);

        assert!(
            content.contains(&"The content is ready"),
            "The tranform to markdown is invalid"
        );
    }

    #[test]
    fn test_transformations_exclude_selector() {
        let markup = template().into_string();
        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();

        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Markdown;

        let mut select_config = SelectorConfiguration::default();

        select_config.exclude_selector = Some("pre".into());

        let content = content::transform_content(&page, &conf, &None, &Some(select_config), &None);

        assert!(
            content.contains(&"Transform Test# Fun is fun\n[Spider Cloud](https://spider.cloud)"),
            "The tranform to markdown is invalid"
        );
    }

    #[test]
    fn test_transformations_exclude_selector_text() {
        let markup = template().into_string();
        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();

        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Text;

        let mut select_config = SelectorConfiguration::default();

        select_config.exclude_selector = Some("pre".into());

        let content = content::transform_content(&page, &conf, &None, &Some(select_config), &None);

        assert!(
            content.contains(&"Transform Test\nFun is fun Spider Cloud"),
            "The tranform to markdown is invalid"
        );
    }

    #[tokio::test]
    async fn test_transformations_exclude_selector_text_streaming() {
        let markup = template().into_string();
        let url = "https://spider.cloud";

        let mut conf = content::TransformConfig::default();
        let mut page_response = PageResponse::default();

        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Text;

        let mut select_config = SelectorConfiguration::default();

        select_config.exclude_selector = Some("pre".into());

        let content =
            content::transform_content_send(&page, &conf, &None, &Some(select_config), &None).await;

        assert!(
            content.contains(&"Transform Test\nFun is fun Spider Cloud"),
            "The tranform to markdown is invalid"
        );
    }

    #[ignore]
    #[tokio::test]
    async fn test_transformations_pdf_handling() {
        use spider::tokio::io::AsyncReadExt;
        let mut f = File::open("./example.pdf").await.unwrap();
        let mut data = vec![];
        f.read_to_end(&mut data).await.unwrap();

        let mut conf = content::TransformConfig::default();
        conf.return_format = ReturnFormat::XML;
        let mut page_response = PageResponse::default();

        page_response.content = Some(data);

        let page = build_with_parse("https://example.com/example.pdf", page_response);

        let content = content::transform_content(&page, &conf, &None, &None, &None);

        assert!(content.is_empty(), "The tranform to markdown is invalid");
    }

    // -------------------------------------------------------------------
    // extract_text: two-pass fix tests
    // -------------------------------------------------------------------

    #[test]
    fn test_extract_text_no_custom_ignore() {
        let html = r#"<div><p>Hello world</p><script>var x=1;</script></div>"#;
        let result = super::text_extract::extract_text(html, &None);
        assert!(result.contains("Hello world"), "should extract text: {result}");
        assert!(!result.contains("var x"), "should exclude script content: {result}");
    }

    #[test]
    fn test_extract_text_custom_ignore_strips_nested_element() {
        // The bug: custom ignore tags via element! remove() didn't prevent
        // text handlers from capturing the removed element's text when nested.
        let html = r#"<div><div class="popup">popup text</div><p>real content</p></div>"#;
        let mut ignore = std::collections::HashSet::new();
        ignore.insert(".popup".to_string());

        let result = super::text_extract::extract_text(html, &Some(ignore));
        assert!(
            !result.contains("popup text"),
            "custom ignore should strip nested .popup text, got: {result}"
        );
        assert!(
            result.contains("real content"),
            "should preserve non-ignored text, got: {result}"
        );
    }

    #[test]
    fn test_extract_text_custom_ignore_strips_deeply_nested() {
        let html = r#"<body><div class="wrapper"><aside class="sidebar"><nav><ul><li>Link 1</li><li>Link 2</li></ul></nav></aside><main><p>Article content</p></main></div></body>"#;
        let mut ignore = std::collections::HashSet::new();
        ignore.insert(".sidebar".to_string());

        let result = super::text_extract::extract_text(html, &Some(ignore));
        assert!(
            !result.contains("Link 1"),
            "sidebar text should be stripped, got: {result}"
        );
        assert!(
            result.contains("Article content"),
            "main content preserved, got: {result}"
        );
    }

    #[test]
    fn test_extract_text_custom_ignore_multiple_selectors() {
        let html = r#"<div><nav>nav text</nav><footer>footer text</footer><main>main text</main></div>"#;
        let mut ignore = std::collections::HashSet::new();
        ignore.insert("nav".to_string());
        ignore.insert("footer".to_string());

        let result = super::text_extract::extract_text(html, &Some(ignore));
        assert!(
            !result.contains("nav text"),
            "nav should be stripped, got: {result}"
        );
        assert!(
            !result.contains("footer text"),
            "footer should be stripped, got: {result}"
        );
        assert!(
            result.contains("main text"),
            "main content preserved, got: {result}"
        );
    }

    #[test]
    fn test_extract_text_empty_custom_ignore() {
        let html = r#"<div><p>content</p></div>"#;
        let ignore = std::collections::HashSet::new();
        let result = super::text_extract::extract_text(html, &Some(ignore));
        assert!(
            result.contains("content"),
            "empty ignore set should not affect extraction, got: {result}"
        );
    }

    #[test]
    fn test_extract_text_empty_html() {
        let result = super::text_extract::extract_text("", &None);
        assert!(result.is_empty(), "empty html should produce empty text");
    }

    #[test]
    fn test_extract_text_script_style_svg_excluded() {
        let html = r#"<div><p>visible</p><script>js code</script><style>.x{}</style><svg><text>svg text</text></svg><noscript>noscript</noscript></div>"#;
        let result = super::text_extract::extract_text(html, &None);
        assert!(result.contains("visible"), "should extract visible text");
        assert!(!result.contains("js code"), "should exclude script");
        assert!(!result.contains(".x{}"), "should exclude style");
    }

    #[tokio::test]
    async fn test_extract_text_streaming_custom_ignore() {
        let html = r#"<div><div class="popup">popup text</div><p>real content</p></div>"#;
        let mut ignore = std::collections::HashSet::new();
        ignore.insert(".popup".to_string());

        let result =
            super::text_extract::extract_text_streaming(html, &Some(ignore)).await;
        assert!(
            !result.contains("popup text"),
            "streaming: custom ignore should strip .popup text, got: {result}"
        );
        assert!(
            result.contains("real content"),
            "streaming: should preserve non-ignored text, got: {result}"
        );
    }

    #[tokio::test]
    async fn test_extract_text_streaming_no_ignore() {
        let html = r#"<div><p>hello</p><script>bad</script></div>"#;
        let result =
            super::text_extract::extract_text_streaming(html, &None).await;
        assert!(result.contains("hello"), "streaming: should extract text");
        assert!(!result.contains("bad"), "streaming: should exclude script");
    }

    // Regression: ensure the existing exclude_selector + Text format pipeline
    // still works correctly end-to-end.
    #[test]
    fn test_transform_content_text_with_exclude_and_ignore() {
        use maud::{html, DOCTYPE};

        let markup = html! {
            (DOCTYPE)
            title { "Test Page" }
            nav { "Navigation Menu" }
            div class="sidebar" { "Sidebar Widget" }
            main {
                h1 { "Article" }
                p { "Important content here." }
            }
            footer { "Footer Links" }
        };

        let url = "https://example.com";
        let mut conf = content::TransformConfig::default();
        let mut page_response = spider::utils::PageResponse::default();
        page_response.content = Some(markup.into_string().into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Text;

        // With ignore_tags that should strip nav and footer
        let ignore_tags = Some(vec!["nav".to_string(), "footer".to_string()]);

        let result =
            content::transform_content(&page, &conf, &None, &None, &ignore_tags);

        assert!(
            result.contains("Important content"),
            "main content should be present, got: {result}"
        );
        assert!(
            !result.contains("Navigation Menu"),
            "nav should be stripped by ignore_tags, got: {result}"
        );
        assert!(
            !result.contains("Footer Links"),
            "footer should be stripped by ignore_tags, got: {result}"
        );
    }

    #[test]
    fn test_transform_content_text_with_selector_and_ignore() {
        use maud::{html, DOCTYPE};

        let markup = html! {
            (DOCTYPE)
            title { "Test" }
            header { "Header" }
            main {
                div class="ad-banner" { "Ad content" }
                p { "Real article text" }
            }
            footer { "Footer" }
        };

        let url = "https://example.com";
        let mut conf = content::TransformConfig::default();
        let mut page_response = spider::utils::PageResponse::default();
        page_response.content = Some(markup.into_string().into());
        let page = build_with_parse(url, page_response);

        conf.return_format = ReturnFormat::Text;

        // exclude_selector removes header/footer, ignore_tags removes .ad-banner
        let mut select_config = SelectorConfiguration::default();
        select_config.exclude_selector = Some("header, footer".into());
        let ignore_tags = Some(vec![".ad-banner".to_string()]);

        let result = content::transform_content(
            &page,
            &conf,
            &None,
            &Some(select_config),
            &ignore_tags,
        );

        assert!(
            result.contains("Real article text"),
            "main content should be present, got: {result}"
        );
        assert!(
            !result.contains("Header"),
            "header should be excluded, got: {result}"
        );
        assert!(
            !result.contains("Footer"),
            "footer should be excluded, got: {result}"
        );
        assert!(
            !result.contains("Ad content"),
            "ad-banner should be stripped by ignore_tags, got: {result}"
        );
    }

    // ===================================================================
    // Panic-freedom / lock-free audit tests
    // ===================================================================

    /// Verify html2text handles tables without panicking (previously used
    /// `unimplemented!()` for TableRow/TableBody/TableCell size estimation).
    #[test]
    fn no_panic_html2text_with_tables() {
        let html = r#"<table><thead><tr><th>A</th><th>B</th></tr></thead>
            <tbody><tr><td>1</td><td>2</td></tr>
            <tr><td>3</td><td>4</td></tr></tbody></table>"#;
        let result = crate::html2text::from_read(html.as_bytes(), 80);
        assert!(!result.is_empty(), "table rendering should produce output");
    }

    /// Nested tables should not panic.
    #[test]
    fn no_panic_html2text_nested_tables() {
        let html = r#"<table><tr><td><table><tr><td>inner</td></tr></table></td></tr></table>"#;
        let result = crate::html2text::from_read(html.as_bytes(), 80);
        assert!(
            result.contains("inner"),
            "nested table content should render: {result}"
        );
    }

    /// Very wide table with many columns should not panic.
    #[test]
    fn no_panic_html2text_wide_table() {
        let mut html = String::from("<table><tr>");
        for i in 0..100 {
            html.push_str(&format!("<td>col{i}</td>"));
        }
        html.push_str("</tr></table>");
        let result = crate::html2text::from_read(html.as_bytes(), 40);
        // Should not panic even with narrow width and many columns.
        assert!(!result.is_empty());
    }

    /// html2text with zero-width should not panic.
    #[test]
    fn no_panic_html2text_zero_width() {
        let html = "<p>Hello world</p>";
        // width=0 might return an error or empty, but must not panic
        let result = crate::html2text::from_read(html.as_bytes(), 0);
        let _ = result; // just verifying no panic
    }

    /// html2text with empty input should not panic.
    #[test]
    fn no_panic_html2text_empty() {
        let result = crate::html2text::from_read("".as_bytes(), 80);
        assert!(result.is_empty() || result.trim().is_empty());
    }

    /// Chunk by sentence with zero chunk size must not panic.
    /// Previously `Vec::chunks(0)` would panic.
    #[test]
    fn no_panic_chunk_by_sentence_zero() {
        use crate::transformation::chunking::{chunk_text, ChunkingAlgorithm};
        let result = chunk_text("Hello world. How are you? Fine.", ChunkingAlgorithm::BySentence(0));
        assert!(!result.is_empty(), "should produce at least one chunk");
    }

    /// Chunk by words with zero chunk size must not panic.
    #[test]
    fn no_panic_chunk_by_words_zero() {
        use crate::transformation::chunking::{chunk_text, ChunkingAlgorithm};
        let result = chunk_text("Hello world foo bar", ChunkingAlgorithm::ByWords(0));
        // With 0, every word becomes its own chunk (>= 0 is always true)
        assert!(!result.is_empty());
    }

    /// Chunk by lines with zero must not panic.
    #[test]
    fn no_panic_chunk_by_lines_zero() {
        use crate::transformation::chunking::{chunk_text, ChunkingAlgorithm};
        let result = chunk_text("line1\nline2\nline3", ChunkingAlgorithm::ByLines(0));
        assert!(!result.is_empty());
    }

    /// Chunk by char length with zero must not panic.
    #[test]
    fn no_panic_chunk_by_char_zero() {
        use crate::transformation::chunking::{chunk_text, ChunkingAlgorithm};
        let result = chunk_text("abcdef", ChunkingAlgorithm::ByCharacterLength(0));
        assert!(!result.is_empty());
    }

    /// Chunking on empty text must not panic for any algorithm.
    #[test]
    fn no_panic_chunk_empty_text() {
        use crate::transformation::chunking::{chunk_text, ChunkingAlgorithm};
        assert!(chunk_text("", ChunkingAlgorithm::ByWords(5)).is_empty());
        assert!(chunk_text("", ChunkingAlgorithm::ByLines(5)).is_empty());
        assert!(chunk_text("", ChunkingAlgorithm::ByCharacterLength(5)).is_empty());
        // BySentence splits on regex, so empty string still produces one empty split
        let _ = chunk_text("", ChunkingAlgorithm::BySentence(5));
    }

    /// extract_text with malformed/truncated HTML must not panic.
    #[test]
    fn no_panic_extract_text_malformed_html() {
        let cases = [
            "<div><p>unclosed",
            "</p></div>stray closing",
            "<sc<ript>broken tag",
            "<<<>>>",
            "<div attr=\"unclosed>text</div>",
            &"<div>".repeat(1000),
            "",
        ];
        for html in &cases {
            let _ = super::text_extract::extract_text(html, &None);
        }
    }

    /// Streaming extract_text with malformed HTML must not panic.
    #[tokio::test]
    async fn no_panic_extract_text_streaming_malformed() {
        let cases = [
            "<div><p>unclosed",
            "</p></div>stray",
            "<<<>>>",
            "",
        ];
        for html in &cases {
            let _ = super::text_extract::extract_text_streaming(html, &None).await;
        }
    }

    /// All ReturnFormat variants on empty content must not panic.
    #[test]
    fn no_panic_transform_all_formats_empty() {
        let url = "https://example.com";
        let mut page_response = PageResponse::default();
        page_response.content = Some(Vec::new());
        let page = build_with_parse(url, page_response);

        let formats = [
            ReturnFormat::Raw,
            ReturnFormat::Text,
            ReturnFormat::Markdown,
            ReturnFormat::CommonMark,
            ReturnFormat::Html2Text,
            ReturnFormat::XML,
            ReturnFormat::Bytes,
            ReturnFormat::Empty,
        ];
        for fmt in &formats {
            let mut conf = content::TransformConfig::default();
            conf.return_format = *fmt;
            let _ = content::transform_content(&page, &conf, &None, &None, &None);
        }
    }

    /// All ReturnFormat variants on valid HTML must not panic.
    #[test]
    fn no_panic_transform_all_formats_valid() {
        let markup = template().into_string();
        let url = "https://spider.cloud";
        let mut page_response = PageResponse::default();
        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        let formats = [
            ReturnFormat::Raw,
            ReturnFormat::Text,
            ReturnFormat::Markdown,
            ReturnFormat::CommonMark,
            ReturnFormat::Html2Text,
            ReturnFormat::XML,
            ReturnFormat::Bytes,
            ReturnFormat::Empty,
        ];
        for fmt in &formats {
            let mut conf = content::TransformConfig::default();
            conf.return_format = *fmt;
            let _ = content::transform_content(&page, &conf, &None, &None, &None);
        }
    }

    /// transform_content with readability on garbage HTML must not panic.
    #[test]
    fn no_panic_transform_readability_garbage() {
        let html = "<html><body><div>some text</div><script>x</script></body></html>";
        let url = "https://example.com";
        let mut page_response = PageResponse::default();
        page_response.content = Some(html.into());
        let page = build_with_parse(url, page_response);

        let mut conf = content::TransformConfig::default();
        conf.readability = true;
        conf.return_format = ReturnFormat::Markdown;
        let _ = content::transform_content(&page, &conf, &None, &None, &None);
    }

    /// XML conversion of non-UTF8-declared content must not panic.
    #[test]
    fn no_panic_xml_conversion_various_encodings() {
        let html = "<html><head><meta charset='utf-8'></head><body>Hello</body></html>";
        let url = "https://example.com";
        let mut page_response = PageResponse::default();
        page_response.content = Some(html.into());
        let page = build_with_parse(url, page_response);

        let mut conf = content::TransformConfig::default();
        conf.return_format = ReturnFormat::XML;

        // With explicit encoding
        let _ = content::transform_content(&page, &conf, &Some("UTF-8".into()), &None, &None);
        // Without encoding
        let _ = content::transform_content(&page, &conf, &None, &None, &None);
        // With unknown encoding
        let _ = content::transform_content(&page, &conf, &Some("FAKE-ENCODING".into()), &None, &None);
    }

    /// Large HTML document should not stack overflow or panic.
    #[test]
    fn no_panic_large_html() {
        let mut html = String::with_capacity(100_000);
        html.push_str("<html><body>");
        for i in 0..1000 {
            html.push_str(&format!("<p>Paragraph {i} with <b>bold</b> and <a href='#'>link</a></p>"));
        }
        html.push_str("</body></html>");

        let result = crate::html2text::from_read(html.as_bytes(), 80);
        assert!(!result.is_empty());

        let _ = super::text_extract::extract_text(&html, &None);
    }

    /// Deeply nested HTML should not stack overflow.
    #[test]
    fn no_panic_deeply_nested_html() {
        let depth = 200;
        let mut html = String::new();
        for _ in 0..depth {
            html.push_str("<div>");
        }
        html.push_str("deep content");
        for _ in 0..depth {
            html.push_str("</div>");
        }
        let _ = crate::html2text::from_read(html.as_bytes(), 80);
        let _ = super::text_extract::extract_text(&html, &None);
    }

    /// Async streaming variants must not panic on any format.
    #[tokio::test]
    async fn no_panic_transform_send_all_formats() {
        let markup = template().into_string();
        let url = "https://spider.cloud";
        let mut page_response = PageResponse::default();
        page_response.content = Some(markup.into());
        let page = build_with_parse(url, page_response);

        let formats = [
            ReturnFormat::Raw,
            ReturnFormat::Text,
            ReturnFormat::Markdown,
            ReturnFormat::CommonMark,
            ReturnFormat::Html2Text,
            ReturnFormat::XML,
            ReturnFormat::Bytes,
            ReturnFormat::Empty,
        ];
        for fmt in formats {
            let mut conf = content::TransformConfig::default();
            conf.return_format = fmt;
            let _ = content::transform_content_send(&page, &conf, &None, &None, &None).await;
        }
    }

    /// Unicode / multibyte content must not panic in any path.
    #[test]
    fn no_panic_unicode_content() {
        let html = "<html><body><p>日本語テスト</p><p>Ñoño café résumé</p><p>🦀🔥💯</p></body></html>";
        let _ = crate::html2text::from_read(html.as_bytes(), 80);
        let _ = super::text_extract::extract_text(html, &None);

        let url = "https://example.com";
        let mut page_response = PageResponse::default();
        page_response.content = Some(html.into());
        let page = build_with_parse(url, page_response);
        let mut conf = content::TransformConfig::default();
        for fmt in [ReturnFormat::Text, ReturnFormat::Markdown, ReturnFormat::Html2Text] {
            conf.return_format = fmt;
            let _ = content::transform_content(&page, &conf, &None, &None, &None);
        }
    }
}