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