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//! Since Wave 2c every page compiles to a FULL HTML document carrying
8//! the estate-seo floor's head artifacts (title, description, canonical,
9//! Open Graph, JSON-LD); a `site.toml` with `base_url` additionally
10//! emits `llms.txt`, `sitemap.xml`, and `robots.txt` (with the
11//! AI-crawler policy as a recorded decision). Per-page inputs come from
12//! `---` front-matter (`title`, `description`, `slug`, `date`).
13//!
14//! Design note (plan ledger W2-3): the server lives in docs-compiler,
15//! not docs-core - docs-core is L2 with no web framework, and serving
16//! is a CLI concern. The server never dies on a bad page: compile
17//! errors are collected per page, printed, and the site keeps serving
18//! the last good HTML (fail-loud, not fail-dead).
19
20use crate::compress::{self, Tools};
21use crate::seo::{self, SeoPage, SiteConfig};
22use crate::{compile, BuildContext};
23use std::io;
24use std::path::{Path, PathBuf};
25
26/// What one site compilation pass produced.
27#[derive(Debug, Default, Clone)]
28pub struct SiteReport {
29    /// Pages written (source paths).
30    pub built: Vec<PathBuf>,
31    /// Pages that failed: (source path, error text).
32    pub errors: Vec<(PathBuf, String)>,
33    /// Content-quality warnings (title > 60 chars, description > 155,
34    /// missing description): the estate-seo floor's guidance, not errors.
35    pub warnings: Vec<String>,
36    /// The SEO view of every built page (route, title, description,
37    /// date) - also the source for llms.txt and sitemap.xml.
38    pub pages: Vec<SeoPage>,
39    /// Whether a `site.toml` provided site-wide settings.
40    pub configured: bool,
41    /// Artifacts written (pages, llms.txt, sitemap, robots) - the
42    /// precompression pass runs over exactly these.
43    pub artifacts: Vec<PathBuf>,
44    /// Compressed sidecars produced (`.gz`/`.br`/`.zst`/`.dcz` files).
45    pub compressed: usize,
46    /// Whether a shared zstd dictionary was trained and emitted
47    /// (`site.dict`, served with `Use-As-Dictionary`).
48    pub dictionary: bool,
49}
50
51impl SiteReport {
52    /// Whether every page compiled.
53    pub fn is_clean(&self) -> bool {
54        self.errors.is_empty()
55    }
56}
57
58/// Compile every `.md` under `src` (recursive, hidden dirs skipped) into
59/// the mirrored `.html` layout under `out`, as full documents with the
60/// SEO head. Front-matter (`title`, `description`, `slug`, `date`)
61/// overrides the title/description/route/date fallbacks. Directive roots
62/// are each page's own directory, matching the single-file CLI's
63/// default. One bad page never blocks the others: its error lands in
64/// the report. A `site.toml` with `base_url` additionally emits
65/// `llms.txt`, `sitemap.xml`, and `robots.txt` into `out`.
66///
67/// # Errors
68/// I/O failures on the tree walk or output creation.
69pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
70    let config = SiteConfig::load(src);
71    let mut report = SiteReport {
72        configured: config.is_some(),
73        ..SiteReport::default()
74    };
75    let mut stack = vec![src.to_path_buf()];
76    while let Some(dir) = stack.pop() {
77        for entry in std::fs::read_dir(&dir)? {
78            let entry = entry?;
79            let path = entry.path();
80            let name = entry.file_name();
81            let name = name.to_string_lossy();
82            if path.is_dir() {
83                if !name.starts_with('.') {
84                    stack.push(path);
85                }
86            } else if name.ends_with(".md") {
87                build_one_page(src, out, &path, config.as_ref(), &mut report);
88            }
89        }
90    }
91    if let Some(config) = &config {
92        let page_refs: &[SeoPage] = &report.pages;
93        for (name, content) in [
94            ("llms.txt", seo::llms_txt(config, page_refs)),
95            ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
96            ("robots.txt", seo::robots_txt(config)),
97        ] {
98            let path = out.join(name);
99            std::fs::write(&path, content)?;
100            report.artifacts.push(path);
101        }
102    }
103    precompress(out, &mut report);
104    Ok(report)
105}
106
107/// The precompression pass (Wave 2c.5): sidecars for every artifact,
108/// plus the shared zstd dictionary and `.dcz` page encodings when the
109/// site has enough pages to train on. Absent tools degrade gracefully
110/// (warning, not failure) - the estate's spawn-don't-link doctrine.
111fn precompress(out: &Path, report: &mut SiteReport) {
112    let tools = Tools::detect();
113    if !tools.any() {
114        report
115            .warnings
116            .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
117        return;
118    }
119    let mut compressed = 0usize;
120    let artifacts = report.artifacts.clone();
121    for artifact in &artifacts {
122        match compress::sidecars(&tools, artifact) {
123            Ok(encodings) => compressed += encodings.len(),
124            Err(e) => report
125                .warnings
126                .push(format!("{}: compression failed: {e}", artifact.display())),
127        }
128    }
129    let dict_path = out.join("site.dict");
130    match compress::train_dictionary(&tools, &artifacts, &dict_path) {
131        Ok(true) => {
132            report.dictionary = true;
133            compressed += 1; // the dictionary itself is an artifact
134            for artifact in &artifacts {
135                if matches!(
136                    artifact.extension().and_then(|e| e.to_str()),
137                    Some("html") | Some("txt") | Some("xml")
138                ) && compress::dcz_sidecar(&tools, &dict_path, artifact).unwrap_or(false)
139                {
140                    compressed += 1;
141                }
142            }
143        }
144        Ok(false) => {
145            report.warnings.push(format!(
146                "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
147                artifacts.len()
148            ));
149        }
150        Err(e) => report
151            .warnings
152            .push(format!("dictionary training failed: {e}")),
153    }
154    report.compressed = compressed;
155}
156
157/// Build one page: front-matter, compile, head, write, report.
158fn build_one_page(
159    src: &Path,
160    out: &Path,
161    path: &Path,
162    config: Option<&SiteConfig>,
163    report: &mut SiteReport,
164) {
165    let rel = match path.strip_prefix(src) {
166        Ok(r) => r.to_path_buf(),
167        Err(_) => path.to_path_buf(),
168    };
169    let source = match std::fs::read_to_string(path) {
170        Ok(s) => s,
171        Err(e) => {
172            report.errors.push((path.to_path_buf(), e.to_string()));
173            return;
174        }
175    };
176    let (meta, body_markdown) = seo::split_front_matter(&source);
177    let root = path
178        .parent()
179        .filter(|p| !p.as_os_str().is_empty())
180        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
181    let body = match compile(&body_markdown, &BuildContext::new(root)) {
182        Ok(html) => html,
183        Err(e) => {
184            report.errors.push((path.to_path_buf(), e.to_string()));
185            return;
186        }
187    };
188
189    let stem = meta.slug.clone().unwrap_or_else(|| {
190        rel.file_stem()
191            .unwrap_or_default()
192            .to_string_lossy()
193            .into_owned()
194    });
195    let dir = rel.parent().unwrap_or(Path::new(""));
196    let route = if dir.as_os_str().is_empty() {
197        format!("{stem}.html")
198    } else {
199        format!("{}/{}.html", dir.display(), stem)
200    };
201    let title = meta
202        .title
203        .clone()
204        .or_else(|| seo::first_h1(&body))
205        .unwrap_or_else(|| {
206            rel.file_stem()
207                .map(|s| s.to_string_lossy().into_owned())
208                .unwrap_or_else(|| "Untitled".to_string())
209        });
210    let description = meta
211        .description
212        .clone()
213        .or_else(|| seo::first_paragraph(&body))
214        .unwrap_or_default();
215
216    if title.chars().count() > 60 {
217        report.warnings.push(format!(
218            "{route}: title is {} chars (guidance: <= 60)",
219            title.chars().count()
220        ));
221    }
222    if description.is_empty() {
223        report.warnings.push(format!(
224            "{route}: no description (front-matter or first paragraph)"
225        ));
226    } else if description.chars().count() > 155 {
227        report.warnings.push(format!(
228            "{route}: description is {} chars (guidance: <= 155)",
229            description.chars().count()
230        ));
231    }
232
233    let document = seo::document(&body, &meta, &title, &description, &route, config);
234    let target = out.join(&route);
235    if let Some(parent) = target.parent() {
236        if let Err(e) = std::fs::create_dir_all(parent) {
237            report.errors.push((path.to_path_buf(), e.to_string()));
238            return;
239        }
240    }
241    if let Err(e) = std::fs::write(&target, document) {
242        report.errors.push((path.to_path_buf(), e.to_string()));
243        return;
244    }
245    report.built.push(path.to_path_buf());
246    report.artifacts.push(target);
247    report.pages.push(SeoPage {
248        route,
249        title,
250        description,
251        date: meta.date,
252    });
253}
254
255/// Map a request path to a file under `out`: empty → `index.html`;
256/// directories resolve to their `index.html`; an extensionless path
257/// falls back to `<path>.html`. Percent escapes are decoded; anything
258/// that escapes `out` (or games the encoding) resolves to nothing.
259#[must_use]
260pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
261    let path = url_path.split(['?', '#']).next().unwrap_or("");
262    let decoded = percent_decode(path)?;
263    let cleaned: Vec<&str> = decoded
264        .split('/')
265        .filter(|seg| !seg.is_empty() && *seg != ".")
266        .collect();
267    if cleaned.contains(&"..") {
268        return None;
269    }
270    let mut file = out.to_path_buf();
271    for seg in &cleaned {
272        file.push(seg);
273    }
274    if cleaned.is_empty() {
275        file.push("index.html");
276    }
277    if file.is_dir() {
278        file.push("index.html");
279    }
280    if !file.exists() && file.extension().is_none() {
281        let with_html = file.with_extension("html");
282        if with_html.is_file() {
283            return Some(with_html);
284        }
285        return None;
286    }
287    if file.is_file() {
288        Some(file)
289    } else {
290        None
291    }
292}
293
294/// Minimal percent-decoding for request paths; malformed escapes
295/// (`%` not followed by two hex digits) resolve to nothing.
296#[must_use]
297fn percent_decode(path: &str) -> Option<String> {
298    let mut out = Vec::with_capacity(path.len());
299    let mut bytes = path.bytes();
300    while let Some(b) = bytes.next() {
301        let value = if b == b'%' {
302            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
303            let hi = decode(bytes.next()?)?;
304            let lo = decode(bytes.next()?)?;
305            hi.checked_mul(16)?.checked_add(lo)?
306        } else {
307            b
308        };
309        out.push(value);
310    }
311    String::from_utf8(out).ok()
312}
313
314/// MIME type by extension; unknown extensions are plain text (the
315/// browser shows them instead of downloading).
316#[must_use]
317pub fn mime_for(path: &Path) -> &'static str {
318    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
319        "html" => "text/html; charset=utf-8",
320        "css" => "text/css; charset=utf-8",
321        "js" | "mjs" => "text/javascript; charset=utf-8",
322        "json" => "application/json",
323        "wasm" => "application/wasm",
324        "svg" => "image/svg+xml",
325        "png" => "image/png",
326        "jpg" | "jpeg" => "image/jpeg",
327        "gif" => "image/gif",
328        "ico" => "image/x-icon",
329        "md" => "text/markdown; charset=utf-8",
330        "xml" => "application/xml",
331        "txt" => "text/plain; charset=utf-8",
332        "woff2" => "font/woff2",
333        _ => "text/plain; charset=utf-8",
334    }
335}