Skip to main content

docs_compiler/
serve.rs

1//! The dev server's reusable half (Wave 2): compiling a directory of
2//! markdown into a directory of HTML, URL routing with a traversal
3//! guard, and MIME mapping. The socket loop and the file watcher are
4//! thin wrappers in the binary; everything with logic lives here and is
5//! unit-tested.
6//!
7//! Design note (plan ledger W2-3): the server lives in docs-compiler,
8//! not docs-core - docs-core is L2 with no web framework, and serving
9//! is a CLI concern. The server never dies on a bad page: compile
10//! errors are collected per page, printed, and the site keeps serving
11//! the last good HTML (fail-loud, not fail-dead).
12
13use crate::{compile, BuildContext};
14use std::io;
15use std::path::{Path, PathBuf};
16
17/// What one site compilation pass produced.
18#[derive(Debug, Default, Clone)]
19pub struct SiteReport {
20    /// Pages written (source paths).
21    pub built: Vec<PathBuf>,
22    /// Pages that failed: (source path, error text).
23    pub errors: Vec<(PathBuf, String)>,
24}
25
26impl SiteReport {
27    /// Whether every page compiled.
28    #[must_use]
29    pub fn is_clean(&self) -> bool {
30        self.errors.is_empty()
31    }
32}
33
34/// Compile every `.md` under `src` (recursive, hidden dirs skipped) into
35/// the mirrored `.html` layout under `out`. Directive roots are each
36/// page's own directory, matching the single-file CLI's default. One bad
37/// page never blocks the others: its error lands in the report.
38///
39/// # Errors
40/// I/O failures on the tree walk or output creation.
41pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
42    let mut report = SiteReport::default();
43    let mut stack = vec![src.to_path_buf()];
44    while let Some(dir) = stack.pop() {
45        for entry in std::fs::read_dir(&dir)? {
46            let entry = entry?;
47            let path = entry.path();
48            let name = entry.file_name();
49            let name = name.to_string_lossy();
50            if path.is_dir() {
51                if !name.starts_with('.') {
52                    stack.push(path);
53                }
54            } else if name.ends_with(".md") {
55                let rel = path.strip_prefix(src).unwrap_or(&path).to_path_buf();
56                let target_rel = rel.with_extension("html");
57                let target = out.join(&target_rel);
58                if let Some(parent) = target.parent() {
59                    std::fs::create_dir_all(parent)?;
60                }
61                let source = match std::fs::read_to_string(&path) {
62                    Ok(s) => s,
63                    Err(e) => {
64                        report.errors.push((path, e.to_string()));
65                        continue;
66                    }
67                };
68                let root = path
69                    .parent()
70                    .filter(|p| !p.as_os_str().is_empty())
71                    .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
72                match compile(&source, &BuildContext::new(root)) {
73                    Ok(html) => {
74                        std::fs::write(&target, html)?;
75                        report.built.push(path);
76                    }
77                    Err(e) => report.errors.push((path, e.to_string())),
78                }
79            }
80        }
81    }
82    Ok(report)
83}
84
85/// Map a request path to a file under `out`: empty → `index.html`;
86/// directories resolve to their `index.html`; an extensionless path
87/// falls back to `<path>.html`. Percent escapes are decoded; anything
88/// that escapes `out` (or games the encoding) resolves to nothing.
89#[must_use]
90pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
91    let path = url_path.split(['?', '#']).next().unwrap_or("");
92    let decoded = percent_decode(path)?;
93    let cleaned: Vec<&str> = decoded
94        .split('/')
95        .filter(|seg| !seg.is_empty() && *seg != ".")
96        .collect();
97    if cleaned.contains(&"..") {
98        return None;
99    }
100    let mut file = out.to_path_buf();
101    for seg in &cleaned {
102        file.push(seg);
103    }
104    if cleaned.is_empty() {
105        file.push("index.html");
106    }
107    if file.is_dir() {
108        file.push("index.html");
109    }
110    if !file.exists() && file.extension().is_none() {
111        let with_html = file.with_extension("html");
112        if with_html.is_file() {
113            return Some(with_html);
114        }
115        return None;
116    }
117    if file.is_file() {
118        Some(file)
119    } else {
120        None
121    }
122}
123
124/// Minimal percent-decoding for request paths; malformed escapes
125/// (`%` not followed by two hex digits) resolve to nothing.
126#[must_use]
127fn percent_decode(path: &str) -> Option<String> {
128    let mut out = Vec::with_capacity(path.len());
129    let mut bytes = path.bytes();
130    while let Some(b) = bytes.next() {
131        let value = if b == b'%' {
132            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
133            let hi = decode(bytes.next()?)?;
134            let lo = decode(bytes.next()?)?;
135            hi.checked_mul(16)?.checked_add(lo)?
136        } else {
137            b
138        };
139        out.push(value);
140    }
141    String::from_utf8(out).ok()
142}
143
144/// MIME type by extension; unknown extensions are plain text (the
145/// browser shows them instead of downloading).
146#[must_use]
147pub fn mime_for(path: &Path) -> &'static str {
148    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
149        "html" => "text/html; charset=utf-8",
150        "css" => "text/css; charset=utf-8",
151        "js" | "mjs" => "text/javascript; charset=utf-8",
152        "json" => "application/json",
153        "wasm" => "application/wasm",
154        "svg" => "image/svg+xml",
155        "png" => "image/png",
156        "jpg" | "jpeg" => "image/jpeg",
157        "gif" => "image/gif",
158        "ico" => "image/x-icon",
159        "md" => "text/markdown; charset=utf-8",
160        "xml" => "application/xml",
161        "woff2" => "font/woff2",
162        _ => "text/plain; charset=utf-8",
163    }
164}