ocre/seo.rs
1//! Search engines and language models: JSON-LD, sitemaps and `llms.txt`.
2//!
3//! - [`json_ld`]: structured data (`Organization`, `FAQPage`,
4//! `BreadcrumbList`...) as a `<script type="application/ld+json">`,
5//! escaped so the JSON can never close the script element.
6//! - [`Sitemap`]: `/sitemap.xml`, with the other languages of each page
7//! (`xhtml:link rel="alternate" hreflang`) and `lastmod`.
8//! - [`LlmsTxt`]: `/llms.txt`, the Markdown index of a site for language
9//! models (<https://llmstxt.org>).
10//!
11//! The canonical and `hreflang` links of a page come from the visitor's
12//! locale: [`I18n::alternate_links`](crate::i18n::I18n::alternate_links).
13//! `ocre g seo` writes `src/seo.rs` with the routes and a list of pages.
14//!
15//! One address per page: [`redirect_www`] sends `www.` + the host of
16//! `APP_URL` to `APP_URL` with a `301`. [IndexNow](https://www.indexnow.org)
17//! tells Bing, Yandex and others that pages changed without waiting for a
18//! crawl: [`indexnow_routes`] serves the key file, [`submit_to_indexnow`]
19//! sends the URLs.
20
21use std::fmt::Write as _;
22
23use axum::{
24 http::header,
25 response::{IntoResponse, Response},
26};
27use serde::Serialize;
28use serde_json::{Value, json};
29
30pub use crate::runtime::seo::{indexnow_routes, redirect_www, submit_to_indexnow};
31
32/// Worker variable holding the IndexNow key: 8 to 128 letters, digits or `-` (`ocre secret` prints one).
33///
34/// Not a secret: search engines check it by fetching [`INDEXNOW_KEY_PATH`].
35///
36/// # Examples
37///
38/// ```
39/// assert_eq!(ocre::seo::INDEXNOW_KEY, "INDEXNOW_KEY");
40/// ```
41pub const INDEXNOW_KEY: &str = "INDEXNOW_KEY";
42
43/// Where [`indexnow_routes`] serves the key: `/indexnow.txt` (the submission names it as `keyLocation`).
44pub const INDEXNOW_KEY_PATH: &str = "/indexnow.txt";
45
46/// The endpoint IndexNow submissions go to; participating engines share them.
47pub const INDEXNOW_ENDPOINT: &str = "https://api.indexnow.org/indexnow";
48
49/// `base` + `path_and_query` when `host` is `www.` + `base`'s host; `None` otherwise.
50pub(crate) fn www_target(base: &str, host: Option<&str>, path_and_query: &str) -> Option<String> {
51 let base = base.trim().trim_end_matches('/');
52 let (_, app_host) = base.split_once("://")?;
53 let host = host?.to_ascii_lowercase();
54 (host.strip_prefix("www.")? == app_host.to_ascii_lowercase()).then(|| format!("{base}{path_and_query}"))
55}
56
57/// Whether `key` is a valid IndexNow key.
58pub(crate) fn valid_indexnow_key(key: &str) -> bool {
59 (8..=128).contains(&key.len()) && key.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
60}
61
62/// The JSON body of an IndexNow submission of `urls` for the site at `base`.
63pub(crate) fn indexnow_body(base: &str, key: &str, urls: &[String]) -> Option<Value> {
64 let base = base.trim().trim_end_matches('/');
65 let host = base.split_once("://")?.1;
66 Some(json!({"host": host, "key": key, "keyLocation": format!("{base}{INDEXNOW_KEY_PATH}"), "urlList": urls}))
67}
68
69/// `data` as a JSON-LD `<script>` for a page's `<head>`.
70///
71/// The JSON is escaped for HTML: `<`, `>` and `&` become `\u003c`,
72/// `\u003e` and `\u0026` (as do U+2028 and U+2029), so a value containing
73/// `</script>` cannot end the element, and the JSON parses to the same
74/// data. In askama: `{{ ocre::seo::json_ld(&data)|safe }}`.
75///
76/// # Examples
77///
78/// ```
79/// use serde_json::json;
80///
81/// let html = ocre::seo::json_ld(&json!({
82/// "@context": "https://schema.org",
83/// "@type": "Organization",
84/// "name": "PureFrame </script><b>",
85/// }));
86/// assert!(html.starts_with("<script type=\"application/ld+json\">{"));
87/// assert!(html.contains("PureFrame \\u003c/script\\u003e\\u003cb\\u003e"));
88/// assert_eq!(html.matches("</script>").count(), 1);
89/// ```
90pub fn json_ld(data: &impl Serialize) -> String {
91 let json = serde_json::to_string(data).unwrap_or_else(|_| "null".to_owned());
92 let mut out = String::with_capacity(json.len() + 48);
93 out.push_str("<script type=\"application/ld+json\">");
94 for c in json.chars() {
95 match c {
96 '<' => out.push_str("\\u003c"),
97 '>' => out.push_str("\\u003e"),
98 '&' => out.push_str("\\u0026"),
99 '\u{2028}' => out.push_str("\\u2028"),
100 '\u{2029}' => out.push_str("\\u2029"),
101 c => out.push(c),
102 }
103 }
104 out.push_str("</script>");
105 out
106}
107
108/// A page of a [`Sitemap`]: its absolute URL, last change and other languages.
109#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct SitemapUrl {
111 /// Absolute URL (`https://example.com/fr/pricing`).
112 pub loc: String,
113 /// Last change, `YYYY-MM-DD` or a full W3C date-time; omitted when `None`.
114 pub lastmod: Option<String>,
115 /// The page in each language, the page itself included: `(hreflang, absolute URL)`,
116 /// plus `("x-default", url)` for the language-picking version.
117 pub alternates: Vec<(String, String)>,
118}
119
120/// `/sitemap.xml`: the pages search engines should crawl.
121///
122/// Answer it from a route (it is a response: `application/xml`). One
123/// sitemap holds at most 50,000 URLs (and 50 MB); split larger sites.
124///
125/// # Examples
126///
127/// ```
128/// use ocre::seo::{Sitemap, SitemapUrl};
129///
130/// let mut sitemap = Sitemap::new();
131/// sitemap.add(SitemapUrl {
132/// loc: "https://example.com/en/pricing".into(),
133/// lastmod: Some("2026-10-01".into()),
134/// alternates: vec![
135/// ("en".into(), "https://example.com/en/pricing".into()),
136/// ("fr".into(), "https://example.com/fr/pricing".into()),
137/// ],
138/// });
139/// let xml = sitemap.to_xml();
140/// assert!(xml.contains("<url><loc>https://example.com/en/pricing</loc><lastmod>2026-10-01</lastmod>"));
141/// assert!(xml.contains("<xhtml:link rel=\"alternate\" hreflang=\"fr\" href=\"https://example.com/fr/pricing\"/>"));
142/// ```
143#[derive(Debug, Clone, Default, PartialEq, Eq)]
144pub struct Sitemap {
145 urls: Vec<SitemapUrl>,
146}
147
148impl Sitemap {
149 /// Most URLs in one sitemap file.
150 pub const MAX_URLS: usize = 50_000;
151
152 /// An empty sitemap.
153 pub fn new() -> Self {
154 Self::default()
155 }
156
157 /// Adds a page.
158 pub fn add(&mut self, url: SitemapUrl) -> &mut Self {
159 self.urls.push(url);
160 self
161 }
162
163 /// Adds a page in every language: `urls` is `(hreflang, absolute URL)`
164 /// for each locale, the first being the default (also `x-default`).
165 /// Each version is listed, with all the others as alternates, as
166 /// search engines expect.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// let mut sitemap = ocre::seo::Sitemap::new();
172 /// sitemap.add_localized(&[("en", "https://ex.com/en"), ("fr", "https://ex.com/fr")], None);
173 /// let xml = sitemap.to_xml();
174 /// assert_eq!(xml.matches("<url>").count(), 2);
175 /// assert_eq!(xml.matches("hreflang=\"x-default\" href=\"https://ex.com/en\"").count(), 2);
176 /// ```
177 pub fn add_localized(&mut self, urls: &[(&str, &str)], lastmod: Option<&str>) -> &mut Self {
178 let mut alternates: Vec<(String, String)> =
179 urls.iter().map(|(lang, url)| ((*lang).to_owned(), (*url).to_owned())).collect();
180 if let Some((_, default)) = urls.first() {
181 alternates.push(("x-default".to_owned(), (*default).to_owned()));
182 }
183 for (_, url) in urls {
184 self.urls.push(SitemapUrl {
185 loc: (*url).to_owned(),
186 lastmod: lastmod.map(str::to_owned),
187 alternates: alternates.clone(),
188 });
189 }
190 self
191 }
192
193 /// The URLs added so far.
194 pub fn len(&self) -> usize {
195 self.urls.len()
196 }
197
198 /// Whether no URL was added.
199 pub fn is_empty(&self) -> bool {
200 self.urls.is_empty()
201 }
202
203 /// The sitemap document (UTF-8 XML, values escaped).
204 pub fn to_xml(&self) -> String {
205 let mut xml = String::from(
206 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" \
207 xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n",
208 );
209 for url in &self.urls {
210 write!(xml, "<url><loc>{}</loc>", escape_xml(&url.loc)).expect("writing to a String");
211 if let Some(lastmod) = &url.lastmod {
212 write!(xml, "<lastmod>{}</lastmod>", escape_xml(lastmod)).expect("writing to a String");
213 }
214 for (lang, href) in &url.alternates {
215 write!(
216 xml,
217 "<xhtml:link rel=\"alternate\" hreflang=\"{}\" href=\"{}\"/>",
218 escape_xml(lang),
219 escape_xml(href)
220 )
221 .expect("writing to a String");
222 }
223 xml.push_str("</url>\n");
224 }
225 xml.push_str("</urlset>\n");
226 xml
227 }
228}
229
230impl IntoResponse for Sitemap {
231 fn into_response(self) -> Response {
232 ([(header::CONTENT_TYPE, "application/xml; charset=utf-8")], self.to_xml()).into_response()
233 }
234}
235
236/// `/llms.txt`: a site's summary and links in Markdown, for language models (<https://llmstxt.org>).
237///
238/// # Examples
239///
240/// ```
241/// use ocre::seo::LlmsTxt;
242///
243/// let txt = LlmsTxt::new("PureFrame", "AI video upscaling, paid per minute.")
244/// .details("Upload a video, get a free preview, then pay to download the full MP4.")
245/// .link("Pages", "Pricing", "https://pureframe.example/pricing", "per-minute prices")
246/// .link("Pages", "FAQ", "https://pureframe.example/faq", "")
247/// .to_string();
248/// assert!(txt.starts_with("# PureFrame\n\n> AI video upscaling, paid per minute.\n\nUpload a video,"));
249/// let pages = "\n## Pages\n\n- [Pricing](https://pureframe.example/pricing): per-minute prices\n- [FAQ](https://pureframe.example/faq)\n";
250/// assert!(txt.ends_with(pages));
251/// ```
252#[derive(Debug, Clone, Default, PartialEq, Eq)]
253pub struct LlmsTxt {
254 title: String,
255 summary: String,
256 details: String,
257 sections: Vec<(String, Vec<String>)>,
258}
259
260impl LlmsTxt {
261 /// The site's name (`# title`) and one-line summary (`> summary`).
262 pub fn new(title: impl Into<String>, summary: impl Into<String>) -> Self {
263 Self { title: title.into(), summary: summary.into(), ..Self::default() }
264 }
265
266 /// Free text after the summary.
267 #[must_use]
268 pub fn details(mut self, text: impl Into<String>) -> Self {
269 self.details = text.into();
270 self
271 }
272
273 /// A link in the `section` list (sections keep the order they first appear in).
274 #[must_use]
275 pub fn link(mut self, section: &str, title: &str, url: &str, description: &str) -> Self {
276 let line = if description.is_empty() {
277 format!("- [{title}]({url})")
278 } else {
279 format!("- [{title}]({url}): {description}")
280 };
281 match self.sections.iter_mut().find(|(name, _)| name == section) {
282 Some((_, lines)) => lines.push(line),
283 None => self.sections.push((section.to_owned(), vec![line])),
284 }
285 self
286 }
287}
288
289impl std::fmt::Display for LlmsTxt {
290 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291 write!(f, "# {}\n\n> {}\n", self.title, self.summary)?;
292 if !self.details.is_empty() {
293 write!(f, "\n{}\n", self.details)?;
294 }
295 for (section, lines) in &self.sections {
296 write!(f, "\n## {section}\n\n{}\n", lines.join("\n"))?;
297 }
298 Ok(())
299 }
300}
301
302impl IntoResponse for LlmsTxt {
303 fn into_response(self) -> Response {
304 ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], self.to_string()).into_response()
305 }
306}
307
308fn escape_xml(text: &str) -> String {
309 let mut out = String::with_capacity(text.len());
310 for c in text.chars() {
311 match c {
312 '&' => out.push_str("&"),
313 '<' => out.push_str("<"),
314 '>' => out.push_str(">"),
315 '"' => out.push_str("""),
316 '\'' => out.push_str("'"),
317 c => out.push(c),
318 }
319 }
320 out
321}
322
323#[cfg(test)]
324#[path = "../tests/seo.rs"]
325mod tests;