Skip to main content

aster/engine/
route.rs

1use std::cmp::Ordering;
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt;
4use std::path::{Path, PathBuf};
5
6use anyhow::{Context, Result, bail, ensure};
7use typst::ecow::{EcoString, EcoVec, eco_format};
8use typst::foundations::{Label, Selector, Value};
9use typst::introspection::{Introspector, MetadataElem};
10use typst::syntax::VirtualPath;
11
12/// Parameter assignments for one generated page.
13pub type ParamSet = BTreeMap<EcoString, EcoString>;
14
15/// A validated, portable path in Aster's virtual output tree.
16#[derive(Clone, Debug, Eq, Hash, PartialEq)]
17pub struct RoutePath(VirtualPath);
18
19impl RoutePath {
20    /// Validate a relative output path and place it in the virtual output root.
21    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
22        use std::path::Component;
23
24        let path = path.as_ref();
25        ensure!(!path.as_os_str().is_empty(), "route path cannot be empty");
26
27        for component in path.components() {
28            match component {
29                Component::Normal(value) => {
30                    let value = value.to_str().context("route path is not valid UTF-8")?;
31                    ensure!(valid_segment(value), "non-portable route segment `{value}`");
32                }
33                Component::CurDir => bail!("route path cannot contain `.`"),
34                Component::ParentDir => bail!("route path cannot contain `..`"),
35                Component::RootDir | Component::Prefix(_) => {
36                    bail!("route path must be relative")
37                }
38            }
39        }
40
41        let path = VirtualPath::virtualize(Path::new(""), path)
42            .context("route path is not a valid virtual path")?;
43        ensure!(!path.is_root(), "route path cannot be empty");
44        Ok(Self(path))
45    }
46
47    /// Return the normalized path within the virtual output root.
48    pub fn as_virtual_path(&self) -> &VirtualPath {
49        &self.0
50    }
51
52    /// Return the exact output route as a root-relative browser URL.
53    pub fn url_path(&self) -> EcoString {
54        eco_format!("/{}", self.0.get_without_slash())
55    }
56
57    /// Return the preferred browser URL for a generated HTML page.
58    pub fn page_url_path(&self) -> EcoString {
59        let path = self.0.get_without_slash();
60        if path == "index.html" {
61            return "/".into();
62        }
63        if let Some(directory) = path.strip_suffix("/index.html") {
64            return eco_format!("/{directory}/");
65        }
66        self.url_path()
67    }
68
69    /// Whether two output paths cannot coexist on a portable filesystem.
70    pub fn conflicts_with(&self, other: &Self) -> bool {
71        let mut left = self
72            .as_virtual_path()
73            .get_without_slash()
74            .split('/')
75            .map(str::to_lowercase);
76        let mut right = other
77            .as_virtual_path()
78            .get_without_slash()
79            .split('/')
80            .map(str::to_lowercase);
81
82        loop {
83            match (left.next(), right.next()) {
84                (Some(left), Some(right)) if left == right => {}
85                (Some(_), Some(_)) => return false,
86                _ => return true,
87            }
88        }
89    }
90}
91
92impl Ord for RoutePath {
93    fn cmp(&self, other: &Self) -> Ordering {
94        self.0.get_with_slash().cmp(other.0.get_with_slash())
95    }
96}
97
98impl PartialOrd for RoutePath {
99    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
100        Some(self.cmp(other))
101    }
102}
103
104impl fmt::Display for RoutePath {
105    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
106        formatter.write_str(self.0.get_without_slash())
107    }
108}
109
110#[derive(Debug, Clone, PartialEq)]
111enum Part {
112    Static(EcoString),
113    Param(EcoString),
114    Spread(EcoString),
115}
116
117/// A pre-parsed and validated route template.
118#[derive(Debug, Clone)]
119pub struct RouteTemplate {
120    segments: Vec<Vec<Part>>,
121    parameters: BTreeSet<EcoString>,
122}
123
124#[derive(Debug, thiserror::Error)]
125pub enum RouteError {
126    #[error("unbalanced brackets in route path")]
127    UnbalancedBrackets,
128    #[error("empty brackets `[]` in route path")]
129    EmptyBrackets,
130    #[error("consecutive brackets `][` in route path")]
131    ConsecutiveBrackets,
132    #[error("spread parameter in segment {0} must be a standalone segment")]
133    SpreadNotStandalone(usize),
134    #[error("duplicate route parameter `{0}`")]
135    DuplicateParameter(EcoString),
136}
137
138pub fn parse_template(path: &Path) -> Result<RouteTemplate, RouteError> {
139    use std::path::Component;
140
141    let normal: Vec<_> = path
142        .components()
143        .filter_map(|component| match component {
144            Component::Normal(value) => Some(value),
145            _ => None,
146        })
147        .collect();
148    let mut segments = Vec::with_capacity(normal.len());
149    let mut parameters = BTreeSet::new();
150
151    for (index, os) in normal.iter().enumerate() {
152        let text = if index + 1 == normal.len() {
153            Path::new(os).file_stem().unwrap_or(os).to_string_lossy()
154        } else {
155            os.to_string_lossy()
156        };
157        let parts = parse_component(&text)?;
158        if parts.is_empty() {
159            continue;
160        }
161
162        for (part_index, part) in parts.iter().enumerate() {
163            if matches!(part, Part::Spread(_)) && parts.len() > 1 {
164                return Err(RouteError::SpreadNotStandalone(segments.len()));
165            }
166            if part_index > 0
167                && matches!(part, Part::Param(_))
168                && matches!(parts[part_index - 1], Part::Param(_))
169            {
170                return Err(RouteError::ConsecutiveBrackets);
171            }
172            if let Part::Param(name) | Part::Spread(name) = part
173                && !parameters.insert(name.clone())
174            {
175                return Err(RouteError::DuplicateParameter(name.clone()));
176            }
177        }
178        segments.push(parts);
179    }
180
181    Ok(RouteTemplate {
182        segments,
183        parameters,
184    })
185}
186
187fn parse_component(text: &str) -> Result<Vec<Part>, RouteError> {
188    let mut parts = Vec::new();
189    let mut pos = 0;
190
191    while pos < text.len() {
192        if text[pos..].starts_with('[') {
193            let open_at = pos;
194            pos += 1;
195            let close_at = text[pos..]
196                .find(']')
197                .map(|index| pos + index)
198                .ok_or(RouteError::UnbalancedBrackets)?;
199            let inner = &text[open_at + 1..close_at];
200            if inner.is_empty() {
201                return Err(RouteError::EmptyBrackets);
202            }
203            if let Some(name) = inner.strip_prefix("...") {
204                if name.is_empty() {
205                    return Err(RouteError::EmptyBrackets);
206                }
207                parts.push(Part::Spread(name.into()));
208            } else {
209                parts.push(Part::Param(inner.into()));
210            }
211            pos = close_at + 1;
212        } else {
213            let start = pos;
214            pos = text[pos..]
215                .find('[')
216                .map(|index| pos + index)
217                .unwrap_or(text.len());
218            parts.push(Part::Static(text[start..pos].into()));
219        }
220    }
221    Ok(parts)
222}
223
224impl RouteTemplate {
225    pub fn is_dynamic(&self) -> bool {
226        !self.parameters.is_empty()
227    }
228
229    pub fn generate(&self, params: &ParamSet) -> Result<RoutePath> {
230        let mut output = self.generate_path(params)?;
231        output.as_mut_os_string().push(".html");
232        RoutePath::new(output)
233    }
234
235    /// Generate an exact output path without appending a page extension.
236    pub fn generate_file(&self, params: &ParamSet) -> Result<RoutePath> {
237        RoutePath::new(self.generate_path(params)?)
238    }
239
240    fn generate_path(&self, params: &ParamSet) -> Result<PathBuf> {
241        let supplied: BTreeSet<_> = params.keys().cloned().collect();
242        let missing: Vec<_> = self.parameters.difference(&supplied).cloned().collect();
243        let extra: Vec<_> = supplied.difference(&self.parameters).cloned().collect();
244        ensure!(
245            missing.is_empty(),
246            "missing route parameter(s): {}",
247            join_names(&missing)
248        );
249        ensure!(
250            extra.is_empty(),
251            "unexpected route parameter(s): {}",
252            join_names(&extra)
253        );
254
255        let mut output = PathBuf::new();
256        for segment in &self.segments {
257            if let [Part::Spread(name)] = segment.as_slice() {
258                let value = params.get(name).expect("validated parameter exists");
259                ensure!(
260                    !value.is_empty(),
261                    "spread parameter `{name}` cannot be empty"
262                );
263                let pieces = value.split('/').collect::<Vec<_>>();
264                for piece in pieces {
265                    ensure!(valid_segment(piece), "invalid route segment `{piece}`");
266                    output.push(piece);
267                }
268                continue;
269            }
270
271            let mut text = String::new();
272            for part in segment {
273                match part {
274                    Part::Static(value) => text.push_str(value),
275                    Part::Param(name) => {
276                        let value = params.get(name).expect("validated parameter exists");
277                        ensure!(
278                            valid_segment(value),
279                            "invalid value for route parameter `{name}`"
280                        );
281                        text.push_str(value);
282                    }
283                    Part::Spread(_) => unreachable!("spread is validated as standalone"),
284                }
285            }
286            ensure!(valid_segment(&text), "invalid route segment `{text}`");
287            output.push(text);
288        }
289        Ok(output)
290    }
291}
292
293fn valid_segment(value: &str) -> bool {
294    const WINDOWS_DEVICES: &[&str] = &[
295        "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
296        "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
297    ];
298    let stem = value.split('.').next().unwrap_or(value);
299    !value.is_empty()
300        && value != "."
301        && value != ".."
302        && !value.ends_with(['.', ' '])
303        && !value.chars().any(|character| {
304            character.is_control()
305                || matches!(
306                    character,
307                    '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' | '#' | '%'
308                )
309        })
310        && !WINDOWS_DEVICES
311            .iter()
312            .any(|device| stem.eq_ignore_ascii_case(device))
313}
314
315fn join_names(names: &[EcoString]) -> String {
316    names
317        .iter()
318        .map(EcoString::as_str)
319        .collect::<Vec<_>>()
320        .join(", ")
321}
322
323/// Extract parameter assignments declared through `<aster-route>` metadata.
324pub fn extract_params(introspector: &dyn Introspector) -> Result<EcoVec<ParamSet>> {
325    let selector =
326        Selector::Label(Label::construct("aster-route".into()).expect("route label is non-empty"));
327    let mut result = EcoVec::new();
328    for element in introspector.query(&selector) {
329        let Some(metadata) = element.to_packed::<MetadataElem>() else {
330            continue;
331        };
332        let declaration = metadata.value.clone();
333        let Value::Array(items) = declaration else {
334            bail!("route metadata must be an array of dictionaries");
335        };
336        for item in items {
337            let Value::Dict(dict) = item else {
338                bail!("route metadata must be an array of dictionaries");
339            };
340            if dict.is_empty() {
341                bail!("route metadata must not contain an empty parameter set");
342            }
343            let mut params = ParamSet::new();
344            for (name, value) in dict.iter() {
345                let Value::Str(value) = value else {
346                    bail!("route parameter `{}` must be a string", name.as_str());
347                };
348                params.insert(name.as_str().into(), value.as_str().into());
349            }
350            result.push(params);
351        }
352    }
353    Ok(result)
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    fn parse(path: &str) -> Result<RouteTemplate, RouteError> {
361        parse_template(Path::new(path))
362    }
363
364    #[test]
365    fn parses_static_and_dynamic_parts() {
366        let route = parse("blog/prefix[slug].typ").unwrap();
367        assert!(route.is_dynamic());
368        assert_eq!(route.parameters, BTreeSet::from(["slug".into()]));
369    }
370
371    #[test]
372    fn rejects_malformed_and_duplicate_parameters() {
373        assert!(matches!(
374            parse("[slug.typ"),
375            Err(RouteError::UnbalancedBrackets)
376        ));
377        assert!(matches!(parse("[].typ"), Err(RouteError::EmptyBrackets)));
378        assert!(matches!(
379            parse("[a][b].typ"),
380            Err(RouteError::ConsecutiveBrackets)
381        ));
382        assert!(matches!(
383            parse("prefix[...slug].typ"),
384            Err(RouteError::SpreadNotStandalone(0))
385        ));
386        assert!(matches!(
387            parse("[slug]/[slug].typ"),
388            Err(RouteError::DuplicateParameter(_))
389        ));
390    }
391
392    #[test]
393    fn generates_validated_dynamic_output() {
394        let route = parse("blog/[slug].typ").unwrap();
395        let params = ParamSet::from([("slug".into(), "hello".into())]);
396        assert_eq!(
397            route
398                .generate(&params)
399                .unwrap()
400                .as_virtual_path()
401                .get_with_slash(),
402            "/blog/hello.html"
403        );
404        assert!(route.generate(&ParamSet::new()).is_err());
405        assert!(
406            route
407                .generate(&ParamSet::from([("slug".into(), "../escape".into())]))
408                .is_err()
409        );
410        assert!(
411            route
412                .generate(&ParamSet::from([
413                    ("slug".into(), "hello".into()),
414                    ("other".into(), "value".into()),
415                ]))
416                .is_err()
417        );
418    }
419
420    #[test]
421    fn only_spread_parameters_create_segments() {
422        let spread = parse("docs/[...path].typ").unwrap();
423        assert_eq!(
424            spread
425                .generate(&ParamSet::from([("path".into(), "a/b".into())]))
426                .unwrap()
427                .as_virtual_path()
428                .get_with_slash(),
429            "/docs/a/b.html"
430        );
431        let plain = parse("docs/[path].typ").unwrap();
432        assert!(
433            plain
434                .generate(&ParamSet::from([("path".into(), "a/b".into())]))
435                .is_err()
436        );
437    }
438
439    #[test]
440    fn preserves_dots_and_rejects_nonportable_segments() {
441        let route = parse("[slug].typ").unwrap();
442        assert_eq!(
443            route
444                .generate(&ParamSet::from([("slug".into(), "v1.2".into())]))
445                .unwrap()
446                .as_virtual_path()
447                .get_with_slash(),
448            "/v1.2.html"
449        );
450        for invalid in ["CON", "bad?name", "fragment#name", "trail."] {
451            assert!(
452                route
453                    .generate(&ParamSet::from([("slug".into(), invalid.into())]))
454                    .is_err(),
455                "{invalid} must be rejected"
456            );
457        }
458    }
459
460    #[test]
461    fn template_paths_determine_page_outputs() {
462        assert_eq!(
463            parse("index.typ")
464                .unwrap()
465                .generate(&ParamSet::new())
466                .unwrap()
467                .as_virtual_path()
468                .get_with_slash(),
469            "/index.html"
470        );
471        assert_eq!(
472            parse("about.typ")
473                .unwrap()
474                .generate(&ParamSet::new())
475                .unwrap()
476                .as_virtual_path()
477                .get_with_slash(),
478            "/about.html"
479        );
480
481        let route = parse("blog/[slug]/index.typ").unwrap();
482        assert_eq!(
483            route
484                .generate(&ParamSet::from([("slug".into(), "hello".into())]))
485                .unwrap()
486                .as_virtual_path()
487                .get_with_slash(),
488            "/blog/hello/index.html"
489        );
490
491        let route = parse("[slug].typ").unwrap();
492        assert_eq!(
493            route
494                .generate(&ParamSet::from([("slug".into(), "index".into())]))
495                .unwrap()
496                .as_virtual_path()
497                .get_with_slash(),
498            "/index.html"
499        );
500
501        assert_eq!(
502            parse("feed/[slug].xml.typ")
503                .unwrap()
504                .generate_file(&ParamSet::from([("slug".into(), "latest".into())]))
505                .unwrap()
506                .as_virtual_path()
507                .get_with_slash(),
508            "/feed/latest.xml"
509        );
510    }
511
512    #[test]
513    fn output_routes_determine_browser_url_paths() {
514        assert_eq!(RoutePath::new("index.html").unwrap().page_url_path(), "/");
515        assert_eq!(
516            RoutePath::new("blog/post/index.html")
517                .unwrap()
518                .page_url_path(),
519            "/blog/post/"
520        );
521        assert_eq!(
522            RoutePath::new("about.html").unwrap().page_url_path(),
523            "/about.html"
524        );
525        assert_eq!(
526            RoutePath::new("feed/index.html").unwrap().url_path(),
527            "/feed/index.html"
528        );
529    }
530
531    #[test]
532    fn detects_portable_and_ancestor_output_collisions() {
533        let route = |path| RoutePath::new(path).unwrap();
534
535        assert!(route("Case/index.html").conflicts_with(&route("case/index.html")));
536        assert!(route("foo/index.html").conflicts_with(&route("foo/index.html/bar/index.html")));
537        assert!(!route("foo/index.html").conflicts_with(&route("foobar/index.html")));
538    }
539
540    #[test]
541    fn route_path_establishes_portable_virtual_path_invariant() {
542        let path = RoutePath::new("docs/index.html").unwrap();
543        assert_eq!(path.as_virtual_path().get_with_slash(), "/docs/index.html");
544
545        for invalid in [
546            "",
547            ".",
548            "../index.html",
549            "docs/../index.html",
550            "/index.html",
551            "bad:name.html",
552            "CON.html",
553        ] {
554            assert!(
555                RoutePath::new(invalid).is_err(),
556                "{invalid} must be rejected"
557            );
558        }
559    }
560}