dioxus-docs-kit-build 0.6.0

Build-time helper for dioxus-docs-kit: generates content maps from _nav.json
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::path::Path;

#[derive(Deserialize)]
struct NavConfig {
    groups: Vec<NavGroup>,
}

#[derive(Deserialize)]
struct NavGroup {
    pages: Vec<String>,
}

/// Builds the absolute path used inside the generated `include_str!()`.
///
/// Backslashes are normalized to forward slashes so the generated string
/// literal is valid on Windows (`C:\Users\...` would otherwise contain
/// invalid escape sequences).
fn include_path(manifest_dir: &str, relative: &str) -> String {
    format!("{manifest_dir}/{relative}").replace('\\', "/")
}

/// Emits a `map.insert(...)` line for `relative` if the file exists.
///
/// Missing files are skipped with a warning, but still registered via
/// `rerun-if-changed` so the build script re-runs once the file is created
/// (cargo re-runs when a watched path does not exist).
fn emit_entry(code: &mut String, manifest_dir: &str, key: &str, relative: &str) {
    let full_path = include_path(manifest_dir, relative);

    println!("cargo:rerun-if-changed={relative}");

    if !Path::new(&full_path).exists() {
        println!(
            "cargo:warning=\"{key}\" is listed in the nav/manifest but {full_path} does not exist — the page will 404. Create the file or remove the entry."
        );
        return;
    }

    // Use absolute path so include_str! works from OUT_DIR
    code.push_str(&format!(
        "    map.insert(\"{key}\", include_str!(\"{full_path}\"));\n"
    ));
}

/// Generates `doc_content_generated.rs` in `OUT_DIR` from a `_nav.json` file.
///
/// Call this from your `build.rs`:
///
/// ```rust,ignore
/// fn main() {
///     dioxus_docs_kit_build::generate_content_map("docs/_nav.json");
/// }
/// ```
///
/// The generated file is an expression that returns a `HashMap<&'static str, &'static str>`
/// and is intended to be used with `include!()`.
///
/// The docs directory is inferred from the parent of `nav_json_path`
/// (e.g. `"docs/_nav.json"` → `"docs"`).
pub fn generate_content_map(nav_json_path: &str) {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();

    println!("cargo:rerun-if-changed={nav_json_path}");

    let json = fs::read_to_string(nav_json_path)
        .unwrap_or_else(|e| panic!("Failed to read {nav_json_path}: {e}"));
    let nav: NavConfig = serde_json::from_str(&json)
        .unwrap_or_else(|e| panic!("Failed to parse {nav_json_path}: {e}"));

    // Infer docs directory from nav path parent (e.g. "docs/_nav.json" → "docs")
    let docs_dir = Path::new(nav_json_path)
        .parent()
        .and_then(|p| p.to_str())
        .unwrap_or("docs");

    let mut code = String::from("// Auto-generated by dioxus-docs-kit-build — do not edit\n{\n");
    code.push_str("    let mut map = std::collections::HashMap::new();\n");

    for group in &nav.groups {
        for page in &group.pages {
            let mdx_path = format!("{docs_dir}/{page}.mdx");
            emit_entry(&mut code, &manifest_dir, page, &mdx_path);
        }
    }

    code.push_str("    map\n}\n");

    let out_dir = env::var("OUT_DIR").unwrap();
    let dest = Path::new(&out_dir).join("doc_content_generated.rs");
    fs::write(&dest, code).expect("Failed to write generated file");

    // Fail the build on malformed docs frontmatter, and warn about broken
    // internal links (warnings only — never fail the build for links).
    let pages: Vec<String> = nav
        .groups
        .iter()
        .flat_map(|g| g.pages.iter().cloned())
        .collect();
    validate_docs(&manifest_dir, docs_dir, &pages);
}

// ============================================================================
// Blog content map generation
// ============================================================================

#[derive(Deserialize)]
struct BlogManifest {
    posts: Vec<String>,
}

