euv-docs 0.48.1

Cross-platform documentation viewer and static site generator powered by euv and euv-ui.
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
use super::*;

/// Parses a single Markdown document with optional YAML frontmatter into a `DocPage`.
///
/// # Arguments
///
/// - `&str` - Canonical route path for this page.
/// - `&str` - Section label derived from directory hierarchy.
/// - `&str` - Raw Markdown source text.
///
/// # Returns
///
/// - `DocPage` - Parsed structured documentation page.
#[must_use]
pub fn parse_markdown_page(route: &str, default_section: &str, raw: &str) -> DocPage {
    let (frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(raw);
    parse_markdown_page_with_frontmatter(route, default_section, frontmatter, body)
}

/// Parses a Markdown body whose YAML frontmatter has already been extracted into a `DocPage`.
///
/// # Arguments
///
/// - `&str` - Canonical route path for this page.
/// - `&str` - Section label derived from directory hierarchy.
/// - `DocFrontmatter` - Pre-parsed YAML frontmatter metadata.
/// - `&str` - Markdown body slice following frontmatter.
///
/// # Returns
///
/// - `DocPage` - Parsed structured documentation page.
fn parse_markdown_page_with_frontmatter(
    route: &str,
    default_section: &str,
    frontmatter: DocFrontmatter,
    body: &str,
) -> DocPage {
    let mut blocks: Vec<DocBlock> = Vec::with_capacity((body.len() / 160).clamp(8, 256));
    let mut toc: Vec<DocTocItem> = Vec::with_capacity((body.len() / 512).clamp(4, 32));
    let mut seen_slugs: BTreeMap<String, usize> = BTreeMap::new();
    let mut active_heading: Option<(u8, Option<CowStr<'_>>)> = None;
    let mut first_h1_title: Option<String> = None;
    let mut in_paragraph: bool = false;
    let mut list_stack: Vec<String> = Vec::new();
    let mut blockquote_depth: usize = 0;
    let mut in_table: bool = false;
    let mut in_table_head: bool = false;
    let mut in_table_cell: bool = false;
    let mut table_headers: Vec<String> = Vec::new();
    let mut table_rows: Vec<Vec<String>> = Vec::new();
    let mut current_row: Vec<String> = Vec::new();
    let mut active_code_lang: Option<String> = None;
    let mut active_image_src: Option<String> = None;
    let mut image_alt_buf: String = String::new();
    let mut buffer: String = String::with_capacity(256);
    let parser: Parser<'_> = Parser::new_ext(body, Options::all());
    for event in parser {
        match event {
            Event::Start(Tag::Heading { level, id, .. }) => {
                active_heading = Some((heading_level_num(level), id));
                buffer.clear();
            }
            Event::End(TagEnd::Heading(_)) => {
                if let Some((level, custom_id)) = active_heading.take() {
                    let text: String = buffer.trim().to_string();
                    if !text.is_empty() {
                        if level == 1 && first_h1_title.is_none() {
                            first_h1_title = Some(text.clone());
                        }
                        let raw_slug: String = custom_id
                            .as_deref()
                            .map(slugify)
                            .filter(|s: &String| !s.is_empty())
                            .unwrap_or_else(|| slugify(&text));
                        let slug: String = deduplicate_slug(raw_slug, &mut seen_slugs);
                        if (2..=4).contains(&level) {
                            toc.push(DocTocItem::new(level, slug.clone(), text.clone()));
                        }
                        blocks.push(DocBlock::Heading { level, slug, text });
                    }
                }
                buffer.clear();
            }
            Event::Start(Tag::BlockQuote(_)) => {
                blockquote_depth += 1;
            }
            Event::End(TagEnd::BlockQuote(_)) => {
                blockquote_depth = blockquote_depth.saturating_sub(1);
            }
            Event::Start(Tag::Table(_)) => {
                in_table = true;
                table_headers.clear();
                table_rows.clear();
            }
            Event::End(TagEnd::Table) => {
                if in_table {
                    in_table = false;
                    let headers: Vec<String> = take(&mut table_headers);
                    let rows: Vec<Vec<String>> = take(&mut table_rows);
                    if !headers.is_empty() || !rows.is_empty() {
                        blocks.push(DocBlock::Table { headers, rows });
                    }
                }
            }
            Event::Start(Tag::TableHead) => {
                in_table_head = true;
                current_row.clear();
            }
            Event::End(TagEnd::TableHead) => {
                in_table_head = false;
                table_headers = take(&mut current_row);
            }
            Event::Start(Tag::TableRow) => {
                current_row.clear();
            }
            Event::End(TagEnd::TableRow) => {
                if !in_table_head {
                    table_rows.push(take(&mut current_row));
                }
            }
            Event::Start(Tag::TableCell) => {
                in_table_cell = true;
                buffer.clear();
            }
            Event::End(TagEnd::TableCell) => {
                if in_table_cell {
                    in_table_cell = false;
                    current_row.push(buffer.trim().to_string());
                }
                buffer.clear();
            }
            Event::Start(Tag::Paragraph) => {
                if list_stack.is_empty() {
                    in_paragraph = true;
                    buffer.clear();
                }
            }
            Event::End(TagEnd::Paragraph) => {
                if in_paragraph {
                    in_paragraph = false;
                    let text: String = buffer.trim().to_string();
                    if !text.is_empty() {
                        if blockquote_depth > 0 {
                            blocks.push(DocBlock::BlockQuote(text));
                        } else {
                            blocks.push(DocBlock::Paragraph(text));
                        }
                    }
                    buffer.clear();
                } else if let Some(top) = list_stack.last_mut()
                    && !top.is_empty()
                {
                    top.push(' ');
                }
            }
            Event::Start(Tag::Item) => {
                if let Some(parent_text) = list_stack.last_mut() {
                    let trimmed: String = parent_text.trim().to_string();
                    if !trimmed.is_empty() {
                        blocks.push(DocBlock::ListItem(trimmed));
                        parent_text.clear();
                    }
                }
                list_stack.push(String::new());
            }
            Event::End(TagEnd::Item) => {
                if let Some(item_buf) = list_stack.pop() {
                    let text: String = item_buf.trim().to_string();
                    if !text.is_empty() {
                        blocks.push(DocBlock::ListItem(text));
                    }
                }
            }
            Event::Start(Tag::CodeBlock(kind)) => {
                let lang: String = match kind {
                    CodeBlockKind::Fenced(tag) => {
                        let trimmed: &str = tag.split_whitespace().next().unwrap_or("");
                        if trimmed.is_empty() {
                            DEFAULT_CODE_LANG.to_string()
                        } else {
                            trimmed.to_string()
                        }
                    }
                    CodeBlockKind::Indented => DEFAULT_CODE_LANG.to_string(),
                };
                active_code_lang = Some(lang);
                buffer.clear();
            }
            Event::End(TagEnd::CodeBlock) => {
                if let Some(language) = active_code_lang.take() {
                    let code: String = buffer.trim_end().to_string();
                    blocks.push(DocBlock::Code { language, code });
                }
                buffer.clear();
            }
            Event::Start(Tag::Image { dest_url, .. }) => {
                active_image_src = Some(dest_url.into_string());
                image_alt_buf.clear();
            }
            Event::End(TagEnd::Image) => {
                if let Some(src) = active_image_src.take() {
                    let alt: String = image_alt_buf.trim().to_string();
                    image_alt_buf.clear();
                    if !src.is_empty() {
                        blocks.push(DocBlock::Image { alt, src });
                    }
                }
            }
            Event::TaskListMarker(checked) => {
                let marker: &str = if checked { "[x] " } else { "[ ] " };
                if let Some(top) = list_stack.last_mut() {
                    top.push_str(marker);
                } else {
                    buffer.push_str(marker);
                }
            }
            Event::Rule => {
                blocks.push(DocBlock::HorizontalRule);
            }
            Event::Text(text) | Event::Code(text) => {
                if active_image_src.is_some() {
                    image_alt_buf.push_str(&text);
                } else if !list_stack.is_empty()
                    && active_code_lang.is_none()
                    && active_heading.is_none()
                    && !in_table_cell
                {
                    if let Some(top) = list_stack.last_mut() {
                        top.push_str(&text);
                    }
                } else {
                    buffer.push_str(&text);
                }
            }
            Event::SoftBreak | Event::HardBreak => {
                let sep: char = if active_code_lang.is_some() {
                    '\n'
                } else {
                    ' '
                };
                if active_image_src.is_some() {
                    image_alt_buf.push(sep);
                } else if !list_stack.is_empty()
                    && active_code_lang.is_none()
                    && active_heading.is_none()
                    && !in_table_cell
                {
                    if let Some(top) = list_stack.last_mut() {
                        top.push(sep);
                    }
                } else {
                    buffer.push(sep);
                }
            }
            _ => {}
        }
    }
    let DocFrontmatter {
        title: fm_title,
        order: fm_order,
        tagline: fm_tagline,
        description: fm_description,
        section: fm_section,
        updated: fm_updated,
        date: fm_date,
        category: fm_categories,
        index: fm_index,
        expanded: fm_expanded,
        dir: fm_dir,
        password: fm_password,
        home: fm_home,
        hero_text: fm_hero_text,
        actions: fm_actions,
        stats: fm_stats,
        features: fm_features,
        sidebar: fm_sidebar,
        ..
    } = frontmatter;
    if toc.is_empty() {
        for b in blocks.iter() {
            if let DocBlock::Heading { level, slug, text } = b
                && *level == 1
            {
                toc.push(DocTocItem::new(*level, slug.clone(), text.clone()));
            }
        }
    }
    let fallback_title: String = first_h1_title
        .or_else(|| {
            toc.first()
                .map(|item: &DocTocItem| item.get_title().clone())
        })
        .unwrap_or_else(|| title_from_route(route));
    let title: String = fm_title.unwrap_or(fallback_title);
    if toc
        .first()
        .is_some_and(|item: &DocTocItem| item.get_title().trim().eq_ignore_ascii_case(title.trim()))
    {
        let _: DocTocItem = toc.remove(0);
    }
    let dir_order: Option<i32> = fm_dir.as_ref().and_then(DocDirFrontmatter::get_order);
    let dir_text: Option<String> = fm_dir
        .as_ref()
        .and_then(|d: &DocDirFrontmatter| d.try_get_text().clone())
        .filter(|s: &String| !s.trim().is_empty());
    let dir_collapsible: Option<bool> =
        fm_dir.as_ref().and_then(DocDirFrontmatter::get_collapsible);
    let default_order: i32 = if route == ROUTE_ROOT || fm_home {
        -1000
    } else {
        100
    };
    let order: i32 = fm_order.or(dir_order).unwrap_or(default_order);
    let section: String = fm_section.unwrap_or_else(|| default_section.to_string());
    let summary: String = fm_tagline.or(fm_description).unwrap_or_else(|| {
        blocks
            .iter()
            .find_map(|b: &DocBlock| match b {
                DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.clone()),
                _ => None,
            })
            .unwrap_or_default()
    });
    let resolved_updated: Option<String> = fm_updated.or_else(|| fm_date.clone());
    let mut page: DocPage = DocPage::new(
        route.to_string(),
        title,
        order,
        section,
        summary,
        blocks,
        toc,
    );
    page.set_markdown_body(body.to_string());
    page.set_updated(resolved_updated);
    page.set_home_meta(fm_home, fm_hero_text, fm_actions, fm_stats, fm_features);
    page.set_hide_sidebar(fm_sidebar == Some(false));
    page.set_dir_meta(
        fm_index == Some(false),
        fm_expanded,
        dir_order,
        dir_text,
        dir_collapsible,
    );
    page.set_page_meta(
        fm_password.filter(|pw: &String| !pw.trim().is_empty()),
        fm_date,
        fm_categories,
    );
    page
}

/// Deduplicates locale entries by content directory while preserving declaration order.
///
/// # Arguments
///
/// - `&[DocLocaleConfig]` - Declared locale entries from frontmatter.
///
/// # Returns
///
/// - `Vec<DocLocaleConfig>` - Unique locale entries ordered by first occurrence of `dir`.
#[must_use]
pub fn unique_locales(locales: &[DocLocaleConfig]) -> Vec<DocLocaleConfig> {
    let mut seen: BTreeSet<String> = BTreeSet::new();
    let mut out: Vec<DocLocaleConfig> = Vec::with_capacity(locales.len());
    for loc in locales.iter() {
        let key: String = loc.get_dir().trim().to_ascii_lowercase();
        if key.is_empty() {
            continue;
        }
        if seen.insert(key) {
            out.push(loc.clone());
        }
    }
    out
}

/// Inspects `<src_dir>/README.md` and `<src_dir>/../README.md` for a multi-locale `DocSiteConfig` frontmatter block.
///
/// # Arguments
///
/// - `&Path` - Source documentation directory (for example `docs/`).
///
/// # Returns
///
/// - `Option<DocSiteConfig>` - Parsed site and locale configuration when `site:` or `locales:` is declared.
#[must_use]
pub fn load_site_config(src_dir: &Path) -> Option<DocSiteConfig> {
    let mut candidates: Vec<PathBuf> = vec![src_dir.join(README_FILENAME)];
    if let Some(parent) = src_dir.parent() {
        candidates.push(parent.join(README_FILENAME));
    }
    let mut fallback: Option<DocSiteConfig> = None;
    for candidate in candidates.into_iter() {
        if !candidate.is_file() {
            continue;
        }
        let Ok(raw) = fs::read_to_string(&candidate) else {
            continue;
        };
        let (fm, _): (DocFrontmatter, &str) = split_frontmatter(&raw);
        let has_locales: bool = !fm.locales.is_empty();
        let has_site: bool = fm.site.is_some();
        if has_locales {
            return Some(DocSiteConfig {
                site: fm.site.unwrap_or_default(),
                locales: fm.locales,
            });
        }
        if has_site && fallback.is_none() {
            fallback = Some(DocSiteConfig {
                site: fm.site.unwrap_or_default(),
                locales: Vec::new(),
            });
        }
    }
    fallback
}

/// Loads a single locale content directory using shared `DocSiteConfig` and active `DocLocaleConfig` metadata.
///
/// # Arguments
///
/// - `&Path` - Root Markdown source directory containing per-locale folders (e.g. `docs/`).
/// - `&DocSiteConfig` - Shared site configuration parsed from root `README.md`.
/// - `&DocLocaleConfig` - Active locale entry specifying `dir`, `prefix`, `lang`, and labels.
/// - `Option<&Path>` - Optional output directory excluded from scanning.
///
/// # Returns
///
/// - `io::Result<DocSite>` - Loaded, ordered, and metadata-annotated documentation site for this locale.
pub fn load_locale_site(
    src_dir: &Path,
    cfg: &DocSiteConfig,
    locale: &DocLocaleConfig,
    exclude_dir: Option<&Path>,
) -> io::Result<DocSite> {
    let locale_dir_name: &str = locale.get_dir().trim();
    let content_dir: PathBuf = if locale_dir_name.is_empty() {
        src_dir.to_path_buf()
    } else {
        let joined: PathBuf = src_dir.join(locale_dir_name);
        if joined.is_dir() {
            joined
        } else {
            src_dir.to_path_buf()
        }
    };
    let title_override: Option<&str> = locale
        .try_get_title()
        .as_deref()
        .or_else(|| cfg.get_site().try_get_title().as_deref());
    let mut site: DocSite = load_doc_site_excluding(&content_dir, title_override, exclude_dir)?;
    if let Some(desc) = locale
        .try_get_description()
        .as_deref()
        .or_else(|| cfg.get_site().try_get_description().as_deref())
        && !desc.trim().is_empty()
    {
        site.tagline = desc.trim().to_string();
    }
    site.apply_locale_metadata(cfg, Some(locale));
    Ok(site)
}

/// Recursively loads all `.md` files under `root_dir` into a sorted `DocSite`.
///
/// # Arguments
///
/// - `&Path` - Root Markdown or project directory.
///
/// # Returns
///
/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
pub fn load_doc_site(root_dir: &Path) -> io::Result<DocSite> {
    load_doc_site_with_options(root_dir, None)
}

/// Recursively loads all `.md` files under `root_dir` with optional site title override and smart directory filtering.
///
/// # Arguments
///
/// - `&Path` - Root Markdown or project directory.
/// - `Option<&str>` - Optional explicit site title overriding frontmatter and folder heuristics.
///
/// # Returns
///
/// - `io::Result<DocSite>` - Loaded documentation site or I/O error.
pub fn load_doc_site_with_options(
    root_dir: &Path,
    title_override: Option<&str>,
) -> io::Result<DocSite> {
    load_doc_site_excluding(root_dir, title_override, None)
}

/// Recursively loads all `.md` files under `root_dir`, skipping `exclude_dir` when it sits inside `root_dir`.
///
/// # Arguments
///
/// - `&Path` - Root Markdown or project directory.
/// - `Option<&str>` - Optional explicit site title override.
/// - `Option<&Path>` - Optional output directory excluded from traversal.
///
/// # Returns
///
/// - `io::Result<DocSite>` - Loaded and section-ordered documentation site or I/O error.
pub(crate) fn load_doc_site_excluding(
    root_dir: &Path,
    title_override: Option<&str>,
    exclude_dir: Option<&Path>,
) -> io::Result<DocSite> {
    if !root_dir.exists() {
        return Err(Error::new(
            ErrorKind::NotFound,
            root_dir.display().to_string(),
        ));
    }
    let canonical_exclude: Option<PathBuf> =
        exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
    let mut files: Vec<PathBuf> = Vec::new();
    collect_markdown_files(root_dir, canonical_exclude.as_deref(), &mut files)?;
    files.sort();
    let mut pages: Vec<DocPage> = Vec::with_capacity(files.len());
    let mut seen_routes: BTreeSet<String> = BTreeSet::new();
    let mut detected_site_cfg: Option<DocSiteConfig> = None;
    let mut root_sidebar_ranks: HashMap<String, i32> = HashMap::new();
    let mut dir_sidebar_ranks: HashMap<(String, String), i32> = HashMap::new();
    let mut detected_title: Option<String> = None;
    let mut detected_tagline: Option<String> = None;
    for file_path in files.into_iter() {
        let raw: String = fs::read_to_string(&file_path)?;
        let rel: &Path = file_path.strip_prefix(root_dir).unwrap_or(&file_path);
        let (mut route, section): (String, String) = route_and_section_from_rel_path(rel);
        let (mut frontmatter, body): (DocFrontmatter, &str) = split_frontmatter(&raw);
        if !frontmatter.sidebar_order.is_empty() {
            let parent_rel: String = rel
                .parent()
                .map(|p: &Path| {
                    p.iter()
                        .map(|seg: &OsStr| slugify(&seg.to_string_lossy()))
                        .collect::<Vec<String>>()
                        .join("/")
                })
                .unwrap_or_default();
            for (rank_idx, entry_name) in frontmatter.sidebar_order.iter().enumerate() {
                let key: String = slugify(entry_name);
                if key.is_empty() {
                    continue;
                }
                let rank_val: i32 = (rank_idx as i32) * 10 - 500;
                if parent_rel.is_empty() {
                    let _: Option<i32> = root_sidebar_ranks.insert(key, rank_val);
                } else {
                    let _: Option<i32> =
                        dir_sidebar_ranks.insert((parent_rel.clone(), key), rank_val);
                }
            }
        }
        if route == ROUTE_ROOT {
            let fm_locales: Vec<DocLocaleConfig> = take(&mut frontmatter.locales);
            if let Some(site_cfg) = frontmatter.site.take() {
                if detected_title.is_none() {
                    detected_title = site_cfg.try_get_title().clone();
                }
                if detected_tagline.is_none() {
                    detected_tagline = site_cfg.try_get_description().clone();
                }
                detected_site_cfg = Some(DocSiteConfig {
                    site: site_cfg,
                    locales: fm_locales,
                });
            } else if !fm_locales.is_empty() {
                detected_site_cfg = Some(DocSiteConfig {
                    site: DocSiteFrontmatter::default(),
                    locales: fm_locales,
                });
            }
        }
        if seen_routes.contains(&route) {
            let stem: String = file_path
                .file_stem()
                .map(|s: &OsStr| slugify(&s.to_string_lossy()))
                .filter(|s: &String| !s.is_empty())
                .unwrap_or_else(|| FALLBACK_SLUG_PREFIX.to_string());
            let base_route: String = if route == ROUTE_ROOT {
                format!("/{stem}")
            } else {
                format!("{route}-{stem}")
            };
            route = base_route.clone();
            let mut suffix: usize = 2;
            while seen_routes.contains(&route) {
                route = format!("{base_route}-{suffix}");
                suffix += 1;
            }
        }
        let _: bool = seen_routes.insert(route.clone());
        let rel_normalized: String = rel
            .components()
            .map(|c: path::Component<'_>| c.as_os_str().to_string_lossy().into_owned())
            .collect::<Vec<String>>()
            .join("/");
        let stem_is_index: bool = rel
            .file_stem()
            .and_then(OsStr::to_str)
            .is_some_and(|s: &str| {
                s.eq_ignore_ascii_case(README_STEM) || s.eq_ignore_ascii_case(INDEX_STEM)
            });
        let mut parsed_page: DocPage =
            parse_markdown_page_with_frontmatter(&route, &section, frontmatter, body);
        parsed_page.set_source_meta(rel_normalized, stem_is_index);
        pages.push(parsed_page);
    }
    let mut dir_passwords: HashMap<String, String> = HashMap::new();
    for page in pages.iter() {
        if page.get_is_dir_index()
            && let Some(pw) = page.try_get_password().as_deref()
            && !pw.trim().is_empty()
        {
            let dir_key: String = page.directory_path();
            if !dir_key.is_empty() {
                let _: Option<String> = dir_passwords.insert(dir_key, pw.trim().to_string());
            }
        }
    }
    if !dir_passwords.is_empty() {
        for page in pages.iter_mut() {
            if page.try_get_password().is_some() {
                continue;
            }
            let dir_key: String = page.directory_path();
            let mut cur: &str = dir_key.as_str();
            while !cur.is_empty() {
                if let Some(pw) = dir_passwords.get(cur) {
                    page.set_inherited_password(pw.clone());
                    break;
                }
                match cur.rsplit_once('/') {
                    Some((parent, _)) => cur = parent,
                    None => break,
                }
            }
        }
    }
    if !root_sidebar_ranks.is_empty() || !dir_sidebar_ranks.is_empty() {
        for page in pages.iter_mut() {
            if page.get_route() == ROUTE_ROOT || page.get_order() != 100 {
                continue;
            }
            let computed_order: Option<i32> = {
                let trimmed: &str = page.get_route().trim_matches('/');
                let mut segs: Vec<&str> = trimmed.split('/').collect();
                let mut found: Option<i32> = None;
                if let Some(last) = segs.pop() {
                    let parent_key: String = segs.join("/");
                    if !parent_key.is_empty()
                        && let Some(&rank) = dir_sidebar_ranks.get(&(parent_key, last.to_string()))
                    {
                        found = Some(rank);
                    }
                }
                if found.is_none()
                    && let Some(first_seg) = trimmed.split('/').next()
                    && let Some(&rank) = root_sidebar_ranks.get(first_seg)
                {
                    let is_group_index: bool = !trimmed.contains('/');
                    found = Some(if is_group_index { rank } else { rank + 1 });
                }
                found
            };
            if let Some(new_order) = computed_order {
                page.order = new_order;
            }
        }
    }
    pages.sort_by(|a: &DocPage, b: &DocPage| {
        let a_root_rank: i32 = a
            .get_route()
            .trim_matches('/')
            .split('/')
            .next()
            .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
            .unwrap_or(i32::MAX);
        let b_root_rank: i32 = b
            .get_route()
            .trim_matches('/')
            .split('/')
            .next()
            .and_then(|seg: &str| root_sidebar_ranks.get(seg).copied())
            .unwrap_or(i32::MAX);
        if a.get_route() == ROUTE_ROOT && b.get_route() != ROUTE_ROOT {
            return Ordering::Less;
        }
        if b.get_route() == ROUTE_ROOT && a.get_route() != ROUTE_ROOT {
            return Ordering::Greater;
        }
        a_root_rank
            .cmp(&b_root_rank)
            .then_with(|| {
                section_sort_rank(a.get_section()).cmp(&section_sort_rank(b.get_section()))
            })
            .then_with(|| a.get_section().cmp(b.get_section()))
            .then_with(|| a.get_order().cmp(&b.get_order()))
            .then_with(|| a.get_route().cmp(b.get_route()))
    });
    let fallback_site_title: String = root_dir
        .file_name()
        .map(|s: &OsStr| s.to_string_lossy().into_owned())
        .filter(|raw: &String| {
            raw.len() > 2
                && !raw.eq_ignore_ascii_case(GENERIC_DOCS_DIR)
                && !raw.eq_ignore_ascii_case(GENERIC_SRC_DIR)
                && raw != "."
                && raw != ".."
        })
        .map(|raw: String| format_section_label(&raw))
        .unwrap_or_else(|| DOCS_SITE_TITLE.to_string());
    let site_title: String = title_override
        .map(str::to_string)
        .or(detected_title)
        .unwrap_or(fallback_site_title);
    let site_tagline: String = detected_tagline.unwrap_or_else(|| DOCS_SITE_TAGLINE.to_string());
    let mut site: DocSite = DocSite::new(site_title, site_tagline, pages);
    if let Some(cfg) = detected_site_cfg.as_ref() {
        site.apply_locale_metadata(cfg, None);
    } else {
        site.release_marker = EUV_DOCS_RELEASE_MARKER.to_string();
    }
    Ok(site)
}

/// Returns the canonical sidebar and pagination ordering rank for a section label.
///
/// # Arguments
///
/// - `&str` - Section display label.
///
/// # Returns
///
/// - `u8` - Priority rank (`0` General, `1` Guide, `2` all other sections alphabetically).
pub(crate) fn section_sort_rank(section: &str) -> u8 {
    if section.eq_ignore_ascii_case(DEFAULT_SECTION) {
        0
    } else if section.eq_ignore_ascii_case(GUIDE_SECTION) {
        1
    } else {
        2
    }
}

/// Extracts optional YAML frontmatter delimited by `---` lines.
///
/// # Arguments
///
/// - `&str` - Full raw Markdown document.
///
/// # Returns
///
/// - `(DocFrontmatter, &str)` - Parsed frontmatter and remaining Markdown body slice.
fn split_frontmatter(raw: &str) -> (DocFrontmatter, &str) {
    let trimmed: &str = raw.trim_start_matches('\u{feff}');
    let Some(rest) = trimmed.strip_prefix(FRONTMATTER_DELIMITER) else {
        return (DocFrontmatter::default(), trimmed);
    };
    let rest: &str = rest
        .strip_prefix("\r\n")
        .or_else(|| rest.strip_prefix('\n'))
        .unwrap_or(rest);
    let mut offset: usize = 0;
    for line in rest.split_inclusive('\n') {
        let clean: &str = line.trim_end_matches(['\r', '\n']);
        if clean.trim() == FRONTMATTER_DELIMITER {
            let yaml_slice: &str = &rest[..offset];
            let body_slice: &str = &rest[(offset + line.len())..];
            let parsed: DocFrontmatter = from_str::<DocFrontmatter>(yaml_slice)
                .unwrap_or_else(|_| parse_frontmatter_fallback(yaml_slice));
            return (parsed, body_slice);
        }
        offset += line.len();
    }
    (DocFrontmatter::default(), trimmed)
}

/// Fallback frontmatter extractor used when non-standard YAML types (e.g. scalar `category` or numeric `password`) prevent strict struct deserialization.
///
/// # Arguments
///
/// - `&str` - Raw YAML frontmatter slice.
///
/// # Returns
///
/// - `DocFrontmatter` - Best-effort parsed frontmatter retaining all recognized fields.
fn parse_frontmatter_fallback(yaml_slice: &str) -> DocFrontmatter {
    let mut fm: DocFrontmatter = DocFrontmatter::default();
    let Ok(Value::Object(map)) = from_str::<Value>(yaml_slice) else {
        return fm;
    };
    if let Some(s) = map.get("title").and_then(Value::as_str) {
        fm.title = Some(s.to_string());
    }
    if let Some(n) = map.get("order").and_then(Value::as_i64) {
        fm.order = Some(n as i32);
    }
    if let Some(s) = map.get("tagline").and_then(Value::as_str) {
        fm.tagline = Some(s.to_string());
    }
    if let Some(s) = map.get("description").and_then(Value::as_str) {
        fm.description = Some(s.to_string());
    }
    if let Some(s) = map.get("section").and_then(Value::as_str) {
        fm.section = Some(s.to_string());
    }
    if let Some(s) = map.get("updated").and_then(Value::as_str) {
        fm.updated = Some(s.to_string());
    }
    if let Some(s) = map.get("date").and_then(Value::as_str) {
        fm.date = Some(s.to_string());
    }
    if let Some(b) = map.get("index").and_then(Value::as_bool) {
        fm.index = Some(b);
    }
    if let Some(b) = map.get("expanded").and_then(Value::as_bool) {
        fm.expanded = Some(b);
    }
    if let Some(b) = map.get("home").and_then(Value::as_bool) {
        fm.home = b;
    }
    if let Some(b) = map.get("sidebar").and_then(Value::as_bool) {
        fm.sidebar = Some(b);
    }
    if let Some(pw) = map.get("password") {
        let pw_str: Option<String> = match pw {
            Value::String(s) => Some(s.clone()),
            Value::Number(n) => Some(n.to_string()),
            _ => None,
        };
        fm.password = pw_str;
    }
    if let Some(cat) = map.get("category") {
        match cat {
            Value::String(s) => fm.category.push(s.clone()),
            Value::Array(arr) => {
                for item in arr.iter() {
                    if let Some(s) = item.as_str() {
                        fm.category.push(s.to_string());
                    }
                }
            }
            _ => {}
        }
    }
    if let Some(Value::Object(dir_map)) = map.get("dir") {
        let mut dir_fm: DocDirFrontmatter = DocDirFrontmatter::default();
        if let Some(n) = dir_map.get("order").and_then(Value::as_i64) {
            dir_fm.order = Some(n as i32);
        }
        if let Some(s) = dir_map.get("text").and_then(Value::as_str) {
            dir_fm.text = Some(s.to_string());
        }
        if let Some(b) = dir_map.get("link").and_then(Value::as_bool) {
            dir_fm.link = Some(b);
        }
        if let Some(b) = dir_map.get("collapsible").and_then(Value::as_bool) {
            dir_fm.collapsible = Some(b);
        }
        fm.dir = Some(dir_fm);
    }
    fm
}

/// Converts a `pulldown_cmark::HeadingLevel` into its `u8` depth (`1..=6`).
///
/// # Arguments
///
/// - `HeadingLevel` - Heading level enum.
///
/// # Returns
///
/// - `u8` - Numeric heading depth.
pub(crate) fn heading_level_num(level: HeadingLevel) -> u8 {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

/// Appends a lowercase Unicode-safe URL anchor slug for `input` directly into `out`.
///
/// # Arguments
///
/// - `&mut String` - Destination slug buffer.
/// - `&str` - Heading text or path segment.
fn push_slugified(out: &mut String, input: &str) {
    let start_len: usize = out.len();
    let mut prev_dash: bool = false;
    for ch in input.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            prev_dash = false;
        } else if ch.is_alphanumeric() {
            for lower in ch.to_lowercase() {
                out.push(lower);
            }
            prev_dash = false;
        } else if !prev_dash && out.len() > start_len {
            out.push('-');
            prev_dash = true;
        }
    }
    while out.len() > start_len && out.ends_with('-') {
        let _: Option<char> = out.pop();
    }
}

/// Produces a lowercase Unicode-safe URL anchor slug from heading text or path segments.
///
/// # Arguments
///
/// - `&str` - Heading text or path segment.
///
/// # Returns
///
/// - `String` - Hyphenated URL slug.
pub(crate) fn slugify(input: &str) -> String {
    let mut out: String = String::with_capacity(input.len());
    push_slugified(&mut out, input);
    out
}

/// Ensures every heading anchor slug within a single page is unique (`slug`, `slug-2`, ...).
///
/// # Arguments
///
/// - `String` - Candidate slug string.
/// - `&mut BTreeMap<String, usize>` - Per-page occurrence map.
///
/// # Returns
///
/// - `String` - Unique anchor slug.
pub(crate) fn deduplicate_slug(raw_slug: String, seen: &mut BTreeMap<String, usize>) -> String {
    let base: String = if raw_slug.is_empty() {
        FALLBACK_SLUG_PREFIX.to_string()
    } else {
        raw_slug
    };
    if let Some(count) = seen.get_mut(&base) {
        *count += 1;
        return format!("{base}-{}", *count);
    }
    let _: Option<usize> = seen.insert(base.clone(), 1);
    base
}

/// Recursively collects `.md` file paths beneath `dir`, skipping build artifacts, hidden folders, and `exclude_dir`.
///
/// # Arguments
///
/// - `&Path` - Directory to walk.
/// - `Option<&Path>` - Optional canonical output directory to skip.
/// - `&mut Vec<PathBuf>` - Output path accumulator.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_markdown_files(
    dir: &Path,
    exclude_dir: Option<&Path>,
    out: &mut Vec<PathBuf>,
) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry_val: DirEntry = entry?;
        let path: PathBuf = entry_val.path();
        let is_dir: bool = match entry_val.file_type() {
            Ok(ft) if ft.is_dir() => true,
            Ok(ft) if ft.is_file() => false,
            _ => path.is_dir(),
        };
        if is_dir {
            let file_name: OsString = entry_val.file_name();
            let name: Cow<'_, str> = file_name.to_string_lossy();
            if should_skip_dir(&name) {
                continue;
            }
            if let Some(excluded) = exclude_dir {
                let candidate: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
                if candidate == excluded || candidate.starts_with(excluded) {
                    continue;
                }
            }
            collect_markdown_files(&path, exclude_dir, out)?;
        } else if path
            .extension()
            .and_then(|s: &OsStr| s.to_str())
            .is_some_and(|ext: &str| ext.eq_ignore_ascii_case(MARKDOWN_EXT))
        {
            out.push(path);
        }
    }
    Ok(())
}

