ssg 0.0.40

A secure-by-default static site generator built in Rust. WCAG 2.2 AA validation, CSP/SRI hardening, native JS/CSS minification, automated CycloneDX SBOM, local LLM content pipeline, WebAssembly target, interactive islands, streaming compilation for 100K+ pages, 28-locale i18n, and one-command deployment.
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! GitHub Flavored Markdown (GFM) extensions plugin.
//!
//! Pre-processes Markdown content in the `before_compile` phase to add
//! support for GFM features that the upstream renderer does not handle:
//!
//! - **Tables** — `| col | col |` blocks with a `|---|---|` separator row.
//! - **Strikethrough** — `~~text~~` becomes `<del>text</del>`.
//! - **Task lists** — `- [ ] item` and `- [x] done` become checkbox lists.
//! - **Footnotes** — `[^id]` references with `[^id]:` definitions.
//!
//! ## How it works
//!
//! For each `.md` file under `content_dir`, the plugin:
//! 1. Splits the YAML/TOML frontmatter from the body so it stays untouched.
//! 2. Walks the body line-by-line, tracking fenced code blocks so GFM
//!    syntax inside ``` ``` ``` ``` blocks is preserved literally.
//! 3. Detects GFM-specific blocks (tables, task lists) and renders **only
//!    those blocks** through `pulldown-cmark` with the matching options
//!    enabled, substituting the rendered HTML back into the source.
//! 4. Applies an inline strikethrough transform to remaining text.
//!
//! Standard markdown renderers pass block-level raw HTML through
//! unchanged, so the substituted HTML composes cleanly with whatever
//! renderer staticdatagen runs afterwards.
//!
//! ## Example
//!
//! ```rust
//! use ssg::plugin::PluginManager;
//! use ssg::markdown_ext::MarkdownExtPlugin;
//!
//! let mut pm = PluginManager::new();
//! pm.register(MarkdownExtPlugin);
//! ```

use crate::error::SsgError;
use crate::plugin::{Plugin, PluginContext};
use crate::walk::walk_files_bounded_depth;
use crate::MAX_DIR_DEPTH;
use pulldown_cmark::{html as cmark_html, Options, Parser};
use std::fs;

/// Plugin that expands GFM Markdown extensions in source files.
///
/// Runs in `before_compile`. See the [module-level docs](self) for the
/// full list of supported features and the transformation strategy.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Copy, Clone)]
pub struct MarkdownExtPlugin;

impl Plugin for MarkdownExtPlugin {
    fn name(&self) -> &'static str {
        "markdown-ext"
    }

    fn before_compile(&self, ctx: &PluginContext) -> Result<(), SsgError> {
        if !ctx.content_dir.exists() {
            return Ok(());
        }

        let files =
            walk_files_bounded_depth(&ctx.content_dir, "md", MAX_DIR_DEPTH)
                .map_err(|e| SsgError::io(e, &ctx.content_dir))?;

        let cdn_prefix = ctx
            .config
            .as_ref()
            .and_then(|c| c.cdn_prefix.as_ref())
            .map(|s| s.as_str());

        let mut transformed = 0usize;
        for path in &files {
            fail_point!("markdown_ext::read", |_| {
                Err(SsgError::Io {
                    path: path.clone(),
                    source: std::io::Error::other(
                        "injected: markdown_ext::read",
                    ),
                })
            });
            let raw =
                fs::read_to_string(path).map_err(|e| SsgError::io(e, path))?;

            let new = expand_gfm(&raw, cdn_prefix);
            if new != raw {
                fail_point!("markdown_ext::write", |_| {
                    Err(SsgError::Io {
                        path: path.clone(),
                        source: std::io::Error::other(
                            "injected: markdown_ext::write",
                        ),
                    })
                });
                fs::write(path, &new).map_err(|e| SsgError::io(e, path))?;
                transformed += 1;
            }
        }

        if transformed > 0 {
            log::info!("[markdown-ext] Transformed {transformed} file(s)");
        }
        Ok(())
    }
}

