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