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    /// Stylesheet URL emitted as a `<link rel="stylesheet">` in every
46    /// page head (e.g. the islands' Tailwind build).
47    pub stylesheet: Option<String>,
48    /// The island shim module URL, emitted as a deferred module script
49    /// in every page head (registers `<docs-island>`).
50    pub island_shim: Option<String>,
51    /// The search island chunk URL, emitted as a search trigger in the
52    /// header (props point at `/search.json`).
53    pub search_island: Option<String>,
54}
55
56impl SiteConfig {
57    /// Parse `site.toml` if present: `key = "value"` scalar lines only.
58    /// `base_url` is the one required key; the rest have defaults.
59    pub fn load(src: &Path) -> Option<SiteConfig> {
60        let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
61        let mut base_url = None;
62        let mut site_title = String::from("Documentation");
63        let mut author = String::new();
64        let mut ai_crawlers = String::from("allow");
65        let mut stylesheet = None;
66        let mut island_shim = None;
67        let mut search_island = None;
68        for line in text.lines() {
69            let line = line.trim();
70            if line.is_empty() || line.starts_with('#') {
71                continue;
72            }
73            let Some((key, value)) = line.split_once('=') else {
74                continue;
75            };
76            let value = value.trim().trim_matches('"').to_string();
77            match key.trim() {
78                "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
79                "site_title" => site_title = value,
80                "author" => author = value,
81                "ai_crawlers" => ai_crawlers = value,
82                "stylesheet" => stylesheet = Some(value),
83                "island_shim" => island_shim = Some(value),
84                "search_island" => search_island = Some(value),
85                _ => {}
86            }
87        }
88        Some(SiteConfig {
89            base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
90            site_title,
91            author,
92            ai_crawlers,
93            stylesheet,
94            island_shim,
95            search_island,
96        })
97    }
98}
99
100/// Per-page metadata, from the page's front-matter (`---` fenced
101/// `key: value` scalars). `title` falls back to the first `<h1>`, then
102/// the file stem; `description` falls back to the first paragraph.
103#[derive(Debug, Clone, Default, PartialEq)]
104pub struct PageMeta {
105    /// Page title.
106    pub title: Option<String>,
107    /// Meta description.
108    pub description: Option<String>,
109    /// Output file stem override (route becomes `<slug>.html`).
110    pub slug: Option<String>,
111    /// Publication date (ISO `YYYY-MM-DD`; sitemap lastmod + JSON-LD).
112    pub date: Option<String>,
113}
114
115/// Split a leading `---` front-matter block off a document: returns the
116/// parsed metadata and the remainder to compile.
117#[must_use]
118pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
119    let mut meta = PageMeta::default();
120    let Some(rest) = markdown.strip_prefix("---\n") else {
121        return (meta, markdown.to_string());
122    };
123    let Some(close) = rest.find("\n---") else {
124        return (meta, markdown.to_string());
125    };
126    let block = &rest[..close];
127    for line in block.lines() {
128        let Some((key, value)) = line.split_once(':') else {
129            continue;
130        };
131        let value = value.trim().to_string();
132        match key.trim() {
133            "title" => meta.title = Some(value),
134            "description" => meta.description = Some(value),
135            "slug" => meta.slug = Some(value),
136            "date" => meta.date = Some(value),
137            _ => {}
138        }
139    }
140    // Skip the closing fence line and any following blank lines
141    // (markdown leading whitespace is insignificant).
142    let after = &rest[close + 4..];
143    (meta, after.trim_start_matches('\n').to_string())
144}
145
146/// Derive a page title from the rendered body: the first `<h1>` text.
147#[must_use]
148pub fn first_h1(body: &str) -> Option<String> {
149    let start = body.find("<h1>")? + 4;
150    let end = body[start..].find("</h1>")? + start;
151    let text = strip_tags(&body[start..end]);
152    if text.is_empty() {
153        None
154    } else {
155        Some(text)
156    }
157}
158
159/// Derive a description from the rendered body: the first paragraph's
160/// text, tags stripped, truncated at a word boundary to 155 chars.
161#[must_use]
162pub fn first_paragraph(body: &str) -> Option<String> {
163    let start = body.find("<p>")? + 3;
164    let end = body[start..].find("</p>")? + start;
165    let text = strip_tags(&body[start..end]);
166    if text.is_empty() {
167        return None;
168    }
169    Some(truncate_words(&text, 155))
170}
171
172/// Strip all tags from rendered HTML and collapse whitespace: the
173/// plain-text view used for search corpora.
174#[must_use]
175pub fn plain_text(body: &str) -> String {
176    let text = strip_tags(body);
177    text.split_whitespace().collect::<Vec<_>>().join(" ")
178}
179
180fn strip_tags(html: &str) -> String {
181    let mut out = String::with_capacity(html.len());
182    let mut in_tag = false;
183    for c in html.chars() {
184        match c {
185            '<' => in_tag = true,
186            '>' => in_tag = false,
187            c if !in_tag => out.push(c),
188            _ => {}
189        }
190    }
191    out.trim().to_string()
192}
193
194fn truncate_words(text: &str, max: usize) -> String {
195    if text.len() <= max {
196        return text.to_string();
197    }
198    match text[..max].rfind(' ') {
199        Some(pos) => format!("{}...", &text[..pos]),
200        None => format!("{}...", &text[..max]),
201    }
202}
203
204/// Attribute-safe escaping: text escaping plus double quotes (SEO head
205/// values live inside `content="..."` attributes).
206fn escape_attr(text: &str) -> String {
207    html_escape(text).replace('"', "&quot;")
208}
209
210/// The full-document wrapper: doctype, head (charset, viewport, title,
211/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
212/// `route` is the page's site-relative HTML path (`index.html`,
213/// `guides/x.html`). Length guidance (title <=60, description <=155)
214/// surfaces as warnings in the report, not build failures.
215#[must_use]
216pub fn document(
217    body: &str,
218    meta: &PageMeta,
219    title: &str,
220    description: &str,
221    route: &str,
222    config: Option<&SiteConfig>,
223) -> String {
224    let canonical = config
225        .map(|c| format!("{}/{}", c.base_url, route))
226        .unwrap_or_default();
227    let canonical_tags = if canonical.is_empty() {
228        String::new()
229    } else {
230        format!(
231            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
232            u = escape_attr(&canonical)
233        )
234    };
235    let json_ld_tag = config
236        .map(|c| {
237            let mut article = serde_json::json!({
238                "@context": "https://schema.org",
239                "@type": "TechArticle",
240                "headline": title,
241                "description": description,
242                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
243            });
244            if let Some(obj) = article.as_object_mut() {
245                if !canonical.is_empty() {
246                    obj.insert("url".into(), serde_json::json!(canonical));
247                }
248                if !c.author.is_empty() {
249                    obj.insert(
250                        "author".into(),
251                        serde_json::json!({ "@type": "Person", "name": c.author }),
252                    );
253                }
254                if let Some(date) = &meta.date {
255                    obj.insert("datePublished".into(), serde_json::json!(date));
256                }
257            }
258            format!("<script type=\"application/ld+json\">{article}</script>")
259        })
260        .unwrap_or_default();
261    let site_name_tag = config
262        .map(|c| {
263            format!(
264                "<meta property=\"og:site_name\" content=\"{}\">",
265                escape_attr(&c.site_title)
266            )
267        })
268        .unwrap_or_default();
269    // Site-level head wiring (Wave 2c.5): the islands' stylesheet and
270    // the shim module that registers <docs-island>.
271    let head_extra = config
272        .map(|c| {
273            let mut extra = String::new();
274            if let Some(css) = &c.stylesheet {
275                extra.push_str(&format!(
276                    "<link rel=\"stylesheet\" href=\"{}\">",
277                    escape_attr(css)
278                ));
279            }
280            if let Some(shim) = &c.island_shim {
281                extra.push_str(&format!(
282                    "<script type=\"module\" src=\"{}\"></script>",
283                    escape_attr(shim)
284                ));
285            }
286            extra
287        })
288        .unwrap_or_default();
289    format!(
290        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
291<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
292<title>{t}</title>\
293<meta name=\"description\" content=\"{d}\">{canonical_tags}\
294<meta property=\"og:type\" content=\"article\">\
295<meta property=\"og:title\" content=\"{t}\">\
296<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
297<meta name=\"twitter:card\" content=\"summary\">\
298<meta name=\"twitter:title\" content=\"{t}\">\
299<meta name=\"twitter:description\" content=\"{d}\">\
300{head_extra}{json_ld_tag}</head><body>{body}</body></html>",
301        t = escape_attr(title),
302        d = escape_attr(description)
303    )
304}
305
306/// `llms.txt` (GEO floor): the site heading plus one curated link per
307/// page with its description.
308#[must_use]
309pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
310    let mut out = format!("# {}\n\n", config.site_title);
311    if !config.author.is_empty() {
312        out.push_str(&format!("By {}.\n\n", config.author));
313    }
314    for page in pages {
315        out.push_str(&format!(
316            "- [{t}]({u}/{r}): {d}\n",
317            t = page.title,
318            u = config.base_url,
319            r = page.route,
320            d = page.description
321        ));
322    }
323    out
324}
325
326/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
327/// when the page declares a date (deterministic builds do not lie about
328/// modification times).
329#[must_use]
330pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
331    let mut out = String::from(
332        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
333    );
334    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
335    sorted.sort_by(|a, b| a.route.cmp(&b.route));
336    for page in sorted {
337        let lastmod = page
338            .date
339            .as_ref()
340            .map(|d| format!("<lastmod>{d}</lastmod>"))
341            .unwrap_or_default();
342        out.push_str(&format!(
343            "<url><loc>{}/{}</loc>{lastmod}</url>\n",
344            config.base_url, page.route
345        ));
346    }
347    out.push_str("</urlset>\n");
348    out
349}
350
351/// `robots.txt` with the AI-crawler policy as a recorded decision.
352#[must_use]
353pub fn robots_txt(config: &SiteConfig) -> String {
354    let policy = config.ai_crawlers.as_str();
355    let mut out =
356        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
357    match policy {
358        "block-all" => {
359            out.push_str("User-agent: *\nDisallow: /\n");
360        }
361        "block-training" => {
362            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
363                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
364            }
365            out.push_str("User-agent: *\nAllow: /\n");
366        }
367        _ => {
368            out.push_str("User-agent: *\nAllow: /\n");
369        }
370    }
371    out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
372    out
373}