/// Splits leading frontmatter (`--- ... ---`) from `input`.
///
/// Returns `(frontmatter, body)`. If no frontmatter is present the
/// frontmatter slice is empty and the entire input is the body.
fn split_frontmatter(input: &str) -> (&str, &str) {
    if let Some(rest) = input.strip_prefix("---\n") {
        if let Some(end) = rest.find("\n---\n") {
            let fm_end = "---\n".len() + end + "\n---\n".len();
            return (&input[..fm_end], &input[fm_end..]);
        }
        if let Some(end) = rest.find("\n---") {
            let fm_end = "---\n".len() + end + "\n---".len();
            // Trailing newline after closing fence is optional.
            return (&input[..fm_end], &input[fm_end..]);
        }
    }
    ("", input)
}

/// Expands all GFM constructs in `input`, returning a new string.
/// Also prefixes local images with a CDN URL if `cdn_prefix` is set.
#[must_use]
pub fn expand_gfm(input: &str, cdn_prefix: Option<&str>) -> String {
    let (frontmatter, body_raw) = split_frontmatter(input);

    let body_owned;
    let body = if let Some(prefix) = cdn_prefix {
        let md_rewritten = rewrite_markdown_images(body_raw, prefix);
        body_owned = rewrite_html_images(&md_rewritten, prefix);
        &body_owned
    } else {
        body_raw
    };

    if !needs_expansion(body) {
        if cdn_prefix.is_none() {
            return input.to_string();
        }
        let mut out = String::with_capacity(frontmatter.len() + body.len());
        out.push_str(frontmatter);
        out.push_str(body);
        return out;
    }

    let mut out = String::with_capacity(input.len() + 256);
    out.push_str(frontmatter);

    let lines: Vec<&str> = body.lines().collect();
    let mut i = 0usize;
    let mut in_fence = false;
    let mut fence_marker: Option<&str> = None;

    while i < lines.len() {
        let line = lines[i];

        if let Some(marker) = detect_fence(line) {
            update_fence_state(&mut in_fence, &mut fence_marker, marker, line);
            out.push_str(line);
            out.push('\n');
            i += 1;
            continue;
        }

        if in_fence {
            out.push_str(line);
            out.push('\n');
            i += 1;
            continue;
        }

        i = process_gfm_line(&lines, i, &mut out);
    }

    if !body.ends_with('\n') && out.ends_with('\n') {
        let _ = out.pop();
    }

    out
}

/// Updates fence tracking state when a fence marker is encountered.
fn update_fence_state<'a>(
    in_fence: &mut bool,
    fence_marker: &mut Option<&'a str>,
    marker: &'a str,
    line: &str,
) {
    if !*in_fence {
        *in_fence = true;
        *fence_marker = Some(marker);
    } else if fence_marker.is_some_and(|m| line.trim_start().starts_with(m)) {
        *in_fence = false;
        *fence_marker = None;
    }
}

/// Processes a single non-fenced line, detecting tables, task lists, or
/// applying strikethrough. Returns the new line index.
fn process_gfm_line(lines: &[&str], i: usize, out: &mut String) -> usize {
    let line = lines[i];

    if i + 1 < lines.len() && is_table_header(line, lines[i + 1]) {
        let end = find_table_end(lines, i);
        let block = lines[i..end].join("\n");
        out.push_str(&render_with_options(&block, Options::ENABLE_TABLES));
        out.push('\n');
        return end;
    }

    if is_task_list_line(line) {
        let end = find_task_list_end(lines, i);
        let block = lines[i..end].join("\n");
        out.push_str(&render_with_options(&block, Options::ENABLE_TASKLISTS));
        out.push('\n');
        return end;
    }

    out.push_str(&apply_strikethrough(line));
    out.push('\n');
    i + 1
}

/// Returns `true` if `body` contains any GFM-specific syntax that this
/// plugin would transform.
fn needs_expansion(body: &str) -> bool {
    if body.contains("~~") {
        return true;
    }
    if body.lines().any(is_task_list_line) {
        return true;
    }
    has_table(body)
}

/// Detects whether `body` contains any GFM table block.
fn has_table(body: &str) -> bool {
    let lines: Vec<&str> = body.lines().collect();
    lines.windows(2).any(|w| is_table_header(w[0], w[1]))
}

/// Returns the fence marker (` ``` ` or `~~~`) if `line` opens or
/// closes a fenced code block.
fn detect_fence(line: &str) -> Option<&'static str> {
    let trimmed = line.trim_start();
    if trimmed.starts_with("```") {
        Some("```")
    } else if trimmed.starts_with("~~~") {
        Some("~~~")
    } else {
        None
    }
}

