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