Skip to main content

adk_site/content/
mod.rs

1//! The content model and repository (spec 3.5 §7.8.2 "Content model").
2//!
3//! Content lives as files in the site's content repository:
4//!
5//! | Path | Holds |
6//! |------|-------|
7//! | `site.toml` | [`SiteConfig`] |
8//! | `content/<kind>/<slug>/<language>.md` | One [`ContentItem`] per language: front matter, then a Markdown body |
9//! | `content/<kind>/<slug>/*` | The item's media, beside it |
10//! | `public-terms.json` | The charter's [`PublicTerms`], written by the charter store |
11//! | `capabilities.json` | The site's [`CapabilityV2`] declarations, for machine views |
12//! | `theme/` | An optional [`Theme`] directory |
13//!
14//! Kind directories are `pages`, `posts`, `articles`, `products`, `events`, `notices`,
15//! `services`, `people` and `collections`. Drafts on branches are the caller's git concern.
16
17mod config;
18mod frontmatter;
19mod history;
20mod store;
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::path::{Path, PathBuf};
24
25use awp_types::{CapabilityV2, ContentId, ContentItem, ContentKind, PublicTerms};
26use bytes::Bytes;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29
30use crate::error::{Result, SiteError};
31use crate::redirects::RedirectsFormat;
32use crate::theme::Theme;
33
34pub use config::{PerformanceBudget, SecurityContact, SiteConfig};
35pub use history::{
36    ContentHistory, FileContentHistory, HistoryEntry, HistoryMeta, InMemoryContentHistory,
37    content_history_conformance,
38};
39pub use store::{
40    ContentStore, FsContentStore, InMemoryContentStore, content_store_conformance,
41    parse_content_file,
42};
43
44/// The directory content items live under.
45pub const CONTENT_DIR: &str = "content";
46
47/// The repository directory of a content kind.
48///
49/// # Example
50///
51/// ```rust
52/// use adk_site::content::kind_directory;
53/// use awp_types::ContentKind;
54///
55/// assert_eq!(kind_directory(ContentKind::Person), "people");
56/// ```
57pub fn kind_directory(kind: ContentKind) -> &'static str {
58    match kind {
59        ContentKind::Page => "pages",
60        ContentKind::Post => "posts",
61        ContentKind::Article => "articles",
62        ContentKind::Product => "products",
63        ContentKind::Event => "events",
64        ContentKind::Notice => "notices",
65        ContentKind::Service => "services",
66        ContentKind::Person => "people",
67        ContentKind::Collection => "collections",
68        _ => "items",
69    }
70}
71
72/// The content kind of a repository directory.
73pub fn kind_from_directory(dir: &str) -> Option<ContentKind> {
74    Some(match dir {
75        "pages" => ContentKind::Page,
76        "posts" => ContentKind::Post,
77        "articles" => ContentKind::Article,
78        "products" => ContentKind::Product,
79        "events" => ContentKind::Event,
80        "notices" => ContentKind::Notice,
81        "services" => ContentKind::Service,
82        "people" => ContentKind::Person,
83        "collections" => ContentKind::Collection,
84        _ => return None,
85    })
86}
87
88/// The wire name of a content kind, such as `product`.
89pub fn kind_name(kind: ContentKind) -> String {
90    serde_json::to_value(kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
91}
92
93/// A problem with a project that stops a build.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub struct ProjectIssue {
97    /// The item, when the issue is an item's.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub item: Option<ContentId>,
100    /// What is wrong.
101    pub message: String,
102}
103
104/// Everything a generator needs to build a site: configuration, items, media, theme,
105/// public terms and capabilities, at a point in time (spec 3.5 §7.8).
106///
107/// Identical projects build identical files: `as_of` stands in for the clock, and nothing
108/// else in the build reads the time.
109///
110/// # Example
111///
112/// ```rust
113/// use adk_site::content::{SiteConfig, SiteProject};
114/// use chrono::{TimeZone, Utc};
115///
116/// let config = SiteConfig::new("Example", "example.com", vec!["en".parse().unwrap()]);
117/// let project = SiteProject::new(config, Vec::new(), Utc.with_ymd_and_hms(2026, 10, 25, 0, 0, 0).unwrap());
118/// assert!(project.issues().is_empty());
119/// ```
120#[derive(Debug, Clone)]
121pub struct SiteProject {
122    /// The site configuration.
123    pub config: SiteConfig,
124    /// Every item, sorted by id.
125    pub items: Vec<ContentItem>,
126    /// Media by repository path, for items not read from disk.
127    pub media: BTreeMap<String, Bytes>,
128    /// The repository root, where media not in `media` is read from.
129    pub root: Option<PathBuf>,
130    /// The theme.
131    pub theme: Theme,
132    /// The charter's public terms.
133    pub public_terms: Option<PublicTerms>,
134    /// The site's capabilities, listed in machine views.
135    pub capabilities: Vec<CapabilityV2>,
136    /// The build time: schedules are evaluated at it and `security.txt` expires a year after.
137    pub as_of: DateTime<Utc>,
138    /// The release the build is for, stamped on machine views.
139    pub release_seq: u64,
140    /// The redirect format of the host the release goes to.
141    pub redirects_format: RedirectsFormat,
142    /// Whether to render drafts, items in review and future schedules: a preview build.
143    pub preview: bool,
144    /// Documents other components add to the release by path, such as the signed contract
145    /// `.well-known/awp.json`, `.well-known/awp/keys.json` and an A2A Agent Card (AWP 2.0
146    /// §14.2). Pages link the contract with `<link rel="awp">` when it is here.
147    pub documents: BTreeMap<String, Bytes>,
148}
149
150impl SiteProject {
151    /// A project from parts, with the default theme.
152    pub fn new(config: SiteConfig, mut items: Vec<ContentItem>, as_of: DateTime<Utc>) -> Self {
153        items.sort_by(|a, b| a.id.cmp(&b.id));
154        Self {
155            config,
156            items,
157            media: BTreeMap::new(),
158            root: None,
159            theme: Theme::default(),
160            public_terms: None,
161            capabilities: Vec::new(),
162            as_of,
163            release_seq: 1,
164            redirects_format: RedirectsFormat::default(),
165            preview: false,
166            documents: BTreeMap::new(),
167        }
168    }
169
170    /// Loads a content repository from disk.
171    ///
172    /// # Errors
173    ///
174    /// [`SiteError::InvalidConfig`] for a missing or invalid `site.toml`; content, theme
175    /// and JSON errors for the other files.
176    pub async fn load(root: &Path, as_of: DateTime<Utc>) -> Result<Self> {
177        let config_path = root.join("site.toml");
178        let text = tokio::fs::read_to_string(&config_path)
179            .await
180            .map_err(|e| SiteError::io(&config_path, e))?;
181        let config = SiteConfig::from_toml(&text)?;
182        let items = FsContentStore::new(root).list().await?;
183        let mut project = Self::new(config, items, as_of);
184        project.root = Some(root.to_path_buf());
185        let root_owned = root.to_path_buf();
186        let theme_dir = root.join("theme");
187        if theme_dir.is_dir() {
188            project.theme = tokio::task::spawn_blocking(move || Theme::load(&theme_dir))
189                .await
190                .map_err(|e| SiteError::Pipeline(e.to_string()))??;
191        }
192        project.public_terms = read_json(&root_owned.join("public-terms.json")).await?;
193        project.capabilities =
194            read_json(&root_owned.join("capabilities.json")).await?.unwrap_or_default();
195        Ok(project)
196    }
197
198    /// Builds a project from a store, reading every item's media into memory.
199    ///
200    /// # Errors
201    ///
202    /// Store errors; [`SiteError::InvalidContent`] when an item's media is missing.
203    pub async fn from_store(
204        config: SiteConfig,
205        store: &dyn ContentStore,
206        as_of: DateTime<Utc>,
207    ) -> Result<Self> {
208        let items = store.list().await?;
209        let mut media = BTreeMap::new();
210        for item in &items {
211            for reference in &item.media {
212                let bytes = store.read_media(&reference.path).await?.ok_or_else(|| {
213                    SiteError::InvalidContent {
214                        path: item.id.to_string(),
215                        message: format!("media '{}' is missing from the store", reference.path),
216                    }
217                })?;
218                media.insert(reference.path.clone(), bytes);
219            }
220        }
221        let mut project = Self::new(config, items, as_of);
222        project.media = media;
223        Ok(project)
224    }
225
226    /// The item with `id`.
227    pub fn item(&self, id: &ContentId) -> Option<&ContentItem> {
228        self.items.iter().find(|item| &item.id == id)
229    }
230
231    /// The bytes of a media file.
232    ///
233    /// # Errors
234    ///
235    /// [`SiteError::InvalidContent`] when the file is in neither `media` nor the repository.
236    pub fn media_bytes(&self, path: &str) -> Result<Bytes> {
237        if let Some(bytes) = self.media.get(path) {
238            return Ok(bytes.clone());
239        }
240        let missing = || SiteError::InvalidContent {
241            path: path.to_string(),
242            message: "media file is missing".into(),
243        };
244        let root = self.root.as_ref().ok_or_else(missing)?;
245        let full = root.join(store::safe_relative(path)?);
246        std::fs::read(&full).map(Bytes::from).map_err(|_| missing())
247    }
248
249    /// Structural problems that stop a build: unknown languages, duplicate ids, invalid
250    /// slugs, missing media, and claim fields an item serves live (spec 3.5 A-I26).
251    pub fn issues(&self) -> Vec<ProjectIssue> {
252        let mut issues = Vec::new();
253        if let Err(error) = self.config.validate() {
254            issues.push(ProjectIssue { item: None, message: error.to_string() });
255        }
256        let languages: BTreeSet<String> =
257            self.config.languages.iter().map(|l| l.as_str().to_ascii_lowercase()).collect();
258        let mut ids = BTreeSet::new();
259        for item in &self.items {
260            let mut issue = |message: String| {
261                issues.push(ProjectIssue { item: Some(item.id.clone()), message })
262            };
263            if !ids.insert(item.id.clone()) {
264                issue("the id is used by another item".into());
265            }
266            if !languages.contains(&item.language.as_str().to_ascii_lowercase()) {
267                issue(format!("language '{}' is not one of the site's languages", item.language));
268            }
269            let slug_ok = item.slug.split('/').all(|segment| {
270                !segment.is_empty()
271                    && segment != "."
272                    && segment != ".."
273                    && !segment.chars().any(|c| c.is_whitespace() || "?#%\\<>\"".contains(c))
274            });
275            if !slug_ok {
276                issue(format!("slug '{}' is not a valid URL path", item.slug));
277            }
278            if let Some(path) = item.fields.get("path") {
279                let valid = path
280                    .as_str()
281                    .is_some_and(|p| p.starts_with('/') && p.ends_with('/') && !p.contains(".."));
282                if !valid {
283                    issue("field 'path' must be a URL path that starts and ends with '/'".into());
284                }
285            }
286            for reference in &item.media {
287                if self.media_bytes(&reference.path).is_err() {
288                    issue(format!("media '{}' is missing", reference.path));
289                }
290            }
291            for violation in crate::lanes::item_violations(&self.config, item) {
292                issue(violation.to_string());
293            }
294        }
295        issues
296    }
297}
298
299async fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Option<T>> {
300    match tokio::fs::read(path).await {
301        Ok(bytes) => serde_json::from_slice(&bytes)
302            .map(Some)
303            .map_err(|e| SiteError::serde(path.display().to_string(), e)),
304        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
305        Err(e) => Err(SiteError::io(path, e)),
306    }
307}