/// Returns `true` when directory `name` is an ignored build, cache, or hidden metadata directory.
///
/// # Arguments
///
/// - `&str` - Directory base name.
///
/// # Returns
///
/// - `bool` - Whether traversal should skip this directory.
pub(crate) fn should_skip_dir(name: &str) -> bool {
    name.starts_with('.')
        || IGNORED_SCAN_DIRS
            .iter()
            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
}

/// Appends a single `/` plus slugified (or ASCII-lowercased fallback) route segment into `out`.
///
/// # Arguments
///
/// - `&mut String` - Destination route buffer.
/// - `&str` - Raw directory name or file stem segment.
fn push_route_segment(out: &mut String, seg: &str) {
    out.push('/');
    let start_len: usize = out.len();
    push_slugified(out, seg);
    if out.len() == start_len {
        for ch in seg.chars() {
            out.push(ch.to_ascii_lowercase());
        }
    }
}

/// Derives canonical route and formatted section label from a relative Markdown path.
///
/// # Arguments
///
/// - `&Path` - Relative path inside the docs root directory.
///
/// # Returns
///
/// - `(String, String)` - Canonical route path and section label.
fn route_and_section_from_rel_path(rel: &Path) -> (String, String) {
    let mut comps: Peekable<Components<'_>> = rel.components().peekable();
    let Some(first_comp) = comps.next() else {
        return (ROUTE_ROOT.to_string(), DEFAULT_SECTION.to_string());
    };
    let mut route: String = String::with_capacity(rel.as_os_str().len() + 1);
    let section: String = if comps.peek().is_some() {
        let first_cow: Cow<'_, str> = first_comp.as_os_str().to_string_lossy();
        let sec: String = format_section_label(&first_cow);
        push_route_segment(&mut route, &first_cow);
        while let Some(comp) = comps.next() {
            if comps.peek().is_some() {
                let seg_cow: Cow<'_, str> = comp.as_os_str().to_string_lossy();
                push_route_segment(&mut route, &seg_cow);
            }
        }
        sec
    } else {
        DEFAULT_SECTION.to_string()
    };
    let stem_cow: Cow<'_, str> = rel
        .file_stem()
        .map(OsStr::to_string_lossy)
        .unwrap_or(Cow::Borrowed(""));
    if !stem_cow.eq_ignore_ascii_case(README_STEM) && !stem_cow.eq_ignore_ascii_case(INDEX_STEM) {
        push_route_segment(&mut route, &stem_cow);
    }
    if route.is_empty() {
        route.push_str(ROUTE_ROOT);
    }
    (route, section)
}