/// Generates `blog_content_generated.rs` in `OUT_DIR` from a `_blog.json` file.
///
/// Call this from your `build.rs`:
///
/// ```rust,ignore
/// fn main() {
///     dioxus_docs_kit_build::generate_blog_content_map("blog/_blog.json");
/// }
/// ```
///
/// The generated file is an expression that returns a `HashMap<&'static str, &'static str>`
/// and is intended to be used with `include!()`.
///
/// The blog directory is inferred from the parent of `manifest_path`
/// (e.g. `"blog/_blog.json"` → `"blog"`).
///
/// The manifest JSON itself is embedded under the key `"__manifest__"` so the
/// runtime library can parse author definitions and other metadata.
pub fn generate_blog_content_map(manifest_path: &str) {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();

    println!("cargo:rerun-if-changed={manifest_path}");

    let json = fs::read_to_string(manifest_path)
        .unwrap_or_else(|e| panic!("Failed to read {manifest_path}: {e}"));
    let manifest: BlogManifest = serde_json::from_str(&json)
        .unwrap_or_else(|e| panic!("Failed to parse {manifest_path}: {e}"));

    // Infer blog directory from manifest path parent
    let blog_dir = Path::new(manifest_path)
        .parent()
        .and_then(|p| p.to_str())
        .unwrap_or("blog");

    let mut code = String::from("// Auto-generated by dioxus-docs-kit-build — do not edit\n{\n");
    code.push_str("    let mut map = std::collections::HashMap::new();\n");

    // Embed the manifest JSON itself
    let manifest_full_path = include_path(&manifest_dir, manifest_path);
    code.push_str(&format!(
        "    map.insert(\"__manifest__\", include_str!(\"{manifest_full_path}\"));\n"
    ));

    for slug in &manifest.posts {
        let mdx_path = format!("{blog_dir}/{slug}.mdx");
        emit_entry(&mut code, &manifest_dir, slug, &mdx_path);

        // Fail the build on malformed frontmatter instead of letting the post
        // silently vanish from the site at runtime.
        let full_path = include_path(&manifest_dir, &mdx_path);
        if let Ok(content) = fs::read_to_string(&full_path) {
            validate_blog_frontmatter(&mdx_path, &content);
        }
    }

    code.push_str("    map\n}\n");

    let out_dir = env::var("OUT_DIR").unwrap();
    let dest = Path::new(&out_dir).join("blog_content_generated.rs");
    fs::write(&dest, code).expect("Failed to write generated file");
}

// ============================================================================
// Build-time validation: internal links + frontmatter
// ============================================================================

