Skip to main content

brrrty_js/
eleventy.rs

1//! Eleventy 3.1.8's own filters: `slug`, `slugify`, `url` and `log`.
2//!
3//! They are engine-neutral: each is a [`FilterImpl`], a plain function from
4//! the input, the positional arguments and a [`FilterEnv`] to a result. An
5//! engine adapts them into its own filter type. `url` uses a path prefix of
6//! `/`.
7//!
8//! Ported from `Filters/Slug.js`, `Filters/Slugify.js` and `Filters/Url.js`
9//! in `@11ty/eleventy`, and from the packages they call: `slugify` 1.6.9,
10//! `@sindresorhus/slugify` 2.2.1 and `@sindresorhus/transliterate`. Their
11//! data tables are in `eleventy_tables.rs`, which `tools/gen-eleventy.mjs`
12//! generates from those packages.
13
14use std::cell::Cell;
15use std::io::Write as _;
16use std::sync::Arc;
17
18use unicode_normalization::UnicodeNormalization;
19
20use crate::eleventy_tables::{DIACRITICS, SLUG_CHARMAP, TRANSLITERATE};
21use crate::{Tz, Value, is_js_whitespace, js_number_to_string};
22
23/// A filter's error that starts with this is a refusal: the filter can't do
24/// what was asked exactly, as opposed to the call failing as it would in
25/// JavaScript. Nunjucks reports it as unsupported.
26pub const REFUSAL_PREFIX: &str = "Brrrty ";
27
28/// A filter that does not depend on a template engine.
29pub type FilterImpl = fn(&Value, &[Value], &FilterEnv) -> Result<Value, String>;
30
31/// A filter that a template engine can call: the closure form of
32/// [`FilterImpl`], for filters that carry state, such as one written in a
33/// config script.
34pub type FilterFn =
35    Arc<dyn Fn(&Value, &[Value], &FilterEnv) -> Result<Value, String> + Send + Sync>;
36
37/// What an engine-neutral filter can see of the build and of the call.
38///
39/// Liquid builds one with [`FilterEnv::new`], which leaves everything past
40/// the time zone empty, so its filters behave as before. Nunjucks fills in
41/// the rest.
42#[derive(Debug, Clone)]
43#[non_exhaustive]
44pub struct FilterEnv {
45    /// The zone a `Date` input is printed in, as JavaScript's `String(date)`
46    /// prints it.
47    pub timezone: Tz,
48    /// The page's data, which a JavaScript filter reads as `this.page`.
49    pub page: Option<Value>,
50    /// The page's `eleventy` data.
51    pub eleventy: Option<Value>,
52    /// The keyword arguments of the call, in the order written. Nunjucks
53    /// also passes them as a last object argument, with `__keywords: true`,
54    /// which stays in the arguments a filter gets; this is the same data
55    /// taken apart. Liquid passes none here.
56    pub kwargs: Vec<(String, Value)>,
57    /// The input is a `SafeString` (from `safe`, `escape` or a macro). The
58    /// filter gets its text as a string, as `String(input)` would give it.
59    pub input_safe: bool,
60    /// Which of the arguments are `SafeString`s, by position.
61    pub args_safe: Vec<bool>,
62    returned_input: Cell<bool>,
63}
64
65impl FilterEnv {
66    pub fn new(timezone: Tz) -> Self {
67        FilterEnv {
68            timezone,
69            page: None,
70            eleventy: None,
71            kwargs: Vec::new(),
72            input_safe: false,
73            args_safe: Vec::new(),
74            returned_input: Cell::new(false),
75        }
76    }
77
78    /// Whether any of the input and the arguments is a `SafeString`.
79    pub fn any_safe(&self) -> bool {
80        self.input_safe || self.args_safe.iter().any(|s| *s)
81    }
82
83    /// A filter calls this when the value it returns is the input object
84    /// itself, as JavaScript's `return input` is. Nunjucks then keeps a
85    /// `SafeString` input safe. A filter that builds a new string, even an
86    /// equal one, must not call it.
87    pub fn returns_input(&self) {
88        self.returned_input.set(true);
89    }
90
91    /// Whether the filter called [`FilterEnv::returns_input`].
92    pub fn did_return_input(&self) -> bool {
93        self.returned_input.get()
94    }
95}
96
97/// Eleventy's filters, by name.
98pub fn eleventy_filters() -> Vec<(&'static str, FilterImpl)> {
99    vec![
100        ("slug", slug_filter),
101        ("slugify", slugify_filter),
102        ("url", url_filter),
103        ("log", log_filter),
104    ]
105}
106
107fn string(s: String) -> Value {
108    Value::String(Arc::from(s))
109}
110
111// ---- slug: slugify 1.6.9 with `{ replacement: "-", lower: true }` ----
112
113fn slug_filter(input: &Value, _args: &[Value], env: &FilterEnv) -> Result<Value, String> {
114    Ok(string(slug(&input.to_js_string_in(env.timezone))))
115}
116
117/// Characters slugify keeps: `[\w\s$*_+~.()'"!\-:@]`.
118fn slug_allowed(c: char) -> bool {
119    c.is_ascii_alphanumeric()
120        || is_js_whitespace(c)
121        || matches!(
122            c,
123            '_' | '$' | '*' | '+' | '~' | '.' | '(' | ')' | '\'' | '"' | '!' | '-' | ':' | '@'
124        )
125}
126
127fn slug(text: &str) -> String {
128    let mut out = String::new();
129    // JS splits into UTF-16 units; a character above the BMP is two lone
130    // surrogates, neither in the map, and both removed. So it is dropped.
131    for c in text.nfc() {
132        if c as u32 > 0xFFFF {
133            continue;
134        }
135        let mapped = SLUG_CHARMAP
136            .binary_search_by_key(&c, |(k, _)| *k)
137            .map(|i| SLUG_CHARMAP[i].1);
138        let mut buf = [0u8; 4];
139        let piece = mapped.unwrap_or_else(|_| c.encode_utf8(&mut buf));
140        let piece = if piece == "-" { " " } else { piece };
141        out.extend(piece.chars().filter(|c| slug_allowed(*c)));
142    }
143    let trimmed = out.trim_matches(is_js_whitespace);
144    let mut slug = String::new();
145    let mut in_space = false;
146    for c in trimmed.chars() {
147        if is_js_whitespace(c) {
148            if !in_space {
149                slug.push('-');
150            }
151            in_space = true;
152        } else {
153            slug.push(c);
154            in_space = false;
155        }
156    }
157    slug.to_lowercase()
158}
159
160// ---- slugify: @sindresorhus/slugify 2.2.1 with `{ decamelize: false }` ----
161
162fn slugify_filter(input: &Value, _args: &[Value], env: &FilterEnv) -> Result<Value, String> {
163    Ok(string(slugify(&input.to_js_string_in(env.timezone))))
164}
165
166fn is_diacritic(c: char) -> bool {
167    let c = c as u32;
168    DIACRITICS
169        .binary_search_by(|&(lo, hi)| {
170            if c < lo {
171                std::cmp::Ordering::Greater
172            } else if c > hi {
173                std::cmp::Ordering::Less
174            } else {
175                std::cmp::Ordering::Equal
176            }
177        })
178        .is_ok()
179}
180
181fn transliterate(text: &str) -> String {
182    let mut s: String = text.nfc().collect();
183    for (key, value) in TRANSLITERATE {
184        if s.contains(key) {
185            s = s.replace(key, value);
186        }
187    }
188    s.nfd().filter(|c| !is_diacritic(*c)).nfc().collect()
189}
190
191/// `@sindresorhus/slugify` 2.2.1 with `{ decamelize: false }`: 11ty's `slugify` filter.
192pub fn slugify(text: &str) -> String {
193    let lowered = transliterate(text).to_lowercase();
194    let lowered = drop_contraction_apostrophes(&lowered);
195    // `[^a-z\d]+` becomes one separator, and a separator at either end goes.
196    let mut out = String::new();
197    let mut pending = false;
198    for c in lowered.chars() {
199        if c.is_ascii_lowercase() || c.is_ascii_digit() {
200            if pending && !out.is_empty() {
201                out.push('-');
202            }
203            pending = false;
204            out.push(c);
205        } else {
206            pending = true;
207        }
208    }
209    out
210}
211
212/// `s.replace(/([a-zA-Z\d]+)'([ts])(\s|$)/g, "$1$2$3")`.
213fn drop_contraction_apostrophes(s: &str) -> String {
214    let chars: Vec<char> = s.chars().collect();
215    let mut out = String::with_capacity(s.len());
216    let mut i = 0;
217    while i < chars.len() {
218        if !chars[i].is_ascii_alphanumeric() {
219            out.push(chars[i]);
220            i += 1;
221            continue;
222        }
223        let start = i;
224        while i < chars.len() && chars[i].is_ascii_alphanumeric() {
225            i += 1;
226        }
227        out.extend(&chars[start..i]);
228        if chars.get(i) == Some(&'\'')
229            && matches!(chars.get(i + 1), Some('t' | 's'))
230            && chars.get(i + 2).is_none_or(|c| is_js_whitespace(*c))
231        {
232            out.push(chars[i + 1]);
233            i += 2;
234            if let Some(c) = chars.get(i) {
235                out.push(*c);
236                i += 1;
237            }
238        }
239    }
240    out
241}
242
243// ---- url ----
244
245fn url_filter(input: &Value, args: &[Value], env: &FilterEnv) -> Result<Value, String> {
246    // The registered filter takes a truthy string argument as the path
247    // prefix, and uses the configured one, `/`, otherwise. A `SafeString`
248    // is an object, not a string.
249    let prefix = match args.first() {
250        Some(Value::String(s)) if !s.is_empty() && !env.args_safe.first().is_some_and(|x| *x) => {
251            s.to_string()
252        }
253        _ => "/".to_string(),
254    };
255    if env.input_safe {
256        // A `SafeString` is truthy. `new URL(it)` and `startsWith` read its
257        // text, so a URL comes back as the same object; anything else
258        // reaches `path.posix.join`, which wants a string.
259        let text = input.to_js_string_in(env.timezone);
260        return if is_valid_url(&text) || text.starts_with("//") {
261            env.returns_input();
262            Ok(input.clone())
263        } else {
264            Err(
265                "The \"path\" argument must be of type string. Received an instance of String"
266                    .to_string(),
267            )
268        };
269    }
270    if !input.js_truthy() {
271        return Ok(string(add_path_prefix("", &prefix)));
272    }
273    let Value::String(s) = input else {
274        // Only a string has `startsWith`. `new URL(value)` still runs first
275        // on the value's string form, so an array holding a URL passes.
276        // A `Date` never parses as a URL, so it throws, as in Eleventy.
277        return if is_valid_url(&input.to_js_string_in(env.timezone)) {
278            env.returns_input();
279            Ok(input.clone())
280        } else {
281            Err("url.startsWith is not a function".to_string())
282        };
283    };
284    if is_valid_url(s) || (s.starts_with("//") && &**s != "//") {
285        env.returns_input();
286        return Ok(input.clone());
287    }
288    Ok(string(add_path_prefix(s, &prefix)))
289}
290
291fn is_valid_url(s: &str) -> bool {
292    url::Url::parse(s).is_ok()
293}
294
295fn add_path_prefix(url: &str, prefix: &str) -> String {
296    let norm_url = normalize_url_path(&[url]);
297    let norm_root = normalize_url_path(&["/", prefix]);
298    let norm_full = normalize_url_path(&["/", prefix, url]);
299    if norm_url == "/" || norm_url == norm_root {
300        let slash = if norm_root.ends_with('/') { "" } else { "/" };
301        format!("{norm_root}{slash}")
302    } else if norm_url.starts_with('/') {
303        norm_full
304    } else {
305        norm_url
306    }
307}
308
309/// `TemplatePath.normalizeUrlPath`: `path.posix.join`, then trailing
310/// slashes collapse to one.
311fn normalize_url_path(parts: &[&str]) -> String {
312    let joined = posix_join(parts);
313    match joined.trim_end_matches('/').len() {
314        n if n == joined.len() => joined,
315        n => format!("{}/", &joined[..n]),
316    }
317}
318
319fn posix_join(parts: &[&str]) -> String {
320    let joined = parts
321        .iter()
322        .filter(|p| !p.is_empty())
323        .copied()
324        .collect::<Vec<_>>()
325        .join("/");
326    if joined.is_empty() {
327        ".".to_string()
328    } else {
329        posix_normalize(&joined)
330    }
331}
332
333/// Node's `path.posix.normalize`.
334fn posix_normalize(path: &str) -> String {
335    let absolute = path.starts_with('/');
336    let trailing = path.ends_with('/');
337    let mut stack: Vec<&str> = Vec::new();
338    for seg in path.split('/') {
339        match seg {
340            "" | "." => {}
341            ".." => {
342                if stack.last().is_some_and(|l| *l != "..") {
343                    stack.pop();
344                } else if !absolute {
345                    stack.push("..");
346                }
347            }
348            s => stack.push(s),
349        }
350    }
351    let mut out = stack.join("/");
352    if out.is_empty() {
353        return if absolute {
354            "/".to_string()
355        } else if trailing {
356            "./".to_string()
357        } else {
358            ".".to_string()
359        };
360    }
361    if trailing {
362        out.push('/');
363    }
364    if absolute { format!("/{out}") } else { out }
365}
366
367// ---- log ----
368
369/// Eleventy's `log` is `console.log(input, ...messages)`, then returns the
370/// input. This prints to stderr, so a build's own output stays clean.
371fn log_filter(input: &Value, args: &[Value], env: &FilterEnv) -> Result<Value, String> {
372    let mut all = Vec::with_capacity(args.len() + 1);
373    all.push(input.clone());
374    all.extend_from_slice(args);
375    // A closed stderr (`2>&1 | head -1`) must not panic mid-render.
376    let _ = writeln!(std::io::stderr(), "{}", console_format(&all));
377    env.returns_input();
378    Ok(input.clone())
379}
380
381/// What `console.log(...values)` prints: strings as they are, other values
382/// as `util.inspect` shows them, joined by spaces. Format specifiers such
383/// as `%s` are not interpreted, and nested values print in the single-line
384/// form Node uses when they fit in 80 columns.
385pub fn console_format(values: &[Value]) -> String {
386    values
387        .iter()
388        .map(|v| match v {
389            Value::String(s) => s.to_string(),
390            v => inspect(v, 0),
391        })
392        .collect::<Vec<_>>()
393        .join(" ")
394}
395
396fn inspect(v: &Value, depth: usize) -> String {
397    match v {
398        Value::String(s) => quote(s),
399        Value::Number(n) if *n == 0.0 && n.is_sign_negative() => "-0".to_string(),
400        Value::Number(n) => js_number_to_string(*n),
401        Value::Array(a) => {
402            if a.is_empty() {
403                "[]".to_string()
404            } else if depth > 2 {
405                "[Array]".to_string()
406            } else {
407                let items: Vec<String> = a.iter().map(|x| inspect(x, depth + 1)).collect();
408                wrap('[', ']', &items, depth)
409            }
410        }
411        Value::Object(o) => {
412            if o.is_empty() {
413                "{}".to_string()
414            } else if depth > 2 {
415                "[Object]".to_string()
416            } else {
417                let items: Vec<String> = Value::js_entries(o)
418                    .into_iter()
419                    .map(|(k, x)| format!("{}: {}", key(k), inspect(x, depth + 1)))
420                    .collect();
421                wrap('{', '}', &items, depth)
422            }
423        }
424        v => v.to_js_string(),
425    }
426}
427
428fn wrap(open: char, close: char, items: &[String], depth: usize) -> String {
429    let total: usize = items.iter().map(|s| s.len()).sum::<usize>() + items.len();
430    let start = items.len() + depth * 2 + 1 + 10;
431    if total + start <= 80 && items.iter().all(|s| !s.contains('\n')) {
432        format!("{open} {} {close}", items.join(", "))
433    } else {
434        let pad = "  ".repeat(depth);
435        format!(
436            "{open}\n{pad}  {}\n{pad}{close}",
437            items.join(&format!(",\n{pad}  "))
438        )
439    }
440}
441
442fn key(k: &str) -> String {
443    let mut chars = k.chars();
444    let ident = chars
445        .next()
446        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
447        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
448    if ident { k.to_string() } else { quote(k) }
449}
450
451fn quote(s: &str) -> String {
452    let q = if !s.contains('\'') {
453        '\''
454    } else if !s.contains('"') {
455        '"'
456    } else if !s.contains('`') {
457        '`'
458    } else {
459        '\''
460    };
461    let mut out = String::from(q);
462    for c in s.chars() {
463        match c {
464            '\n' => out.push_str("\\n"),
465            '\t' => out.push_str("\\t"),
466            '\r' => out.push_str("\\r"),
467            '\\' => out.push_str("\\\\"),
468            c if c == q => {
469                out.push('\\');
470                out.push(c);
471            }
472            c => out.push(c),
473        }
474    }
475    out.push(q);
476    out
477}