/// Formats a directory or filename slug into a readable Title-Case label.
///
/// # Arguments
///
/// - `&str` - Raw path segment or filename stem.
///
/// # Returns
///
/// - `String` - Formatted display label.
fn format_section_label(raw: &str) -> String {
    let mut out: String = String::with_capacity(raw.len());
    for part in raw.split(['-', '_']) {
        let trimmed: &str = part.trim();
        if trimmed.is_empty() {
            continue;
        }
        let mut chars: Chars<'_> = trimmed.chars();
        if let Some(first) = chars.next() {
            if !out.is_empty() {
                out.push(' ');
            }
            for up in first.to_uppercase() {
                out.push(up);
            }
            out.push_str(chars.as_str());
        }
    }
    if out.is_empty() {
        out.push_str(DEFAULT_SECTION);
    }
    out
}

/// Derives a human-readable fallback page title from a canonical route string.
///
/// # Arguments
///
/// - `&str` - Canonical route path.
///
/// # Returns
///
/// - `String` - Display title fallback.
fn title_from_route(route: &str) -> String {
    let trimmed: &str = route.trim_matches('/');
    if trimmed.is_empty() {
        return DEFAULT_DOC_TITLE.to_string();
    }
    trimmed
        .rsplit('/')
        .next()
        .map(format_section_label)
        .unwrap_or_else(|| DEFAULT_DOC_TITLE.to_string())
}