/// Convert a heading title to a URL anchor slug.
///
/// Mirrors `dioxus_mdx`'s `slugify` (in `components/toc.rs`) exactly, so
/// build-time anchor checks resolve to the same ids the renderer injects. The
/// build crate cannot depend on `dioxus-mdx` (that would pull `dioxus` into
/// every consumer's build-dependencies), so this small function is duplicated.
fn slugify(text: &str) -> String {
    let text = text
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&amp;", "&");
    let text = strip_markdown_links(&text);
    text.to_lowercase()
        .chars()
        .filter_map(|c| {
            if c.is_alphanumeric() {
                Some(c)
            } else if c.is_whitespace() || c == '-' || c == '_' || c == '.' {
                Some('-')
            } else {
                None
            }
        })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

/// Reduce markdown links/images `[text](url)` to their text (mirrors
/// `dioxus_mdx`'s `strip_markdown_links`, for the same slug-agreement reason).
fn strip_markdown_links(text: &str) -> String {
    let mut out = String::new();
    let mut rest = text;
    while let Some(open) = rest.find('[') {
        if let Some(mid) = rest[open..].find("](") {
            let mid = open + mid;
            if let Some(close) = rest[mid..].find(')') {
                out.push_str(&rest[..open]);
                out.push_str(&rest[open + 1..mid]);
                rest = &rest[mid + close + 1..];
                continue;
            }
        }
        out.push_str(&rest[..=open]);
        rest = &rest[open + 1..];
    }
    out.push_str(rest);
    out
}

/// Remove fenced code blocks (``` or ~~~) so markdown-looking text inside code
/// samples is not mistaken for links or headings.
fn strip_code_fences(content: &str) -> String {
    let mut out = String::new();
    let mut fence: Option<char> = None;
    for line in content.lines() {
        let trimmed = line.trim_start();
        let marker = if trimmed.starts_with("```") {
            Some('`')
        } else if trimmed.starts_with("~~~") {
            Some('~')
        } else {
            None
        };
        match (fence, marker) {
            (None, Some(m)) => fence = Some(m), // opening fence
            (Some(open), Some(m)) if open == m => fence = None, // closing fence
            (None, None) => {
                out.push_str(line);
                out.push('\n');
            }
            _ => {} // inside a fence (or a mismatched fence marker within one)
        }
    }
    out
}

/// Extract anchor slugs for level 2-4 ATX headings, matching the ids the
/// renderer injects (`dioxus_mdx`'s `extract_headers` + `slugify`). H1 is
/// excluded (it is not linkable and is stripped as the duplicate page title).
fn extract_heading_slugs(content: &str) -> Vec<String> {
    let mut slugs = Vec::new();
    for line in content.lines() {
        let hashes = line.bytes().take_while(|&b| b == b'#').count();
        if (2..=4).contains(&hashes) && matches!(line.as_bytes().get(hashes), Some(b' ' | b'\t')) {
            let title = line[hashes..].trim();
            if !title.is_empty() {
                slugs.push(slugify(title));
            }
        }
    }
    slugs
}

/// Extract non-image markdown link targets (`[text](target)`), stripping any
/// `"title"` suffix and `<>` wrappers. Image links (`![...](...)`) are skipped.
fn extract_links(content: &str) -> Vec<String> {
    let bytes = content.as_bytes();
    let mut links = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'[' {
            let is_image = i > 0 && bytes[i - 1] == b'!';
            if let Some(close) = (i + 1..bytes.len()).find(|&j| bytes[j] == b']') {
                if bytes.get(close + 1) == Some(&b'(')
                    && let Some(pclose) = (close + 2..bytes.len()).find(|&j| bytes[j] == b')')
                {
                    if !is_image
                        && let Some(tok) = content[close + 2..pclose].split_whitespace().next()
                    {
                        let tok = tok.trim_start_matches('<').trim_end_matches('>');
                        if !tok.is_empty() {
                            links.push(tok.to_string());
                        }
                    }
                    i = pclose + 1;
                    continue;
                }
                i = close + 1;
                continue;
            }
        }
        i += 1;
    }
    links
}

/// Returns true if `target` begins with a URL scheme (`https:`, `mailto:`, …).
fn has_scheme(target: &str) -> bool {
    let mut chars = target.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() => {}
        _ => return false,
    }
    for c in chars {
        if c == ':' {
            return true;
        }
        if !(c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') {
            return false;
        }
    }
    false
}

/// Strip a trailing slash and any `.mdx`/`.md` extension so a link target lines
/// up with the extension-less nav page keys.
fn normalize_page_key(s: &str) -> String {
    let s = s.trim_end_matches('/');
    let s = s
        .strip_suffix(".mdx")
        .or_else(|| s.strip_suffix(".md"))
        .unwrap_or(s);
    s.to_string()
}

/// Resolve a relative link target against the directory of `current_page`.
/// Returns `None` if the path escapes the docs root.
fn resolve_relative(current_page: &str, path: &str) -> Option<String> {
    let mut base: Vec<&str> = current_page.split('/').collect();
    base.pop(); // drop the current file component, keeping its directory
    for seg in path.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                base.pop()?;
            }
            s => base.push(s),
        }
    }
    Some(base.join("/"))
}

/// Outcome of resolving an internal link target to a docs page.
enum LinkResolution {
    /// Resolved to a known page (carries its key for anchor validation).
    Valid(String),
    /// Clearly targets a docs page, but no page matches.
    Broken,
    /// Not validatable (external route, runtime-generated section, …).
    Skip,
}

/// A group directory is "validatable" only if it holds at least two static nav
/// pages. Single-page groups (e.g. an `api-reference` group whose remaining
/// pages are generated at runtime from an OpenAPI spec) are skipped, since the
/// build crate cannot know those slugs and would false-positive on them.
fn group_is_validatable(page: &str, group_counts: &HashMap<&str, usize>) -> bool {
    page.split_once('/')
        .map(|(g, _)| group_counts.get(g).copied().unwrap_or(0) >= 2)
        .unwrap_or(false)
}

