1use std::path::Path;
16
17use crate::directives::html_escape;
18
19#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22 pub route: String,
24 pub title: String,
26 pub description: String,
28 pub date: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35 pub base_url: String,
38 pub site_title: String,
40 pub author: String,
42 pub ai_crawlers: String,
45}
46
47impl SiteConfig {
48 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#[derive(Debug, Clone, Default, PartialEq)]
86pub struct PageMeta {
87 pub title: Option<String>,
89 pub description: Option<String>,
91 pub slug: Option<String>,
93 pub date: Option<String>,
95}
96
97#[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 let after = &rest[close + 4..];
125 (meta, after.trim_start_matches('\n').to_string())
126}
127
128#[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#[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
178fn escape_attr(text: &str) -> String {
181 html_escape(text).replace('"', """)
182}
183
184#[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#[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#[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#[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}