Skip to main content

docs_compiler/
seo.rs

1//! SEO emission (Wave 2c): full HTML documents with the estate-seo
2//! floor's technical artifacts - title, meta description, canonical,
3//! Open Graph, JSON-LD per page; `llms.txt`, `sitemap.xml`, and
4//! `robots.txt` per site (with `base_url` in `site.toml`).
5//!
6//! Policy decisions, recorded (estate-seo: never block AI crawlers
7//! silently): `site.toml` carries `ai_crawlers = "allow"` (default) /
8//! `"block-training"` / `"block-all"`, and the emitted robots.txt states
9//! the decision in a comment next to the rules.
10//!
11//! Inputs are deliberately tiny: front-matter is `key: value` scalars
12//! under a leading `---` fence; `site.toml` is `key = "value"` lines.
13//! No YAML/TOML dependency; anything richer belongs to a real pipeline.
14
15use std::path::Path;
16
17use crate::directives::html_escape;
18
19/// One indexable page, as the SEO emitters see it.
20#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22    /// Site-relative HTML route (`index.html`, `guides/x.html`).
23    pub route: String,
24    /// Page title (front-matter, first h1, or file stem).
25    pub title: String,
26    /// Meta description (front-matter or first paragraph).
27    pub description: String,
28    /// Declared publication date (ISO), for sitemap lastmod + JSON-LD.
29    pub date: Option<String>,
30}
31
32/// Site-wide settings, from `site.toml` in the source root.
33#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35    /// Absolute origin for canonical URLs, sitemap, and llms.txt
36    /// (`https://docs.example.com`, no trailing slash).
37    pub base_url: String,
38    /// Site title (llms.txt heading, JSON-LD `isPartOf`).
39    pub site_title: String,
40    /// Named author (E-E-A-T: real names beat anonymous).
41    pub author: String,
42    /// AI-crawler policy, recorded in robots.txt: `"allow"` (default),
43    /// `"block-training"`, `"block-all"`.
44    pub ai_crawlers: String,
45}
46
47impl SiteConfig {
48    /// Parse `site.toml` if present: `key = "value"` scalar lines only.
49    /// `base_url` is the one required key; the rest have defaults.
50    pub fn load(src: &Path) -> Option<SiteConfig> {
51        let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
52        let mut base_url = None;
53        let mut site_title = String::from("Documentation");
54        let mut author = String::new();
55        let mut ai_crawlers = String::from("allow");
56        for line in text.lines() {
57            let line = line.trim();
58            if line.is_empty() || line.starts_with('#') {
59                continue;
60            }
61            let Some((key, value)) = line.split_once('=') else {
62                continue;
63            };
64            let value = value.trim().trim_matches('"').to_string();
65            match key.trim() {
66                "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
67                "site_title" => site_title = value,
68                "author" => author = value,
69                "ai_crawlers" => ai_crawlers = value,
70                _ => {}
71            }
72        }
73        Some(SiteConfig {
74            base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
75            site_title,
76            author,
77            ai_crawlers,
78        })
79    }
80}
81
82/// Per-page metadata, from the page's front-matter (`---` fenced
83/// `key: value` scalars). `title` falls back to the first `<h1>`, then
84/// the file stem; `description` falls back to the first paragraph.
85#[derive(Debug, Clone, Default, PartialEq)]
86pub struct PageMeta {
87    /// Page title.
88    pub title: Option<String>,
89    /// Meta description.
90    pub description: Option<String>,
91    /// Output file stem override (route becomes `<slug>.html`).
92    pub slug: Option<String>,
93    /// Publication date (ISO `YYYY-MM-DD`; sitemap lastmod + JSON-LD).
94    pub date: Option<String>,
95}
96
97/// Split a leading `---` front-matter block off a document: returns the
98/// parsed metadata and the remainder to compile.
99#[must_use]
100pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
101    let mut meta = PageMeta::default();
102    let Some(rest) = markdown.strip_prefix("---\n") else {
103        return (meta, markdown.to_string());
104    };
105    let Some(close) = rest.find("\n---") else {
106        return (meta, markdown.to_string());
107    };
108    let block = &rest[..close];
109    for line in block.lines() {
110        let Some((key, value)) = line.split_once(':') else {
111            continue;
112        };
113        let value = value.trim().to_string();
114        match key.trim() {
115            "title" => meta.title = Some(value),
116            "description" => meta.description = Some(value),
117            "slug" => meta.slug = Some(value),
118            "date" => meta.date = Some(value),
119            _ => {}
120        }
121    }
122    // Skip the closing fence line and any following blank lines
123    // (markdown leading whitespace is insignificant).
124    let after = &rest[close + 4..];
125    (meta, after.trim_start_matches('\n').to_string())
126}
127
128/// Derive a page title from the rendered body: the first `<h1>` text.
129#[must_use]
130pub fn first_h1(body: &str) -> Option<String> {
131    let start = body.find("<h1>")? + 4;
132    let end = body[start..].find("</h1>")? + start;
133    let text = strip_tags(&body[start..end]);
134    if text.is_empty() {
135        None
136    } else {
137        Some(text)
138    }
139}
140
141/// Derive a description from the rendered body: the first paragraph's
142/// text, tags stripped, truncated at a word boundary to 155 chars.
143#[must_use]
144pub fn first_paragraph(body: &str) -> Option<String> {
145    let start = body.find("<p>")? + 3;
146    let end = body[start..].find("</p>")? + start;
147    let text = strip_tags(&body[start..end]);
148    if text.is_empty() {
149        return None;
150    }
151    Some(truncate_words(&text, 155))
152}
153
154fn strip_tags(html: &str) -> String {
155    let mut out = String::with_capacity(html.len());
156    let mut in_tag = false;
157    for c in html.chars() {
158        match c {
159            '<' => in_tag = true,
160            '>' => in_tag = false,
161            c if !in_tag => out.push(c),
162            _ => {}
163        }
164    }
165    out.trim().to_string()
166}
167
168fn truncate_words(text: &str, max: usize) -> String {
169    if text.len() <= max {
170        return text.to_string();
171    }
172    match text[..max].rfind(' ') {
173        Some(pos) => format!("{}...", &text[..pos]),
174        None => format!("{}...", &text[..max]),
175    }
176}
177
178/// Attribute-safe escaping: text escaping plus double quotes (SEO head
179/// values live inside `content="..."` attributes).
180fn escape_attr(text: &str) -> String {
181    html_escape(text).replace('"', "&quot;")
182}
183
184/// The full-document wrapper: doctype, head (charset, viewport, title,
185/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
186/// `route` is the page's site-relative HTML path (`index.html`,
187/// `guides/x.html`). Length guidance (title <=60, description <=155)
188/// surfaces as warnings in the report, not build failures.
189#[must_use]
190pub fn document(
191    body: &str,
192    meta: &PageMeta,
193    title: &str,
194    description: &str,
195    route: &str,
196    config: Option<&SiteConfig>,
197) -> String {
198    let canonical = config
199        .map(|c| format!("{}/{}", c.base_url, route))
200        .unwrap_or_default();
201    let canonical_tags = if canonical.is_empty() {
202        String::new()
203    } else {
204        format!(
205            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
206            u = escape_attr(&canonical)
207        )
208    };
209    let json_ld_tag = config
210        .map(|c| {
211            let mut article = serde_json::json!({
212                "@context": "https://schema.org",
213                "@type": "TechArticle",
214                "headline": title,
215                "description": description,
216                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
217            });
218            if let Some(obj) = article.as_object_mut() {
219                if !canonical.is_empty() {
220                    obj.insert("url".into(), serde_json::json!(canonical));
221                }
222                if !c.author.is_empty() {
223                    obj.insert(
224                        "author".into(),
225                        serde_json::json!({ "@type": "Person", "name": c.author }),
226                    );
227                }
228                if let Some(date) = &meta.date {
229                    obj.insert("datePublished".into(), serde_json::json!(date));
230                }
231            }
232            format!("<script type=\"application/ld+json\">{article}</script>")
233        })
234        .unwrap_or_default();
235    let site_name_tag = config
236        .map(|c| {
237            format!(
238                "<meta property=\"og:site_name\" content=\"{}\">",
239                escape_attr(&c.site_title)
240            )
241        })
242        .unwrap_or_default();
243    format!(
244        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
245<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
246<title>{t}</title>\
247<meta name=\"description\" content=\"{d}\">{canonical_tags}\
248<meta property=\"og:type\" content=\"article\">\
249<meta property=\"og:title\" content=\"{t}\">\
250<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
251<meta name=\"twitter:card\" content=\"summary\">\
252<meta name=\"twitter:title\" content=\"{t}\">\
253<meta name=\"twitter:description\" content=\"{d}\">\
254{json_ld_tag}</head><body>{body}</body></html>",
255        t = escape_attr(title),
256        d = escape_attr(description)
257    )
258}
259
260/// `llms.txt` (GEO floor): the site heading plus one curated link per
261/// page with its description.
262#[must_use]
263pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
264    let mut out = format!("# {}\n\n", config.site_title);
265    if !config.author.is_empty() {
266        out.push_str(&format!("By {}.\n\n", config.author));
267    }
268    for page in pages {
269        out.push_str(&format!(
270            "- [{t}]({u}/{r}): {d}\n",
271            t = page.title,
272            u = config.base_url,
273            r = page.route,
274            d = page.description
275        ));
276    }
277    out
278}
279
280/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
281/// when the page declares a date (deterministic builds do not lie about
282/// modification times).
283#[must_use]
284pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
285    let mut out = String::from(
286        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
287    );
288    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
289    sorted.sort_by(|a, b| a.route.cmp(&b.route));
290    for page in sorted {
291        let lastmod = page
292            .date
293            .as_ref()
294            .map(|d| format!("<lastmod>{d}</lastmod>"))
295            .unwrap_or_default();
296        out.push_str(&format!(
297            "<url><loc>{}/{}</loc>{lastmod}</url>\n",
298            config.base_url, page.route
299        ));
300    }
301    out.push_str("</urlset>\n");
302    out
303}
304
305/// `robots.txt` with the AI-crawler policy as a recorded decision.
306#[must_use]
307pub fn robots_txt(config: &SiteConfig) -> String {
308    let policy = config.ai_crawlers.as_str();
309    let mut out =
310        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
311    match policy {
312        "block-all" => {
313            out.push_str("User-agent: *\nDisallow: /\n");
314        }
315        "block-training" => {
316            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
317                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
318            }
319            out.push_str("User-agent: *\nAllow: /\n");
320        }
321        _ => {
322            out.push_str("User-agent: *\nAllow: /\n");
323        }
324    }
325    out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
326    out
327}