/// Classify a root-absolute link (e.g. `/docs/guides/foo`). The consumer's base
/// path (e.g. `/docs`) is unknown, so both the full path and the path with its
/// first segment stripped are tried against the known pages.
fn classify_root_absolute(
    rest: &str,
    page_set: &HashSet<&str>,
    group_counts: &HashMap<&str, usize>,
) -> LinkResolution {
    let full = normalize_page_key(rest);
    let stripped = rest.split_once('/').map(|(_, s)| normalize_page_key(s));

    if page_set.contains(full.as_str()) {
        return LinkResolution::Valid(full);
    }
    if let Some(s) = &stripped
        && page_set.contains(s.as_str())
    {
        return LinkResolution::Valid(s.clone());
    }

    let clearly_docs = group_is_validatable(&full, group_counts)
        || stripped
            .as_ref()
            .is_some_and(|s| group_is_validatable(s, group_counts));
    if clearly_docs {
        LinkResolution::Broken
    } else {
        LinkResolution::Skip
    }
}

/// Classify a relative link (e.g. `../guides/foo`) resolved against the current
/// file's directory.
fn classify_relative(
    current_page: &str,
    path: &str,
    page_set: &HashSet<&str>,
    group_counts: &HashMap<&str, usize>,
) -> LinkResolution {
    let Some(resolved) = resolve_relative(current_page, path) else {
        return LinkResolution::Skip;
    };
    let resolved = normalize_page_key(&resolved);
    if resolved.is_empty() {
        return LinkResolution::Skip;
    }
    if page_set.contains(resolved.as_str()) {
        return LinkResolution::Valid(resolved);
    }
    if group_is_validatable(&resolved, group_counts) {
        LinkResolution::Broken
    } else {
        LinkResolution::Skip
    }
}

/// Validate a single link target found in `src`. Emits `cargo:warning` for
/// broken page targets and missing anchors.
fn check_link(
    src: &str,
    current_page: &str,
    target: &str,
    page_set: &HashSet<&str>,
    group_counts: &HashMap<&str, usize>,
    headings: &HashMap<&str, HashSet<String>>,
) {
    let (path_part, fragment) = match target.split_once('#') {
        Some((p, f)) => (p, Some(f)),
        None => (target, None),
    };

    // Same-page anchor (`#heading`).
    if path_part.is_empty() {
        if let Some(frag) = fragment {
            check_anchor(src, current_page, target, frag, headings);
        }
        return;
    }

    // Skip external links (`https:`, `mailto:`, protocol-relative `//host`).
    if path_part.starts_with("//") || has_scheme(path_part) {
        return;
    }

    let resolution = if let Some(rest) = path_part.strip_prefix('/') {
        classify_root_absolute(rest, page_set, group_counts)
    } else {
        classify_relative(current_page, path_part, page_set, group_counts)
    };

    match resolution {
        LinkResolution::Valid(page) => {
            if let Some(frag) = fragment {
                check_anchor(src, &page, target, frag, headings);
            }
        }
        LinkResolution::Broken => {
            println!(
                "cargo:warning={src}: internal link target \"{target}\" does not match any known docs page"
            );
        }
        LinkResolution::Skip => {}
    }
}

/// Validate that `fragment` matches a heading anchor in `page`. Skipped when the
/// target page's headings are unknown (its file was not read).
fn check_anchor(
    src: &str,
    page: &str,
    target: &str,
    fragment: &str,
    headings: &HashMap<&str, HashSet<String>>,
) {
    if fragment.is_empty() {
        return;
    }
    if let Some(anchors) = headings.get(page)
        && !anchors.contains(&slugify(fragment))
    {
        println!(
            "cargo:warning={src}: link \"{target}\" points to \"#{fragment}\" but no heading with that anchor exists in {page}"
        );
    }
}

