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    compile_site_with(src, out, None)
89}
90
91/// [`compile_site`] with a base-path override (subpath hosting: the
92/// preview deploy under `/solid-fx/preview` passes that prefix here and
93/// every chrome URL follows it).
94///
95/// # Errors
96/// Same as [`compile_site`].
97pub fn compile_site_with(
98    src: &Path,
99    out: &Path,
100    base_path_override: Option<&str>,
101) -> io::Result<SiteReport> {
102    let mut config = SiteConfig::load(src);
103    if let Some(bp) = base_path_override {
104        if let Some(c) = config.as_mut() {
105            c.base_path = bp.trim_end_matches('/').to_string();
106        }
107    }
108    let config = config;
109    let tools = compress::Tools::detect();
110    let mut report = SiteReport {
111        configured: config.is_some(),
112        ..SiteReport::default()
113    };
114
115    // Pass 1: render every page body and collect its metadata.
116    let mut pages: Vec<PageBuild> = Vec::new();
117    let mut stack = vec![src.to_path_buf()];
118    while let Some(dir) = stack.pop() {
119        for entry in std::fs::read_dir(&dir)? {
120            let entry = entry?;
121            let path = entry.path();
122            let name = entry.file_name();
123            let name = name.to_string_lossy();
124            if path.is_dir() {
125                if !name.starts_with('.') {
126                    stack.push(path);
127                }
128            } else if name.ends_with(".md") {
129                build_page(src, &path, &mut report, &mut pages);
130            }
131        }
132    }
133    pages.sort_by(|a, b| a.route.cmp(&b.route));
134
135    // Site assets: src/assets/** mirrors to out/_assets/** (the island
136    // base URL space), and the chrome stylesheet is emitted first so
137    // every wrapped page can link it.
138    let chrome_css = out.join("_assets").join("layout.css");
139    std::fs::create_dir_all(
140        chrome_css
141            .parent()
142            .map_or_else(|| Path::new("."), Path::new),
143    )?;
144    std::fs::write(&chrome_css, chrome::LAYOUT_CSS)?;
145    report.artifacts.push(chrome_css);
146    let assets_src = src.join("assets");
147    if assets_src.is_dir() {
148        report.assets_copied = copy_tree(&assets_src, &out.join("_assets"))?;
149    }
150
151    // Pass 2: chrome-wrap and write every page, in route order. The
152    // search corpus grows alongside (title/url/description/body JSON for
153    // the doc-search island, plus the docs-search binary index).
154    let base_path_str = config.as_ref().map(|c| c.base_path.clone());
155    let mut corpus = String::from("[\n");
156    let mut index = docs_search::IndexBuilder::new();
157    for page in &pages {
158        // Breadcrumbs: Home + the intermediate directory (no link unless
159        // a group index page exists - the styled 404 catches stale ones).
160        let segs: Vec<&str> = page.route.split('/').collect();
161        let home_href = base_path_str
162            .clone()
163            .map_or_else(|| "/".to_string(), |bp| format!("{bp}/"));
164        let mut breadcrumbs: Vec<(String, Option<String>)> =
165            vec![("Home".to_string(), Some(home_href))];
166        if segs.len() >= 3 {
167            let dir_label = segs[1].split('.').next().unwrap_or(segs[1]);
168            let mut label = dir_label.to_string();
169            if let Some(first) = label.chars().next() {
170                label = first.to_uppercase().to_string() + &label[first.len_utf8()..];
171            }
172            breadcrumbs.push((label, None));
173        }
174        let chrome = Chrome {
175            nav: nav_groups(&pages, &page.route),
176            active_route: page.route.clone(),
177            toc: chrome::extract_toc(&page.body),
178            prev: prev_of(&pages, &page.route),
179            next: next_of(&pages, &page.route),
180            search_island: config.as_ref().and_then(|c| c.search_island.clone()),
181            search_index: Some(match base_path_str.as_deref() {
182                Some("") | None => "/search.json".to_string(),
183                Some(bp) => format!("{bp}/search.json"),
184            }),
185        };
186        let doc = seo::document(
187            &page.body,
188            &page.meta,
189            &page.title,
190            &page.description,
191            &page.route,
192            config.as_ref(),
193            &breadcrumbs,
194        );
195        let site_title = config
196            .as_ref()
197            .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone());
198        let with_chrome = chrome::page(
199            &doc,
200            &site_title,
201            &chrome,
202            base_path_str.as_deref().unwrap_or(""),
203        );
204        let target = out.join(&page.route);
205        if let Some(parent) = target.parent() {
206            std::fs::create_dir_all(parent)?;
207        }
208        std::fs::write(&target, with_chrome)?;
209        report.built.push(page.source.clone());
210        report.artifacts.push(target);
211        report.pages.push(SeoPage {
212            route: page.route.clone(),
213            title: page.title.clone(),
214            description: page.description.clone(),
215            date: page.date.clone(),
216        });
217
218        corpus.push_str(&format!(
219            "{{\"title\":{},\"url\":{},\"description\":{},\"body\":{}}},\n",
220            serde_json::to_string(&page.title).unwrap_or_else(|_| "\"\"".into()),
221            serde_json::to_string(&format!("/{}", page.route)).unwrap_or_else(|_| "\"\"".into()),
222            serde_json::to_string(&page.description).unwrap_or_else(|_| "\"\"".into()),
223            serde_json::to_string(&page.text).unwrap_or_else(|_| "\"\"".into()),
224        ));
225        let _ = index.add_doc(&format!(
226            "{} {} {}",
227            page.title, page.description, page.text
228        ));
229    }
230
231    // SEO artifacts.
232    if let Some(config) = &config {
233        let page_refs: &[SeoPage] = &report.pages;
234        for (name, content) in [
235            ("llms.txt", seo::llms_txt(config, page_refs)),
236            ("sitemap.xml", seo::sitemap_xml(config, page_refs)),
237            ("robots.txt", seo::robots_txt(config)),
238        ] {
239            let path = out.join(name);
240            std::fs::write(&path, content)?;
241            report.artifacts.push(path);
242        }
243        let feed_path = out.join("atom.xml");
244        std::fs::write(&feed_path, seo::atom_xml(config, page_refs))?;
245        report.artifacts.push(feed_path);
246    }
247
248    // Styled 404: a chrome-wrapped page served for missing routes.
249    let not_found = seo::document(
250        "<h1>404</h1><p>This page does not exist. Use the navigation to find your way back.</p>",
251        &seo::PageMeta::default(),
252        "404 - not found",
253        "Page not found.",
254        "404.html",
255        config.as_ref(),
256        &[],
257    );
258    let not_found = chrome::page(
259        &not_found,
260        &config
261            .as_ref()
262            .map_or_else(|| "Docs".to_string(), |c| c.site_title.clone()),
263        &chrome::Chrome {
264            nav: nav_groups(&pages, ""),
265            active_route: "404.html".into(),
266            toc: Vec::new(),
267            prev: None,
268            next: None,
269            search_island: config.as_ref().and_then(|c| c.search_island.clone()),
270            search_index: Some(match base_path_str.as_deref() {
271                Some("") | None => "/search.json".to_string(),
272                Some(bp) => format!("{bp}/search.json"),
273            }),
274        },
275        base_path_str.as_deref().unwrap_or(""),
276    );
277    let not_found_path = out.join("404.html");
278    std::fs::write(&not_found_path, not_found)?;
279    report.artifacts.push(not_found_path);
280
281    // Search artifacts: the JSON corpus for the doc-search island and a
282    // docs-search binary index for the future in-browser reader.
283    if !report.pages.is_empty() {
284        corpus.push_str("]\n");
285        let corpus_path = out.join("search.json");
286        std::fs::write(&corpus_path, corpus)?;
287        report.artifacts.push(corpus_path);
288        let index_path = out.join("search.bin");
289        match index.build() {
290            Ok(bytes) => {
291                std::fs::write(&index_path, bytes)?;
292                report.artifacts.push(index_path);
293            }
294            Err(e) => report
295                .warnings
296                .push(format!("search index build failed: {e}")),
297        }
298    }
299
300    precompress(out, &tools, &mut report);
301    Ok(report)
302}
303
304/// Build one page's metadata and body into the pending list. All
305/// failures land in the report - one bad page never blocks the site.
306fn build_page(src: &Path, path: &Path, report: &mut SiteReport, pages: &mut Vec<PageBuild>) {
307    let rel = match path.strip_prefix(src) {
308        Ok(r) => r.to_path_buf(),
309        Err(_) => path.to_path_buf(),
310    };
311    let source = match std::fs::read_to_string(path) {
312        Ok(s) => s,
313        Err(e) => {
314            report.errors.push((path.to_path_buf(), e.to_string()));
315            return;
316        }
317    };
318    let (meta, body_markdown) = seo::split_front_matter(&source);
319    let root = path
320        .parent()
321        .filter(|p| !p.as_os_str().is_empty())
322        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
323    let body = match compile(&body_markdown, &BuildContext::new(root)) {
324        Ok(html) => html,
325        Err(e) => {
326            report.errors.push((path.to_path_buf(), e.to_string()));
327            return;
328        }
329    };
330
331    let stem = meta.slug.clone().unwrap_or_else(|| {
332        rel.file_stem()
333            .unwrap_or_default()
334            .to_string_lossy()
335            .into_owned()
336    });
337    let dir = rel.parent().unwrap_or(Path::new(""));
338    let route = if dir.as_os_str().is_empty() {
339        format!("{stem}.html")
340    } else {
341        format!("{}/{}.html", dir.display(), stem)
342    };
343    let title = meta
344        .title
345        .clone()
346        .or_else(|| seo::first_h1(&body))
347        .unwrap_or_else(|| {
348            rel.file_stem()
349                .map(|s| s.to_string_lossy().into_owned())
350                .unwrap_or_else(|| "Untitled".to_string())
351        });
352    let description = meta
353        .description
354        .clone()
355        .or_else(|| seo::first_paragraph(&body))
356        .unwrap_or_default();
357
358    if title.chars().count() > 60 {
359        report.warnings.push(format!(
360            "{route}: title is {} chars (guidance: <= 60)",
361            title.chars().count()
362        ));
363    }
364    if description.is_empty() {
365        report.warnings.push(format!(
366            "{route}: no description (front-matter or first paragraph)"
367        ));
368    } else if description.chars().count() > 155 {
369        report.warnings.push(format!(
370            "{route}: description is {} chars (guidance: <= 155)",
371            description.chars().count()
372        ));
373    }
374
375    pages.push(PageBuild {
376        source: path.to_path_buf(),
377        route,
378        title,
379        description,
380        date: meta.date.clone(),
381        meta,
382        text: crate::seo::plain_text(&body),
383        body,
384    });
385}
386
387/// Sidebar nav groups: group pages by their first route segment, label
388/// groups by the second segment when present ("content/TextAnimations"
389/// -> "TextAnimations"). The homepage stays out - the header brand
390/// links it.
391fn nav_groups(pages: &[PageBuild], active_route: &str) -> Vec<NavGroup> {
392    let mut order: Vec<String> = Vec::new();
393    let mut groups: std::collections::HashMap<String, Vec<(String, String)>> =
394        std::collections::HashMap::new();
395    for page in pages {
396        if page.route == "index.html" {
397            continue;
398        }
399        // Group key: the directory the page lives in. Depth-2 routes
400        // ("guides/one.html") group under their top segment; deeper
401        // routes group under the first two ("extras/osint"), so
402        // categories stay separate.
403        let segs: Vec<&str> = page.route.split('/').collect();
404        let key = match (segs.first(), segs.get(1)) {
405            (Some(top), Some(second)) if second.contains('.') => (*top).to_string(),
406            (Some(top), Some(second)) => format!(
407                "{top}/{stem}",
408                stem = second.split('.').next().unwrap_or(second)
409            ),
410            _ => "pages".to_string(),
411        };
412        if !groups.contains_key(&key) {
413            order.push(key.clone());
414        }
415        groups
416            .entry(key)
417            .or_default()
418            .push((page.route.clone(), page.title.clone()));
419    }
420    let mut out = Vec::new();
421    for key in order {
422        let items = groups.remove(&key).unwrap_or_default();
423        let label = key.rsplit('/').next().unwrap_or(&key).to_string();
424        let active = active_route.starts_with(&format!("{key}/"));
425        out.push(NavGroup {
426            label: display_label(&key, &label),
427            active,
428            items,
429        });
430    }
431    out
432}
433
434/// Display label: capitalize the group's last segment for the sidebar.
435fn display_label(key: &str, label: &str) -> String {
436    let mut chars = label.chars();
437    match chars.next() {
438        Some(first) => {
439            let mut out = String::from(key);
440            out.clear();
441            out.push(first.to_ascii_uppercase());
442            out.push_str(chars.as_str());
443            out
444        }
445        None => key.to_string(),
446    }
447}
448
449fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
450    let pos = pages.iter().position(|p| p.route == route)?;
451    let previous = pos.checked_sub(1)?;
452    pages
453        .get(previous)
454        .map(|p| (p.route.clone(), p.title.clone()))
455}
456
457fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
458    let pos = pages.iter().position(|p| p.route == route)?;
459    pages
460        .get(pos + 1)
461        .map(|p| (p.route.clone(), p.title.clone()))
462}
463
464/// Mirror-copy a directory tree; returns the file count.
465fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
466    let mut count = 0usize;
467    let mut stack = vec![from.to_path_buf()];
468    while let Some(dir) = stack.pop() {
469        for entry in std::fs::read_dir(&dir)? {
470            let entry = entry?;
471            let path = entry.path();
472            if path.is_dir() {
473                stack.push(path);
474            } else {
475                let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
476                let dest = to.join(rel);
477                if let Some(parent) = dest.parent() {
478                    std::fs::create_dir_all(parent)?;
479                }
480                std::fs::copy(&path, &dest)?;
481                count += 1;
482            }
483        }
484    }
485    Ok(count)
486}
487
488/// The precompression pass (Wave 2c.5): sidecars for every text
489/// artifact, plus the shared zstd dictionary and `.dcz` encodings when
490/// the site has enough pages. Absent tools degrade gracefully (warning,
491/// not failure) - the estate's spawn-don't-link doctrine.
492fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
493    if !tools.any() {
494        report
495            .warnings
496            .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
497        return;
498    }
499    let mut compressed = 0usize;
500    let artifacts = report.artifacts.clone();
501    for artifact in &artifacts {
502        match compress::sidecars(tools, artifact) {
503            Ok(encodings) => compressed += encodings.len(),
504            Err(e) => report
505                .warnings
506                .push(format!("{}: compression failed: {e}", artifact.display())),
507        }
508    }
509    let dict_path = out.join("site.dict");
510    match compress::train_dictionary(tools, &artifacts, &dict_path) {
511        Ok(true) => {
512            report.dictionary = true;
513            compressed += 1;
514            for artifact in &artifacts {
515                if matches!(
516                    artifact.extension().and_then(|e| e.to_str()),
517                    Some("html") | Some("txt") | Some("xml") | Some("json")
518                ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
519                {
520                    compressed += 1;
521                }
522            }
523        }
524        Ok(false) => {
525            report.warnings.push(format!(
526                "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
527                artifacts.len()
528            ));
529        }
530        Err(e) => report
531            .warnings
532            .push(format!("dictionary training failed: {e}")),
533    }
534    report.compressed = compressed;
535}
536
537/// Map a request path to a file under `out`: empty → `index.html`;
538/// directories resolve to their `index.html`; an extensionless path
539/// falls back to `<path>.html`. Percent escapes are decoded; anything
540/// that escapes `out` (or games the encoding) resolves to nothing.
541#[must_use]
542pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
543    let path = url_path.split(['?', '#']).next().unwrap_or("");
544    let decoded = percent_decode(path)?;
545    let cleaned: Vec<&str> = decoded
546        .split('/')
547        .filter(|seg| !seg.is_empty() && *seg != ".")
548        .collect();
549    if cleaned.contains(&"..") {
550        return None;
551    }
552    let mut file = out.to_path_buf();
553    for seg in &cleaned {
554        file.push(seg);
555    }
556    if cleaned.is_empty() {
557        file.push("index.html");
558    }
559    if file.is_dir() {
560        file.push("index.html");
561    }
562    if !file.exists() && file.extension().is_none() {
563        let with_html = file.with_extension("html");
564        if with_html.is_file() {
565            return Some(with_html);
566        }
567        return None;
568    }
569    if file.is_file() {
570        Some(file)
571    } else {
572        None
573    }
574}
575
576/// Minimal percent-decoding for request paths; malformed escapes
577/// (`%` not followed by two hex digits) resolve to nothing.
578#[must_use]
579fn percent_decode(path: &str) -> Option<String> {
580    let mut out = Vec::with_capacity(path.len());
581    let mut bytes = path.bytes();
582    while let Some(b) = bytes.next() {
583        let value = if b == b'%' {
584            let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
585            let hi = decode(bytes.next()?)?;
586            let lo = decode(bytes.next()?)?;
587            hi.checked_mul(16)?.checked_add(lo)?
588        } else {
589            b
590        };
591        out.push(value);
592    }
593    String::from_utf8(out).ok()
594}
595
596/// MIME type by extension; unknown extensions are plain text (the
597/// browser shows them instead of downloading).
598#[must_use]
599pub fn mime_for(path: &Path) -> &'static str {
600    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
601        "html" => "text/html; charset=utf-8",
602        "css" => "text/css; charset=utf-8",
603        "js" | "mjs" => "text/javascript; charset=utf-8",
604        "json" => "application/json",
605        "wasm" => "application/wasm",
606        "svg" => "image/svg+xml",
607        "png" => "image/png",
608        "jpg" | "jpeg" => "image/jpeg",
609        "gif" => "image/gif",
610        "ico" => "image/x-icon",
611        "md" => "text/markdown; charset=utf-8",
612        "xml" => "application/xml",
613        "txt" => "text/plain; charset=utf-8",
614        "bin" => "application/octet-stream",
615        "woff2" => "font/woff2",
616        _ => "text/plain; charset=utf-8",
617    }
618}