1mod 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
44pub const CONTENT_DIR: &str = "content";
46
47pub 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
72pub 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
88pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "camelCase")]
96pub struct ProjectIssue {
97 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub item: Option<ContentId>,
100 pub message: String,
102}
103
104#[derive(Debug, Clone)]
121pub struct SiteProject {
122 pub config: SiteConfig,
124 pub items: Vec<ContentItem>,
126 pub media: BTreeMap<String, Bytes>,
128 pub root: Option<PathBuf>,
130 pub theme: Theme,
132 pub public_terms: Option<PublicTerms>,
134 pub capabilities: Vec<CapabilityV2>,
136 pub as_of: DateTime<Utc>,
138 pub release_seq: u64,
140 pub redirects_format: RedirectsFormat,
142 pub preview: bool,
144 pub documents: BTreeMap<String, Bytes>,
148}
149
150impl SiteProject {
151 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 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 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 pub fn item(&self, id: &ContentId) -> Option<&ContentItem> {
228 self.items.iter().find(|item| &item.id == id)
229 }
230
231 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 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}