/// Validate docs frontmatter (build error on malformed) and internal markdown
/// links (warnings only) for every existing nav page.
fn validate_docs(manifest_dir: &str, docs_dir: &str, pages: &[String]) {
    // Read each existing page once.
    let mut contents: Vec<(String, String)> = Vec::new();
    for page in pages {
        let mdx_path = format!("{docs_dir}/{page}.mdx");
        let full_path = include_path(manifest_dir, &mdx_path);
        if let Ok(raw) = fs::read_to_string(&full_path) {
            validate_docs_frontmatter(&mdx_path, &raw);
            contents.push((page.clone(), raw));
        }
    }

    let page_set: HashSet<&str> = pages.iter().map(String::as_str).collect();

    let mut group_counts: HashMap<&str, usize> = HashMap::new();
    for page in pages {
        if let Some((group, _)) = page.split_once('/') {
            *group_counts.entry(group).or_insert(0) += 1;
        }
    }

    // Strip fenced code once and reuse for both headings and link scanning.
    let stripped: Vec<(String, String)> = contents
        .iter()
        .map(|(page, raw)| (page.clone(), strip_code_fences(raw)))
        .collect();

    let mut headings: HashMap<&str, HashSet<String>> = HashMap::new();
    for (page, body) in &stripped {
        headings.insert(
            page.as_str(),
            extract_heading_slugs(body).into_iter().collect(),
        );
    }

    for (page, body) in &stripped {
        let src = format!("{docs_dir}/{page}.mdx");
        for target in extract_links(body) {
            check_link(&src, page, &target, &page_set, &group_counts, &headings);
        }
    }
}

/// A docs page's frontmatter block (if present) must parse as a YAML mapping.
/// No particular fields are required for docs pages.
fn validate_docs_frontmatter(path: &str, content: &str) {
    let content = content.trim();
    if !content.starts_with("---") {
        return;
    }
    let after = &content[3..];
    // No closing delimiter → not a frontmatter block (matches runtime behavior).
    let Some(end) = after.find("\n---") else {
        return;
    };
    let yaml = after[..end].trim();
    if yaml.is_empty() {
        return; // an empty frontmatter block is valid
    }
    match serde_yaml::from_str::<serde_yaml::Value>(yaml) {
        Ok(serde_yaml::Value::Mapping(_)) => {}
        // The runtime treats an unparseable leading block as page content and
        // still renders the page (a `---`-fenced paragraph is legal markdown),
        // so a hard build failure here would reject pages that work. Warn only.
        Ok(_) => println!(
            "cargo:warning={path}: leading --- block is not a YAML mapping and will render as page content, not frontmatter"
        ),
        Err(e) => println!(
            "cargo:warning={path}: leading --- block is not valid YAML ({e}) and will render as page content, not frontmatter"
        ),
    }
}

/// Blog frontmatter fields, mirroring
/// `dioxus_docs_kit::blog::types::BlogFrontmatter` (which a build crate cannot
/// depend on). ALL fields are mirrored, including optional ones: a
/// present-but-wrong-typed optional field (e.g. `tags: rust` instead of a
/// sequence) is a hard deserialize error at runtime that silently drops the
/// post, so it must fail the build here too.
#[derive(Deserialize)]
#[allow(dead_code)]
struct BlogFrontmatterCheck {
    title: String,
    #[serde(default)]
    description: Option<String>,
    date: String,
    author: String,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default, rename = "coverImage")]
    cover_image: Option<String>,
    #[serde(default)]
    draft: bool,
    #[serde(default)]
    featured: bool,
}