/// Returns `true` if `header` looks like a table header followed by a
/// `|---|---|` separator row on `separator`.
fn is_table_header(header: &str, separator: &str) -> bool {
    if !header.contains('|') {
        return false;
    }
    is_separator_row(separator)
}

/// Returns `true` if `line` is a GFM table separator row like
/// `| --- | :---: | ---: |`.
fn is_separator_row(line: &str) -> bool {
    let t = line.trim();
    if !t.contains('-') || !t.contains('|') {
        return false;
    }
    t.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t'))
}

/// Returns the index *just past* the last contiguous table line.
fn find_table_end(lines: &[&str], start: usize) -> usize {
    let mut end = start + 2; // header + separator
    while end < lines.len() {
        let l = lines[end];
        if l.trim().is_empty() || !l.contains('|') {
            break;
        }
        end += 1;
    }
    end
}

/// Returns `true` if `line` is a task list item.
fn is_task_list_line(line: &str) -> bool {
    let t = line.trim_start();
    if t.len() < 6 {
        return false;
    }
    let bytes = t.as_bytes();
    let bullet = bytes[0];
    if !matches!(bullet, b'-' | b'*' | b'+') {
        return false;
    }
    if bytes[1] != b' ' {
        return false;
    }
    if bytes[2] != b'[' {
        return false;
    }
    if !matches!(bytes[3], b' ' | b'x' | b'X') {
        return false;
    }
    if bytes[4] != b']' {
        return false;
    }
    bytes[5] == b' '
}

/// Returns the index just past the last contiguous task list line.
fn find_task_list_end(lines: &[&str], start: usize) -> usize {
    let mut end = start;
    while end < lines.len() && is_task_list_line(lines[end]) {
        end += 1;
    }
    end
}

/// Renders `markdown` to HTML using `pulldown-cmark` with `extra`
/// options merged in alongside the always-on strikethrough flag.
fn render_with_options(markdown: &str, extra: Options) -> String {
    let mut opts = Options::ENABLE_STRIKETHROUGH;
    opts.insert(extra);
    let parser = Parser::new_ext(markdown, opts);
    let mut html = String::with_capacity(markdown.len() + 64);
    cmark_html::push_html(&mut html, parser);
    html.trim_end().to_string()
}

