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 first two route segments ("content/TextAnimations",
318        // "extras/osint") so categories stay separate; the label is the
319        // key's last segment.
320        let segs: Vec<&str> = page.route.split('/').collect();
321        let key = match (segs.first(), segs.get(1)) {
322            (Some(top), Some(second)) => {
323                let stem = second.split('.').next().unwrap_or(second);
324                format!("{top}/{stem}")
325            }
326            _ => "pages".to_string(),
327        };
328        if !groups.contains_key(&key) {
329            order.push(key.clone());
330        }
331        groups
332            .entry(key)
333            .or_default()
334            .push((page.route.clone(), page.title.clone()));
335    }
336    let mut out = Vec::new();
337    for key in order {
338        let items = groups.remove(&key).unwrap_or_default();
339        let label = key.rsplit('/').next().unwrap_or(&key).to_string();
340        let active = active_route.starts_with(&format!("{key}/"));
341        out.push(NavGroup {
342            label: display_label(&key, &label),
343            active,
344            items,
345        });
346    }
347    out
348}
349
350/// Display label: capitalize the group's last segment for the sidebar.
351fn display_label(key: &str, label: &str) -> String {
352    let mut chars = label.chars();
353    match chars.next() {
354        Some(first) => {
355            let mut out = String::from(key);
356            out.clear();
357            out.push(first.to_ascii_uppercase());
358            out.push_str(chars.as_str());
359            out
360        }
361        None => key.to_string(),
362    }
363}
364
365fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
366    let pos = pages.iter().position(|p| p.route == route)?;
367    let previous = pos.checked_sub(1)?;
368    pages
369        .get(previous)
370        .map(|p| (p.route.clone(), p.title.clone()))
371}
372
373fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
374    let pos = pages.iter().position(|p| p.route == route)?;
375    pages
376        .get(pos + 1)
377        .map(|p| (p.route.clone(), p.title.clone()))
378}
379
380/// Mirror-copy a directory tree; returns the file count.
381fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
382    let mut count = 0usize;
383    let mut stack = vec![from.to_path_buf()];
384    while let Some(dir) = stack.pop() {
385        for entry in std::fs::read_dir(&dir)? {
386            let entry = entry?;
387            let path = entry.path();
388            if path.is_dir() {
389                stack.push(path);
390            } else {
391                let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
392                let dest = to.join(rel);
393                if let Some(parent) = dest.parent() {
394                    std::fs::create_dir_all(parent)?;
395                }
396                std::fs::copy(&path, &dest)?;
397                count += 1;
398            }
399        }
400    }
401    Ok(count)
402}
403
404/// The precompression pass (Wave 2c.5): sidecars for every text
405/// artifact, plus the shared zstd dictionary and `.dcz` encodings when
406/// the site has enough pages. Absent tools degrade gracefully (warning,
407/// not failure) - the estate's spawn-don't-link doctrine.
408fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
409    if !tools.any() {
410        report
411            .warnings
412            .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
413        return;
414    }
415    let mut compressed = 0usize;
416    let artifacts = report.artifacts.clone();
417    for artifact in &artifacts {
418        match compress::sidecars(tools, artifact) {
419            Ok(encodings) => compressed += encodings.len(),
420            Err(e) => report
421                .warnings
422                .push(format!("{}: compression failed: {e}", artifact.display())),
423        }
424    }
425    let dict_path = out.join("site.dict");
426    match compress::train_dictionary(tools, &artifacts, &dict_path) {
427        Ok(true) => {
428            report.dictionary = true;
429            compressed += 1;
430            for artifact in &artifacts {
431                if matches!(
432                    artifact.extension().and_then(|e| e.to_str()),
433                    Some("html") | Some("txt") | Some("xml") | Some("json")
434                ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
435                {
436                    compressed += 1;
437                }
438            }
439        }
440        Ok(false) => {
441            report.warnings.push(format!(
442                "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
443                artifacts.len()
444            ));
445        }
446        Err(e) => report
447            .warnings
448            .push(format!("dictionary training failed: {e}")),
449    }
450    report.compressed = compressed;
451}
452
453/// Map a request path to a file under `out`: empty → `index.html`;
454/// directories resolve to their `index.html`; an extensionless path
455/// falls back to `<path>.html`. Percent escapes are decoded; anything
456/// that escapes `out` (or games the encoding) resolves to nothing.
457#[must_use]
458pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
459    let path = url_path.split(['?', '#']).next().unwrap_or("");
460    let decoded = percent_decode(path)?;
461    let cleaned: Vec<&str> = decoded
462        .split('/')
463        .filter(|seg| !seg.is_empty() && *seg != ".")
464        .collect();
465    if cleaned.contains(&"..") {
466        return None;
467    }
468    let mut file = out.to_path_buf();
469    for seg in &cleaned {
470        file.push(seg);
471    }
472    if cleaned.is_empty() {
473        file.push("index.html");
474    }
475    if file.is_dir() {
476        file.push("index.html");
477    }
478    if !file.exists() && file.extension().is_none() {
479        let with_html = file.with_extension("html");
480        if with_html.is_file() {
481            return Some(with_html);
482        }
483        return None;
484    }
485    if file.is_file() {
486        Some(file)
487    } else {
488        None
489    }
490}
491
492/// Minimal percent-decoding for request paths; malformed escapes
493/// (`%` not followed by two hex digits) resolve to nothing.
494#[must_use]
495fn percent_decode(path: &str) -> Option<String> {
496    let mut out = Vec::with_capacity(path.len());
497    let mut bytes = path.bytes();
498    while let Some(b) = bytes.next() {
499        let value = if b == b'%' {
500            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
501            let hi = decode(bytes.next()?)?;
502            let lo = decode(bytes.next()?)?;
503            hi.checked_mul(16)?.checked_add(lo)?
504        } else {
505            b
506        };
507        out.push(value);
508    }
509    String::from_utf8(out).ok()
510}
511
512/// MIME type by extension; unknown extensions are plain text (the
513/// browser shows them instead of downloading).
514#[must_use]
515pub fn mime_for(path: &Path) -> &'static str {
516    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
517        "html" => "text/html; charset=utf-8",
518        "css" => "text/css; charset=utf-8",
519        "js" | "mjs" => "text/javascript; charset=utf-8",
520        "json" => "application/json",
521        "wasm" => "application/wasm",
522        "svg" => "image/svg+xml",
523        "png" => "image/png",
524        "jpg" | "jpeg" => "image/jpeg",
525        "gif" => "image/gif",
526        "ico" => "image/x-icon",
527        "md" => "text/markdown; charset=utf-8",
528        "xml" => "application/xml",
529        "txt" => "text/plain; charset=utf-8",
530        "bin" => "application/octet-stream",
531        "woff2" => "font/woff2",
532        _ => "text/plain; charset=utf-8",
533    }
534}