1use 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#[derive(Debug, Default, Clone)]
29pub struct SiteReport {
30 pub built: Vec<PathBuf>,
32 pub errors: Vec<(PathBuf, String)>,
34 pub warnings: Vec<String>,
37 pub pages: Vec<SeoPage>,
40 pub configured: bool,
42 pub artifacts: Vec<PathBuf>,
45 pub compressed: usize,
47 pub dictionary: bool,
50 pub assets_copied: usize,
52}
53
54impl SiteReport {
55 pub fn is_clean(&self) -> bool {
57 self.errors.is_empty()
58 }
59}
60
61struct 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 text: String,
72}
73
74pub fn compile_site(src: &Path, out: &Path) -> io::Result<SiteReport> {
88 compile_site_with(src, out, None)
89}
90
91pub 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 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 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 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 let segs: Vec<&str> = page.route.split('/').collect();
161 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(match base_path_str.as_deref() {
179 Some("") | None => "/search.json".to_string(),
180 Some(bp) => format!("{bp}/search.json"),
181 }),
182 search_wasm: config.as_ref().and_then(|c| c.search_wasm.clone()),
183 search_bin: config.as_ref().and_then(|c| c.search_bin.clone()),
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_entries.push(format!(
218 "{{\"title\":{},\"url\":{},\"description\":{},\"body\":{}}}",
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 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 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 ¬_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, "404.html"),
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 search_wasm: config.as_ref().and_then(|c| c.search_wasm.clone()),
274 search_bin: config.as_ref().and_then(|c| c.search_bin.clone()),
275 },
276 base_path_str.as_deref().unwrap_or(""),
277 );
278 let not_found_path = out.join("404.html");
279 std::fs::write(¬_found_path, not_found)?;
280 report.artifacts.push(not_found_path);
281
282 if !corpus_entries.is_empty() {
285 let corpus = format!("[\n{}\n]\n", corpus_entries.join(",\n"));
286 let corpus_path = out.join("search.json");
287 std::fs::write(&corpus_path, corpus)?;
288 report.artifacts.push(corpus_path);
289 let index_path = out.join("search.bin");
290 match index.build() {
291 Ok(bytes) => {
292 std::fs::write(&index_path, bytes)?;
293 report.artifacts.push(index_path);
294 }
295 Err(e) => report
296 .warnings
297 .push(format!("search index build failed: {e}")),
298 }
299 }
300
301 precompress(out, &tools, &mut report);
302 Ok(report)
303}
304
305fn build_page(
308 src: &Path,
309 path: &Path,
310 config: Option<&SiteConfig>,
311 report: &mut SiteReport,
312 pages: &mut Vec<PageBuild>,
313) {
314 let rel = match path.strip_prefix(src) {
315 Ok(r) => r.to_path_buf(),
316 Err(_) => path.to_path_buf(),
317 };
318 let source = match std::fs::read_to_string(path) {
319 Ok(s) => s,
320 Err(e) => {
321 report.errors.push((path.to_path_buf(), e.to_string()));
322 return;
323 }
324 };
325 let (meta, body_markdown) = seo::split_front_matter(&source);
326 let root = path
327 .parent()
328 .filter(|p| !p.as_os_str().is_empty())
329 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
330 let ctx = match config {
331 Some(c) if !c.base_path.is_empty() => {
332 BuildContext::with_asset_base(root, format!("{}/_assets", c.base_path))
333 }
334 _ => BuildContext::new(root),
335 };
336 let body = match compile(&body_markdown, &ctx) {
337 Ok(html) => html,
338 Err(e) => {
339 report.errors.push((path.to_path_buf(), e.to_string()));
340 return;
341 }
342 };
343
344 let stem = meta.slug.clone().unwrap_or_else(|| {
345 rel.file_stem()
346 .unwrap_or_default()
347 .to_string_lossy()
348 .into_owned()
349 });
350 let dir = rel.parent().unwrap_or(Path::new(""));
351 let route = if dir.as_os_str().is_empty() {
352 format!("{stem}.html")
353 } else {
354 format!("{}/{}.html", dir.display(), stem)
355 };
356 let title = meta
357 .title
358 .clone()
359 .or_else(|| seo::first_h1(&body))
360 .unwrap_or_else(|| {
361 rel.file_stem()
362 .map(|s| s.to_string_lossy().into_owned())
363 .unwrap_or_else(|| "Untitled".to_string())
364 });
365 let description = meta
366 .description
367 .clone()
368 .or_else(|| seo::first_paragraph(&body))
369 .unwrap_or_default();
370
371 if title.chars().count() > 60 {
372 report.warnings.push(format!(
373 "{route}: title is {} chars (guidance: <= 60)",
374 title.chars().count()
375 ));
376 }
377 if description.is_empty() {
378 report.warnings.push(format!(
379 "{route}: no description (front-matter or first paragraph)"
380 ));
381 } else if description.chars().count() > 155 {
382 report.warnings.push(format!(
383 "{route}: description is {} chars (guidance: <= 155)",
384 description.chars().count()
385 ));
386 }
387
388 pages.push(PageBuild {
389 source: path.to_path_buf(),
390 route,
391 title,
392 description,
393 date: meta.date.clone(),
394 meta,
395 text: crate::seo::plain_text(&body),
396 body,
397 });
398}
399
400fn nav_groups(pages: &[PageBuild], active_route: &str) -> Vec<NavGroup> {
405 let mut order: Vec<String> = Vec::new();
406 let mut groups: std::collections::HashMap<String, Vec<(String, String)>> =
407 std::collections::HashMap::new();
408 for page in pages {
409 if page.route == "index.html" {
410 continue;
411 }
412 let segs: Vec<&str> = page.route.split('/').collect();
417 let key = match (segs.first(), segs.get(1)) {
418 (Some(top), Some(second)) if second.contains('.') => (*top).to_string(),
419 (Some(top), Some(second)) => format!(
420 "{top}/{stem}",
421 stem = second.split('.').next().unwrap_or(second)
422 ),
423 _ => "pages".to_string(),
424 };
425 if !groups.contains_key(&key) {
426 order.push(key.clone());
427 }
428 groups
429 .entry(key)
430 .or_default()
431 .push((page.route.clone(), page.title.clone()));
432 }
433 let mut out = Vec::new();
434 for key in order {
435 let items = groups.remove(&key).unwrap_or_default();
436 let label = key.rsplit('/').next().unwrap_or(&key).to_string();
437 let active = active_route.starts_with(&format!("{key}/"));
438 out.push(NavGroup {
439 label: display_label(&key, &label),
440 active,
441 items,
442 });
443 }
444 out
445}
446
447fn display_label(key: &str, label: &str) -> String {
449 let mut chars = label.chars();
450 match chars.next() {
451 Some(first) => {
452 let mut out = String::from(key);
453 out.clear();
454 out.push(first.to_ascii_uppercase());
455 out.push_str(chars.as_str());
456 out
457 }
458 None => key.to_string(),
459 }
460}
461
462fn prev_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
463 let pos = pages.iter().position(|p| p.route == route)?;
464 let previous = pos.checked_sub(1)?;
465 pages
466 .get(previous)
467 .map(|p| (p.route.clone(), p.title.clone()))
468}
469
470fn next_of(pages: &[PageBuild], route: &str) -> Option<(String, String)> {
471 let pos = pages.iter().position(|p| p.route == route)?;
472 pages
473 .get(pos + 1)
474 .map(|p| (p.route.clone(), p.title.clone()))
475}
476
477fn copy_tree(from: &Path, to: &Path) -> io::Result<usize> {
479 let mut count = 0usize;
480 let mut stack = vec![from.to_path_buf()];
481 while let Some(dir) = stack.pop() {
482 for entry in std::fs::read_dir(&dir)? {
483 let entry = entry?;
484 let path = entry.path();
485 if path.is_dir() {
486 stack.push(path);
487 } else {
488 let rel = path.strip_prefix(from).unwrap_or(&path).to_path_buf();
489 let dest = to.join(rel);
490 if let Some(parent) = dest.parent() {
491 std::fs::create_dir_all(parent)?;
492 }
493 std::fs::copy(&path, &dest)?;
494 count += 1;
495 }
496 }
497 }
498 Ok(count)
499}
500
501fn precompress(out: &Path, tools: &compress::Tools, report: &mut SiteReport) {
506 if !tools.any() {
507 report
508 .warnings
509 .push("no gzip/brotli/zstd on PATH: precompression skipped".into());
510 return;
511 }
512 let mut compressed = 0usize;
513 let artifacts = report.artifacts.clone();
514 for artifact in &artifacts {
515 match compress::sidecars(tools, artifact) {
516 Ok(encodings) => compressed += encodings.len(),
517 Err(e) => report
518 .warnings
519 .push(format!("{}: compression failed: {e}", artifact.display())),
520 }
521 }
522 let dict_path = out.join("site.dict");
523 match compress::train_dictionary(tools, &artifacts, &dict_path) {
524 Ok(true) => {
525 report.dictionary = true;
526 compressed += 1;
527 for artifact in &artifacts {
528 if matches!(
529 artifact.extension().and_then(|e| e.to_str()),
530 Some("html") | Some("txt") | Some("xml") | Some("json")
531 ) && compress::dcz_sidecar(tools, &dict_path, artifact).unwrap_or(false)
532 {
533 compressed += 1;
534 }
535 }
536 }
537 Ok(false) => {
538 report.warnings.push(format!(
539 "shared dictionary skipped ({} artifacts: zstd trains on >= 8 samples)",
540 artifacts.len()
541 ));
542 }
543 Err(e) => report
544 .warnings
545 .push(format!("dictionary training failed: {e}")),
546 }
547 report.compressed = compressed;
548}
549
550#[must_use]
555pub fn resolve_route(out: &Path, url_path: &str) -> Option<PathBuf> {
556 let path = url_path.split(['?', '#']).next().unwrap_or("");
557 let decoded = percent_decode(path)?;
558 let cleaned: Vec<&str> = decoded
559 .split('/')
560 .filter(|seg| !seg.is_empty() && *seg != ".")
561 .collect();
562 if cleaned.contains(&"..") {
563 return None;
564 }
565 let mut file = out.to_path_buf();
566 for seg in &cleaned {
567 file.push(seg);
568 }
569 if cleaned.is_empty() {
570 file.push("index.html");
571 }
572 if file.is_dir() {
573 file.push("index.html");
574 }
575 if !file.exists() && file.extension().is_none() {
576 let with_html = file.with_extension("html");
577 if with_html.is_file() {
578 return Some(with_html);
579 }
580 return None;
581 }
582 if file.is_file() {
583 Some(file)
584 } else {
585 None
586 }
587}
588
589#[must_use]
592fn percent_decode(path: &str) -> Option<String> {
593 let mut out = Vec::with_capacity(path.len());
594 let mut bytes = path.bytes();
595 while let Some(b) = bytes.next() {
596 let value = if b == b'%' {
597 let decode = |d: u8| (d as char).to_digit(16).map(|v| v as u8);
598 let hi = decode(bytes.next()?)?;
599 let lo = decode(bytes.next()?)?;
600 hi.checked_mul(16)?.checked_add(lo)?
601 } else {
602 b
603 };
604 out.push(value);
605 }
606 String::from_utf8(out).ok()
607}
608
609#[must_use]
612pub fn mime_for(path: &Path) -> &'static str {
613 match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
614 "html" => "text/html; charset=utf-8",
615 "css" => "text/css; charset=utf-8",
616 "js" | "mjs" => "text/javascript; charset=utf-8",
617 "json" => "application/json",
618 "wasm" => "application/wasm",
619 "svg" => "image/svg+xml",
620 "png" => "image/png",
621 "jpg" | "jpeg" => "image/jpeg",
622 "gif" => "image/gif",
623 "ico" => "image/x-icon",
624 "md" => "text/markdown; charset=utf-8",
625 "xml" => "application/xml",
626 "txt" => "text/plain; charset=utf-8",
627 "bin" => "application/octet-stream",
628 "woff2" => "font/woff2",
629 _ => "text/plain; charset=utf-8",
630 }
631}