/// Replaces `~~text~~` with `<del>text</del>` outside of inline code spans.
fn apply_strikethrough(line: &str) -> String {
    let bytes = line.as_bytes();
    let mut out = String::with_capacity(line.len());
    let mut i = 0usize;
    let mut in_code = false;

    while i < bytes.len() {
        if bytes[i] == b'`' {
            in_code = !in_code;
            out.push('`');
            i += 1;
            continue;
        }
        if !in_code
            && i + 1 < bytes.len()
            && bytes[i] == b'~'
            && bytes[i + 1] == b'~'
        {
            // Find closing `~~`.
            if let Some(close) = find_strike_close(line, i + 2) {
                out.push_str("<del>");
                out.push_str(&line[i + 2..close]);
                out.push_str("</del>");
                i = close + 2;
                continue;
            }
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

/// Returns the byte offset of the next `~~` after `from`, or `None`.
fn find_strike_close(line: &str, from: usize) -> Option<usize> {
    let bytes = line.as_bytes();
    let mut j = from;
    while j + 1 < bytes.len() {
        if bytes[j] == b'`' {
            // Skip inline code spans inside the strike content.
            let mut k = j + 1;
            while k < bytes.len() && bytes[k] != b'`' {
                k += 1;
            }
            j = k.saturating_add(1);
            continue;
        }
        if bytes[j] == b'~' && bytes[j + 1] == b'~' {
            return Some(j);
        }
        j += 1;
    }
    None
}

fn rewrite_markdown_images(body: &str, cdn_prefix: &str) -> String {
    let mut result = String::with_capacity(body.len());
    let mut remaining = body;

    while let Some(start_idx) = remaining.find("![") {
        result.push_str(&remaining[..start_idx]);
        let post_bracket = &remaining[start_idx + 2..];

        let Some(close_bracket_idx) = post_bracket.find(']') else {
            result.push_str("![");
            remaining = post_bracket;
            continue;
        };

        let alt_text = &post_bracket[..close_bracket_idx];
        let post_alt = &post_bracket[close_bracket_idx + 1..];

        if post_alt.starts_with('(') {
            let Some(close_paren_idx) = post_alt.find(')') else {
                result.push_str("![");
                result.push_str(alt_text);
                result.push(']');
                remaining = post_alt;
                continue;
            };

            let url = &post_alt[1..close_paren_idx];

            let new_url = if !url.starts_with("http://")
                && !url.starts_with("https://")
                && !url.starts_with("//")
                && !url.starts_with("data:")
            {
                format!("{}{}&w=1600&format=webp&q=85", cdn_prefix, url)
            } else {
                url.to_string()
            };

            result.push_str(&format!("![{alt_text}]({new_url})"));
            remaining = &post_alt[close_paren_idx + 1..];
        } else {
            result.push_str("![");
            result.push_str(alt_text);
            result.push(']');
            remaining = post_alt;
        }
    }

    result.push_str(remaining);
    result
}

fn rewrite_html_images(body: &str, cdn_prefix: &str) -> String {
    let mut result = String::with_capacity(body.len());
    let mut remaining = body;

    while let Some(start_idx) = remaining.find("<img ") {
        result.push_str(&remaining[..start_idx]);
        let tag_content = &remaining[start_idx..];

        let Some(end_idx) = tag_content.find('>') else {
            result.push_str(remaining);
            return result;
        };

        let tag_inner = &tag_content[..end_idx + 1];
        let mut rewritten_tag = tag_inner.to_string();

        let mut src_val = None;
        for quote in ['"', '\''] {
            let pattern = format!("src={quote}");
            if let Some(pos) = tag_inner.find(&pattern) {
                let val_start = pos + pattern.len();
                if let Some(val_end) = tag_inner[val_start..].find(quote) {
                    src_val = Some((
                        val_start,
                        val_end,
                        tag_inner[val_start..val_start + val_end].to_string(),
                        quote,
                    ));
                    break;
                }
            }
        }

        if let Some((val_start, val_end, url, _quote)) = src_val {
            if !url.starts_with("http://")
                && !url.starts_with("https://")
                && !url.starts_with("//")
                && !url.starts_with("data:")
            {
                let new_url =
                    format!("{}{}&w=1600&format=webp&q=85", cdn_prefix, url);
                let before = &rewritten_tag[..val_start];
                let after = &rewritten_tag[val_start + val_end..];
                rewritten_tag = format!("{before}{new_url}{after}");
            }
        }

        result.push_str(&rewritten_tag);
        remaining = &tag_content[end_idx + 1..];
    }

    result.push_str(remaining);
    result
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::plugin::Plugin;
    use tempfile::tempdir;

    #[test]
    fn split_frontmatter_extracts_yaml_block() {
        let input = "---\ntitle: Hello\n---\nBody here\n";
        let (fm, body) = split_frontmatter(input);
        assert_eq!(fm, "---\ntitle: Hello\n---\n");
        assert_eq!(body, "Body here\n");
    }

    #[test]
    fn split_frontmatter_returns_empty_when_absent() {
        let input = "Just a body\nwith two lines\n";
        let (fm, body) = split_frontmatter(input);
        assert_eq!(fm, "");
        assert_eq!(body, input);
    }

    #[test]
    fn needs_expansion_detects_strikethrough() {
        assert!(needs_expansion("hello ~~world~~"));
    }

    #[test]
    fn needs_expansion_detects_task_list() {
        assert!(needs_expansion("- [ ] todo\n- [x] done\n"));
    }

    #[test]
    fn needs_expansion_detects_table() {
        let body = "| a | b |\n|---|---|\n| 1 | 2 |\n";
        assert!(needs_expansion(body));
    }

    #[test]
    fn needs_expansion_returns_false_for_plain_markdown() {
        assert!(!needs_expansion("# Heading\n\nA paragraph.\n"));
    }

    #[test]
    fn is_separator_row_accepts_aligned_separators() {
        assert!(is_separator_row("|---|---|"));
        assert!(is_separator_row("| :--- | :---: | ---: |"));
        assert!(!is_separator_row("| a | b |"));
        assert!(!is_separator_row("plain text"));
    }

    #[test]
    fn is_task_list_line_recognises_open_and_done() {
        assert!(is_task_list_line("- [ ] todo"));
        assert!(is_task_list_line("- [x] done"));
        assert!(is_task_list_line("- [X] done"));
        assert!(is_task_list_line("  * [ ] indented"));
        assert!(!is_task_list_line("- regular bullet"));
        assert!(!is_task_list_line("[ ] no bullet"));
    }

    #[test]
    fn apply_strikethrough_wraps_simple_pair() {
        assert_eq!(
            apply_strikethrough("hello ~~world~~ done"),
            "hello <del>world</del> done"
        );
    }

    #[test]
    fn apply_strikethrough_skips_inside_code_span() {
        assert_eq!(
            apply_strikethrough("`~~not~~` but ~~yes~~"),
            "`~~not~~` but <del>yes</del>"
        );
    }

    #[test]
    fn apply_strikethrough_leaves_unmatched_tildes() {
        assert_eq!(apply_strikethrough("just ~~ here"), "just ~~ here");
    }

    #[test]
    fn expand_gfm_renders_table_block() {
        let input = "Intro\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\nOutro\n";
        let out = expand_gfm(input, None);
        assert!(out.contains("<table>"), "got: {out}");
        assert!(out.contains("<th>a</th>"));
        assert!(out.contains("<td>1</td>"));
        assert!(out.contains("Intro"));
        assert!(out.contains("Outro"));
    }

    #[test]
    fn expand_gfm_renders_task_list_block() {
        let input = "- [ ] one\n- [x] two\n";
        let out = expand_gfm(input, None);
        assert!(out.contains("<ul>"), "got: {out}");
        assert!(out.contains("type=\"checkbox\""));
        assert!(out.contains("disabled"));
        assert!(out.contains("checked"));
    }

    #[test]
    fn expand_gfm_renders_strikethrough_inline() {
        let input = "Some ~~old~~ new text\n";
        let out = expand_gfm(input, None);
        assert_eq!(out, "Some <del>old</del> new text\n");
    }

    #[test]
    fn expand_gfm_preserves_fenced_code_contents() {
        let input =
            "```\n| a | b |\n|---|---|\n~~not strike~~\n- [ ] not task\n```\n";
        let out = expand_gfm(input, None);
        // Nothing inside the fence should be transformed.
        assert!(out.contains("| a | b |"));
        assert!(out.contains("~~not strike~~"));
        assert!(out.contains("- [ ] not task"));
        assert!(!out.contains("<table>"));
        assert!(!out.contains("<del>"));
    }

    #[test]
    fn expand_gfm_preserves_frontmatter_unchanged() {
        let input = "---\ntitle: Test\n---\n~~strike~~ this\n";
        let out = expand_gfm(input, None);
        assert!(out.starts_with("---\ntitle: Test\n---\n"));
        assert!(out.contains("<del>strike</del>"));
    }

    #[test]
    fn expand_gfm_returns_input_unchanged_when_no_features() {
        let input = "# Heading\n\nA paragraph with no extensions.\n";
        let out = expand_gfm(input, None);
        assert_eq!(out, input);
    }

    #[test]
    fn expand_gfm_handles_tildes_in_tilde_fenced_code() {
        // ~~~ fences must also protect contents.
        let input = "~~~\n~~text~~\n~~~\n";
        let out = expand_gfm(input, None);
        assert!(out.contains("~~text~~"));
        assert!(!out.contains("<del>"));
    }

    #[test]
    fn plugin_transforms_markdown_files_in_place() {
        let dir = tempdir().unwrap();
        let content = dir.path().join("content");
        fs::create_dir_all(&content).unwrap();
        fs::write(
            content.join("post.md"),
            "---\ntitle: Test\n---\n~~old~~ new\n",
        )
        .unwrap();
        fs::write(content.join("untouched.md"), "# Plain\n\nNothing fancy.\n")
            .unwrap();

        let ctx =
            PluginContext::new(&content, dir.path(), dir.path(), dir.path());
        MarkdownExtPlugin.before_compile(&ctx).unwrap();

        let post = fs::read_to_string(content.join("post.md")).unwrap();
        assert!(post.contains("<del>old</del>"));
        assert!(post.starts_with("---\ntitle: Test\n---\n"));

        let untouched =
            fs::read_to_string(content.join("untouched.md")).unwrap();
        assert_eq!(untouched, "# Plain\n\nNothing fancy.\n");
    }

    #[test]
    fn plugin_returns_ok_when_content_dir_missing() {
        let dir = tempdir().unwrap();
        let ctx = PluginContext::new(
            &dir.path().join("missing"),
            dir.path(),
            dir.path(),
            dir.path(),
        );
        MarkdownExtPlugin.before_compile(&ctx).unwrap();
    }

    #[test]
    fn plugin_name_is_markdown_ext() {
        assert_eq!(MarkdownExtPlugin.name(), "markdown-ext");
    }

    #[test]
    fn test_cdn_prefix_rewrites_images() {
        let input = "![Alt text](/images/pic.png)\n<img src=\"/images/pic2.png\" alt=\"HTML img\">";
        let prefix = "https://cloudcdn.pro/api/transform?url=";
        let out = expand_gfm(input, Some(prefix));
        assert!(out.contains("![Alt text](https://cloudcdn.pro/api/transform?url=/images/pic.png&w=1600&format=webp&q=85)"));
        assert!(out.contains("src=\"https://cloudcdn.pro/api/transform?url=/images/pic2.png&w=1600&format=webp&q=85\""));
    }

    #[test]
    fn split_frontmatter_optional_trailing_newline() {
        let input = "---\ntitle: Hello\n---Body here";
        let (fm, body) = split_frontmatter(input);
        assert_eq!(fm, "---\ntitle: Hello\n---");
        assert_eq!(body, "Body here");
    }

    #[test]
    fn test_cdn_prefix_no_gfm_expansion() {
        let input = "![Alt](/img.png)";
        let prefix = "https://cdn.example.com/";
        let out = expand_gfm(input, Some(prefix));
        assert!(out.contains("https://cdn.example.com//img.png"));
    }

    #[test]
    fn test_rewrite_html_images_edge_cases() {
        let prefix = "https://cdn/";

        let out1 = rewrite_html_images("<img src='foo.png'>", prefix);
        assert!(out1.contains("https://cdn/foo.png"));

        assert_eq!(
            rewrite_html_images("<img src=\"http://foo.com/a.png\">", prefix),
            "<img src=\"http://foo.com/a.png\">"
        );
        assert_eq!(
            rewrite_html_images("<img src=\"https://foo.com/a.png\">", prefix),
            "<img src=\"https://foo.com/a.png\">"
        );
        assert_eq!(
            rewrite_html_images("<img src=\"//foo.com/a.png\">", prefix),
            "<img src=\"//foo.com/a.png\">"
        );
        assert_eq!(
            rewrite_html_images(
                "<img src=\"data:image/png;base64,...\">",
                prefix
            ),
            "<img src=\"data:image/png;base64,...\">"
        );

        assert_eq!(
            rewrite_html_images("<img src=\"foo.png\"", prefix),
            "<img src=\"foo.png\""
        );
    }

    #[test]
    fn test_rewrite_markdown_images_edge_cases() {
        let prefix = "https://cdn/";

        assert_eq!(
            rewrite_markdown_images("![unclosed alt text", prefix),
            "![unclosed alt text"
        );

        assert_eq!(
            rewrite_markdown_images("![alt](unclosed-paren", prefix),
            "![alt](unclosed-paren"
        );

        assert_eq!(
            rewrite_markdown_images("![alt] no paren", prefix),
            "![alt] no paren"
        );

        assert_eq!(
            rewrite_markdown_images("![alt](http://site.com/img.png)", prefix),
            "![alt](http://site.com/img.png)"
        );
        assert_eq!(
            rewrite_markdown_images("![alt](https://site.com/img.png)", prefix),
            "![alt](https://site.com/img.png)"
        );
        assert_eq!(
            rewrite_markdown_images("![alt](//site.com/img.png)", prefix),
            "![alt](//site.com/img.png)"
        );
        assert_eq!(
            rewrite_markdown_images(
                "![alt](data:image/png;base64,123)",
                prefix
            ),
            "![alt](data:image/png;base64,123)"
        );
    }
}