/// A blog post must have a valid frontmatter block carrying the required
/// fields, or the build fails (the post would otherwise silently vanish from
/// the site at runtime). The extraction mirrors `extract_blog_frontmatter`.
fn validate_blog_frontmatter(path: &str, content: &str) {
    let content = content.trim();
    if !content.starts_with("---") {
        panic!("{path}: missing frontmatter block (expected leading ---)");
    }
    let after = &content[3..];
    let Some(end) = after.find("\n---") else {
        panic!("{path}: unclosed frontmatter block (missing closing ---)");
    };
    let yaml = after[..end].trim();
    if let Err(e) = serde_yaml::from_str::<BlogFrontmatterCheck>(yaml) {
        panic!("{path}: malformed frontmatter: {e}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn include_path_joins_with_forward_slash() {
        assert_eq!(
            include_path("/home/me/project", "docs/intro.mdx"),
            "/home/me/project/docs/intro.mdx"
        );
    }

    #[test]
    fn include_path_normalizes_windows_backslashes() {
        assert_eq!(
            include_path("C:\\Users\\me\\project", "docs\\intro.mdx"),
            "C:/Users/me/project/docs/intro.mdx"
        );
    }

    // ---- link validation ---------------------------------------------------

    // Mirrors `dioxus_mdx`'s own `slugify` test cases.
    #[test]
    fn slugify_matches_mdx() {
        assert_eq!(slugify("Hello World"), "hello-world");
        assert_eq!(slugify("Getting Started!"), "getting-started");
        assert_eq!(slugify("API v1.0"), "api-v1-0");
        assert_eq!(slugify("Tips & Tricks"), "tips-tricks");
        assert_eq!(slugify("Tips &amp; Tricks"), "tips-tricks");
        assert_eq!(slugify("Q&A"), "qa");
        assert_eq!(slugify("a &lt; b"), "a-b");
        assert_eq!(slugify("See [the docs](https://x.y/z)"), "see-the-docs");
    }

    #[test]
    fn extract_links_skips_images() {
        let md = "see ![alt](/img/logo.png) and [Quickstart](/docs/getting-started/quickstart)";
        assert_eq!(
            extract_links(md),
            vec!["/docs/getting-started/quickstart".to_string()]
        );
    }

    #[test]
    fn extract_links_strips_title_and_angle_brackets() {
        let md = "[a](/docs/x \"the title\") and [b](</docs/y>)";
        assert_eq!(
            extract_links(md),
            vec!["/docs/x".to_string(), "/docs/y".to_string()]
        );
    }

    #[test]
    fn strip_code_fences_removes_fenced_links() {
        let md = "before\n```\n[not a link](/docs/nope)\n```\nafter [real](/docs/real)";
        let body = strip_code_fences(md);
        assert!(!body.contains("nope"));
        assert_eq!(extract_links(&body), vec!["/docs/real".to_string()]);
    }

    #[test]
    fn has_scheme_detects_external() {
        assert!(has_scheme("https://example.com"));
        assert!(has_scheme("mailto:me@example.com"));
        assert!(!has_scheme("/docs/guides/x"));
        assert!(!has_scheme("guides/x"));
        assert!(!has_scheme("../guides/x"));
    }

    #[test]
    fn resolve_relative_resolves_against_dir() {
        assert_eq!(
            resolve_relative("guides/blog", "customization").as_deref(),
            Some("guides/customization")
        );
        assert_eq!(
            resolve_relative("guides/blog", "../guides/customization").as_deref(),
            Some("guides/customization")
        );
        assert_eq!(
            resolve_relative("getting-started/introduction", "../guides/basic-usage").as_deref(),
            Some("guides/basic-usage")
        );
        // Escapes the docs root.
        assert_eq!(resolve_relative("changelog", "../../x"), None);
    }

    #[test]
    fn extract_heading_slugs_covers_h2_to_h4_only() {
        let md = "# Title\n## Section One\n### Sub Section\n##### Too Deep\ntext\n";
        assert_eq!(
            extract_heading_slugs(md),
            vec!["section-one".to_string(), "sub-section".to_string()]
        );
    }

    fn sample_page_data() -> (Vec<&'static str>, HashMap<&'static str, usize>) {
        let pages = vec![
            "getting-started/introduction",
            "getting-started/quickstart",
            "guides/basic-usage",
            "guides/customization",
            "guides/integration",
            "guides/blog",
            "api-reference/overview",
            "changelog",
        ];
        let mut group_counts: HashMap<&str, usize> = HashMap::new();
        for p in &pages {
            if let Some((g, _)) = p.split_once('/') {
                *group_counts.entry(g).or_insert(0) += 1;
            }
        }
        (pages, group_counts)
    }

    #[test]
    fn root_absolute_heuristic() {
        let (pages, group_counts) = sample_page_data();
        let page_set: HashSet<&str> = pages.iter().copied().collect();

        // Valid under a `/docs` base path.
        assert!(matches!(
            classify_root_absolute("docs/guides/basic-usage", &page_set, &group_counts),
            LinkResolution::Valid(_)
        ));
        // Valid under an empty (`/`) base path.
        assert!(matches!(
            classify_root_absolute("getting-started/introduction", &page_set, &group_counts),
            LinkResolution::Valid(_)
        ));
        // Broken: a dense group, but no such page.
        assert!(matches!(
            classify_root_absolute("docs/guides/nope", &page_set, &group_counts),
            LinkResolution::Broken
        ));
        // Skip: api-reference has a single static page; the rest are runtime
        // OpenAPI operations the build crate cannot see.
        assert!(matches!(
            classify_root_absolute("docs/api-reference/getUser", &page_set, &group_counts),
            LinkResolution::Skip
        ));
        // Skip: non-docs routes.
        assert!(matches!(
            classify_root_absolute("blog/hello", &page_set, &group_counts),
            LinkResolution::Skip
        ));
    }

    #[test]
    fn relative_heuristic() {
        let (pages, group_counts) = sample_page_data();
        let page_set: HashSet<&str> = pages.iter().copied().collect();

        assert!(matches!(
            classify_relative(
                "guides/basic-usage",
                "customization",
                &page_set,
                &group_counts
            ),
            LinkResolution::Valid(_)
        ));
        assert!(matches!(
            classify_relative("guides/basic-usage", "nope", &page_set, &group_counts),
            LinkResolution::Broken
        ));
        // Relative link into the single-page (OpenAPI) group is skipped.
        assert!(matches!(
            classify_relative(
                "api-reference/overview",
                "get-user",
                &page_set,
                &group_counts
            ),
            LinkResolution::Skip
        ));
    }

    // ---- frontmatter validation --------------------------------------------

    #[test]
    fn docs_frontmatter_valid_and_empty_ok() {
        validate_docs_frontmatter("x.mdx", "---\ntitle: Hi\n---\nbody");
        validate_docs_frontmatter("x.mdx", "---\n---\nbody");
        validate_docs_frontmatter("x.mdx", "no frontmatter here");
    }

    #[test]
    fn docs_frontmatter_unparseable_block_warns_but_does_not_panic() {
        // The runtime renders these pages (the block is treated as content),
        // so the build must not reject them — it only emits cargo:warning.
        validate_docs_frontmatter("x.mdx", "---\ntitle: [unclosed\n---\nbody");
        validate_docs_frontmatter("x.mdx", "---\n- a\n- b\n---\nbody");
        validate_docs_frontmatter("x.mdx", "---\nJust a fenced paragraph.\n---\nbody");
    }

    #[test]
    fn blog_frontmatter_valid_ok() {
        validate_blog_frontmatter(
            "p.mdx",
            "---\ntitle: Hi\ndate: \"2026-01-01\"\nauthor: jane\n---\nbody",
        );
    }

    #[test]
    #[should_panic(expected = "malformed frontmatter")]
    fn blog_frontmatter_bad_yaml_panics() {
        validate_blog_frontmatter(
            "p.mdx",
            "---\ntitle: [x\ndate: \"2026\"\nauthor: jane\n---\nbody",
        );
    }

    #[test]
    #[should_panic(expected = "missing field")]
    fn blog_frontmatter_missing_field_panics() {
        // No `date` field.
        validate_blog_frontmatter("p.mdx", "---\ntitle: Hi\nauthor: jane\n---\nbody");
    }

    #[test]
    #[should_panic(expected = "missing frontmatter")]
    fn blog_frontmatter_no_block_panics() {
        validate_blog_frontmatter("p.mdx", "just body, no frontmatter");
    }

    #[test]
    #[should_panic(expected = "invalid type")]
    fn blog_frontmatter_wrong_typed_optional_field_panics() {
        // `tags` must be a sequence; a scalar fails deserialization at runtime
        // and would silently drop the post, so it must fail the build.
        validate_blog_frontmatter(
            "p.mdx",
            "---\ntitle: Hi\ndate: \"2026-01-01\"\nauthor: jane\ntags: rust\n---\nbody",
        );
    }

    #[test]
    fn blog_frontmatter_optional_fields_ok() {
        validate_blog_frontmatter(
            "p.mdx",
            "---\ntitle: Hi\ndate: \"2026-01-01\"\nauthor: jane\ntags: [rust, web]\ndraft: true\ncoverImage: cover.png\n---\nbody",
        );
    }
}