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 2d the site builder owns the whole tree: pages become
8//! full documents wrapped in the site chrome (header, sidebar nav tree
9//! built from the directory structure, per-page TOC, prev/next pager,
10//! theme toggle), `src/assets/**` is mirrored to `out/_assets/**`, and
11//! a search corpus (`search.json`, for the solid-fx doc-search island)
12//! plus a `docs-search` binary index (`search.bin`) are emitted.
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::chrome::{self, Chrome, NavGroup};
21use crate::compress::{self};
22use crate::seo::{self, SeoPage, SiteConfig};
23use crate::{compile, BuildContext};
24use std::io;
25use std::path::{Path, PathBuf};
26
27/// What one site compilation pass produced.
28#[derive(Debug, Default, Clone)]
29pub struct SiteReport {
30    /// Pages written (source paths).
31    pub built: Vec<PathBuf>,
32    /// Pages that failed: (source path, error text).
33    pub errors: Vec<(PathBuf, String)>,
34    /// Content-quality warnings (title > 60 chars, description > 155,
35    /// missing description): the estate-seo floor's guidance, not errors.
36    pub warnings: Vec<String>,
37    /// The SEO view of every built page (route, title, description,
38    /// date) - also the source for llms.txt and sitemap.xml.
39    pub pages: Vec<SeoPage>,
40    /// Whether a `site.toml` provided site-wide settings.
41    pub configured: bool,
42    /// Artifacts written (pages, search corpus/index, llms.txt,
43    /// sitemap, robots) - the precompression pass runs over these.
44    pub artifacts: Vec<PathBuf>,
45    /// Compressed sidecars produced (`.gz`/`.br`/`.zst`/`.dcz` files).
46    pub compressed: usize,
47    /// Whether a shared zstd dictionary was trained and emitted
48    /// (`site.dict`, served with `Use-As-Dictionary`).
49    pub dictionary: bool,
50    /// Asset files copied from `src/assets/**`.
51    pub assets_copied: usize,
52}
53
54impl SiteReport {
55    /// Whether every page compiled.
56    pub fn is_clean(&self) -> bool {
57        self.errors.is_empty()
58    }
59}
60
61/// One rendered page, ready for chrome wrapping and writing.
62struct PageBuild {
63    source: PathBuf,
64    route: String,
65    title: String,
66    description: String,
67    date: Option<String>,
68    meta: seo::PageMeta,
69    body: String,
70    /// Plain text of the body - the search corpus input.
71    text: String,
72}
73
74/// Compile every `.md` under `src` (recursive, hidden dirs skipped) into
75/// the mirrored `.html` layout under `out`, wrapped in the site chrome.
76/// Front-matter (`title`, `description`, `slug`, `date`) overrides the
77/// title/description/route/date fallbacks. Directive roots are each
78/// page's own directory, matching the single-file CLI's default.
79///
80/// A `site.toml` with `base_url` additionally emits `llms.txt`,
81/// `sitemap.xml`, and `robots.txt`; `src/assets/**` is mirrored to
82/// `out/_assets/**`; and `search.json` + `search.bin` (a docs-search
83/// index) are emitted for client-side search.
84///
85/// # Errors
86/// I/O failures on the tree walk or output creation.
87pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
88    let config = SiteConfig::load(src);
89    let tools = compress::Tools::detect();
90    let mut report = SiteReport {
91        configured: config.is_some(),
92        ..SiteReport::default()
93    };
94
95    // Pass 1: render every page body and collect its metadata.
96    let mut pages: Vec<PageBuild> = Vec::new();
97    let mut stack = vec![src.to_path_buf()];
98    while let Some(dir) = stack.pop() {
99        for entry in std::fs::read_dir(&dir)? {
100            let entry = entry?;
101            let path = entry.path();
102            let name = entry.file_name();
103            let name = name.to_string_lossy();
104            if path.is_dir() {
105                if !name.starts_with('.') {
106                    stack.push(path);
107                }
108            } else if name.ends_with(".md") {
109                build_page(src, &path, &mut report, &mut pages);
110            }
111        }
112    }
113    pages.sort_by(|a, b| a.route.cmp(&b.route));
114
115    // Site assets: src/assets/** mirrors to out/_assets/** (the island
116    // base URL space), and the chrome stylesheet is emitted first so
117    // every wrapped page can link it.
118    let chrome_css = out.join("_assets").join("layout.css");
119    std::fs::create_dir_all(
120        chrome_css
121            .parent()
122            .map_or_else(|| Path::new("."), Path::new),
123    )?;
124    std::fs::write(&chrome_css, chrome::LAYOUT_CSS)?;
125    report.artifacts.push(chrome_css);
126    let assets_src = src.join("assets");
127    if assets_src.is_dir() {
128        report.assets_copied = copy_tree(&assets_src, &out.join("_assets"))?;
129    }
130
131    // Pass 2: chrome-wrap and write every page, in route order. The
132    // search corpus grows alongside (title/url/description/body JSON for
133    // the doc-search island, plus the docs-search binary index).
134    let mut corpus = String::from("[\n");
135    let mut index = docs_search::IndexBuilder::new();
136    for page in &pages {
137        let chrome = Chrome {
138            nav: nav_groups(&pages, &page.route),
139            active_route: page.route.clone(),
140            toc: chrome::extract_toc(&page.body),
141            prev: prev_of(&pages, &page.route),
142            next: next_of(&pages, &page.route),
143            search_island: config.as_ref().and_then(|c| c.search_island.clone()),
144            search_index: config.as_ref().map(|_| "/search.json".into()),
145        };
146        let doc = seo::document(
147            &page.body,
148            &page.meta,
149            &page.title,
150            &page.description,
151            &page.route,
152            config.as_ref(),
153        );
154        let site_title = config
155            .as_ref()
156            .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone());
157        let with_chrome = chrome::page(&doc, &site_title, &chrome);
158        let target = out.join(&page.route);
159        if let Some(parent) = target.parent() {
160            std::fs::create_dir_all(parent)?;
161        }
162        std::fs::write(&target, with_chrome)?;
163        report.built.push(page.source.clone());
164        report.artifacts.push(target);
165        report.pages.push(SeoPage {
166            route: page.route.clone(),
167            title: page.title.clone(),
168            description: page.description.clone(),
169            date: page.date.clone(),
170        });
171
172        corpus.push_str(&format!(
173            "{{\"title\":{},\"url\":{},\"description\":{},\"body\":{}}},\n",
174            serde_json::to_string(&page.title).unwrap_or_else(|_| "\"\"".into()),
175            serde_json::to_string(&format!("/{}", page.route)).unwrap_or_else(|_| "\"\"".into()),
176            serde_json::to_string(&page.description).unwrap_or_else(|_| "\"\"".into()),
177            serde_json::to_string(&page.text).unwrap_or_else(|_| "\"\"".into()),
178        ));
179        let _ = index.add_doc(&format!(
180            "{} {} {}",
181            page.title, page.description, page.text
182        ));
183    }
184
185    // SEO artifacts.
186    if let Some(config) = &config {
187        let page_refs: &[SeoPage] = &report.pages;
188        for (name, content) in [
189            ("llms.txt", seo::llms_txt(config, page_refs)),
190            ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
191            ("robots.txt", seo::robots_txt(config)),
192        ] {
193            let path = out.join(name);
194            std::fs::write(&path, content)?;
195            report.artifacts.push(path);
196        }
197    }
198
199    // Search artifacts: the JSON corpus for the doc-search island and a
200    // docs-search binary index for the future in-browser reader.
201    if !report.pages.is_empty() {
202        corpus.push_str("]\n");
203        let corpus_path = out.join("search.json");
204        std::fs::write(&corpus_path, corpus)?;
205        report.artifacts.push(corpus_path);
206        let index_path = out.join("search.bin");
207        match index.build() {
208            Ok(bytes) => {
209                std::fs::write(&index_path, bytes)?;
210                report.artifacts.push(index_path);
211            }
212            Err(e) => report
213                .warnings
214                .push(format!("search index build failed: {e}")),
215        }
216    }
217
218    precompress(out, &tools, &mut report);
219    Ok(report)
220}
221
222/// Build one page's metadata and body into the pending list. All
223/// failures land in the report - one bad page never blocks the site.
224fn build_page(src: &Path, path: &Path, report: &mut SiteReport, pages: &mut Vec<PageBuild>) {
225    let rel = match path.strip_prefix(src) {
226        Ok(r) => r.to_path_buf(),
227        Err(_) => path.to_path_buf(),
228    };
229    let source = match std::fs::read_to_string(path) {
230        Ok(s) => s,
231        Err(e) => {
232            report.errors.push((path.to_path_buf(), e.to_string()));
233            return;
234        }
235    };
236    let (meta, body_markdown) = seo::split_front_matter(&source);
237    let root = path
238        .parent()
239        .filter(|p| !p.as_os_str().is_empty())
240        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
241    let body = match compile(&body_markdown, &BuildContext::new(root)) {
242        Ok(html) => html,
243        Err(e) => {
244            report.errors.push((path.to_path_buf(), e.to_string()));
245            return;
246        }
247    };
248
249    let stem = meta.slug.clone().unwrap_or_else(|| {
250        rel.file_stem()
251            .unwrap_or_default()
252            .to_string_lossy()
253            .into_owned()
254    });
255    let dir = rel.parent().unwrap_or(Path::new(""));
256    let route = if dir.as_os_str().is_empty() {
257        format!("{stem}.html")
258    } else {
259        format!("{}/{}.html", dir.display(), stem)
260    };
261    let title = meta
262        .title
263        .clone()
264        .or_else(|| seo::first_h1(&body))
265        .unwrap_or_else(|| {
266            rel.file_stem()
267                .map(|s| s.to_string_lossy().into_owned())
268                .unwrap_or_else(|| "Untitled".to_string())
269        });
270    let description = meta
271        .description
272        .clone()
273        .or_else(|| seo::first_paragraph(&body))
274        .unwrap_or_default();
275
276    if title.chars().count() > 60 {
277        report.warnings.push(format!(
278            "{route}: title is {} chars (guidance: <= 60)",
279            title.chars().count()
280        ));
281    }
282    if description.is_empty() {
283        report.warnings.push(format!(
284            "{route}: no description (front-matter or first paragraph)"
285        ));
286    } else if description.chars().count() > 155 {
287        report.warnings.push(format!(
288            "{route}: description is {} chars (guidance: <= 155)",
289            description.chars().count()
290        ));
291    }
292
293    pages.push(PageBuild {
294        source: path.to_path_buf(),
295        route,
296        title,
297        description,
298        date: meta.date.clone(),
299        meta,
300        text: crate::seo::plain_text(&body),
301        body,
302    });
303}
304
305/// Sidebar nav groups: group pages by their first route segment, label
306/// groups by the second segment when present ("content/TextAnimations"
307/// -> "TextAnimations"). The homepage stays out - the header brand
308/// links it.
309fn nav_groups(pages: &[PageBuild], active_route: &str) -> Vec<NavGroup> {
310    let mut order: Vec<String> = Vec::new();
311    let mut groups: std::collections::HashMap<String, Vec<(String, String)>> =
312        std::collections::HashMap::new();
313    for page in pages {
314        if page.route == "index.html" {
315            continue;
316        }
317        // Group key: the directory the page lives in. Depth-2 routes
318        // ("guides/one.html") group under their top segment; deeper
319        // routes group under the first two ("extras/osint"), so
320        // categories stay separate.
321        let segs: Vec<&str> = page.route.split('/').collect();
322        let key = match (segs.first(), segs.get(1)) {
323            (Some(top), Some(second)) if second.contains('.') => (*top).to_string(),
324            (Some(top), Some(second)) => format!(
325                "{top}/{stem}",
326                stem = second.split('.').next().unwrap_or(second)
327            ),
328            _ => "pages".to_string(),
329        };
330        if !groups.contains_key(&key) {
331            order.push(key.clone());
332        }
333        groups
334            .entry(key)
335            .or_default()
336            .push((page.route.clone(), page.title.clone()));
337    }
338    let mut out = Vec::new();
339    for key in order {
340        let items = groups.remove(&key).unwrap_or_default();
341        let label = key.rsplit('/').next().unwrap_or(&key).to_string();
342        let active = active_route.starts_with(&format!("{key}/"));
343        out.push(NavGroup {
344            label: display_label(&key, &label),
345            active,
346            items,
347        });
348    }
349    out
350}
351
352/// Display label: capitalize the group's last segment for the sidebar.
353fn display_label(key: &str, label: &str) -> String {
354    let mut chars = label.chars();
355    match chars.next() {
356        Some(first) => {
357            let mut out = String::from(key);
358            out.clear();
359            out.push(first.to_ascii_uppercase());
360            out.push_str(chars.as_str());
361            out
362        }
363        None => key.to_string(),
364    }
365}
366
367fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
368    let pos = pages.iter().position(|p| p.route == route)?;
369    let previous = pos.checked_sub(1)?;
370    pages
371        .get(previous)
372        .map(|p| (p.route.clone(), p.title.clone()))
373}
374
375fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
376    let pos = pages.iter().position(|p| p.route == route)?;
377    pages
378        .get(pos + 1)
379        .map(|p| (p.route.clone(), p.title.clone()))
380}
381
382/// Mirror-copy a directory tree; returns the file count.
383fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
384    let mut count = 0usize;
385    let mut stack = vec![from.to_path_buf()];
386    while let Some(dir) = stack.pop() {
387        for entry in std::fs::read_dir(&dir)? {
388            let entry = entry?;
389            let path = entry.path();
390            if path.is_dir() {
391                stack.push(path);
392            } else {
393                let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
394                let dest = to.join(rel);
395                if let Some(parent) = dest.parent() {
396                    std::fs::create_dir_all(parent)?;
397                }
398                std::fs::copy(&path, &dest)?;
399                count += 1;
400            }
401        }
402    }
403    Ok(count)
404}
405
406/// The precompression pass (Wave 2c.5): sidecars for every text
407/// artifact, plus the shared zstd dictionary and `.dcz` encodings when
408/// the site has enough pages. Absent tools degrade gracefully (warning,
409/// not failure) - the estate's spawn-don't-link doctrine.
410fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
411    if !tools.any() {
412        report
413            .warnings
414            .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
415        return;
416    }
417    let mut compressed = 0usize;
418    let artifacts = report.artifacts.clone();
419    for artifact in &artifacts {
420        match compress::sidecars(tools, artifact) {
421            Ok(encodings) => compressed += encodings.len(),
422            Err(e) => report
423                .warnings
424                .push(format!("{}: compression failed: {e}", artifact.display())),
425        }
426    }
427    let dict_path = out.join("site.dict");
428    match compress::train_dictionary(tools, &artifacts, &dict_path) {
429        Ok(true) => {
430            report.dictionary = true;
431            compressed += 1;
432            for artifact in &artifacts {
433                if matches!(
434                    artifact.extension().and_then(|e| e.to_str()),
435                    Some("html") | Some("txt") | Some("xml") | Some("json")
436                ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
437                {
438                    compressed += 1;
439                }
440            }
441        }
442        Ok(false) => {
443            report.warnings.push(format!(
444                "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
445                artifacts.len()
446            ));
447        }
448        Err(e) => report
449            .warnings
450            .push(format!("dictionary training failed: {e}")),
451    }
452    report.compressed = compressed;
453}
454
455/// Map a request path to a file under `out`: empty → `index.html`;
456/// directories resolve to their `index.html`; an extensionless path
457/// falls back to `<path>.html`. Percent escapes are decoded; anything
458/// that escapes `out` (or games the encoding) resolves to nothing.
459#[must_use]
460pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
461    let path = url_path.split(['?', '#']).next().unwrap_or("");
462    let decoded = percent_decode(path)?;
463    let cleaned: Vec<&str> = decoded
464        .split('/')
465        .filter(|seg| !seg.is_empty() && *seg != ".")
466        .collect();
467    if cleaned.contains(&"..") {
468        return None;
469    }
470    let mut file = out.to_path_buf();
471    for seg in &cleaned {
472        file.push(seg);
473    }
474    if cleaned.is_empty() {
475        file.push("index.html");
476    }
477    if file.is_dir() {
478        file.push("index.html");
479    }
480    if !file.exists() && file.extension().is_none() {
481        let with_html = file.with_extension("html");
482        if with_html.is_file() {
483            return Some(with_html);
484        }
485        return None;
486    }
487    if file.is_file() {
488        Some(file)
489    } else {
490        None
491    }
492}
493
494/// Minimal percent-decoding for request paths; malformed escapes
495/// (`%` not followed by two hex digits) resolve to nothing.
496#[must_use]
497fn percent_decode(path: &str) -> Option<String> {
498    let mut out = Vec::with_capacity(path.len());
499    let mut bytes = path.bytes();
500    while let Some(b) = bytes.next() {
501        let value = if b == b'%' {
502            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
503            let hi = decode(bytes.next()?)?;
504            let lo = decode(bytes.next()?)?;
505            hi.checked_mul(16)?.checked_add(lo)?
506        } else {
507            b
508        };
509        out.push(value);
510    }
511    String::from_utf8(out).ok()
512}
513
514/// MIME type by extension; unknown extensions are plain text (the
515/// browser shows them instead of downloading).
516#[must_use]
517pub fn mime_for(path: &Path) -> &'static str {
518    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
519        "html" => "text/html; charset=utf-8",
520        "css" => "text/css; charset=utf-8",
521        "js" | "mjs" => "text/javascript; charset=utf-8",
522        "json" => "application/json",
523        "wasm" => "application/wasm",
524        "svg" => "image/svg+xml",
525        "png" => "image/png",
526        "jpg" | "jpeg" => "image/jpeg",
527        "gif" => "image/gif",
528        "ico" => "image/x-icon",
529        "md" => "text/markdown; charset=utf-8",
530        "xml" => "application/xml",
531        "txt" => "text/plain; charset=utf-8",
532        "bin" => "application/octet-stream",
533        "woff2" => "font/woff2",
534        _ => "text/plain; charset=utf-8",
535    }
536}