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
188/// `@sindresorhus/slugify` 2.2.1 with `{ decamelize: false }`: 11ty's `slugify` filter.
189pub fn slugify(text: &str) -> String {
190    let lowered = transliterate(text).to_lowercase();
191    let lowered = drop_contraction_apostrophes(&lowered);
192    // `[^a-z\d]+` becomes one separator, and a separator at either end goes.
193    let mut out = String::new();
194    let mut pending = false;
195    for c in lowered.chars() {
196        if c.is_ascii_lowercase() || c.is_ascii_digit() {
197            if pending && !out.is_empty() {
198                out.push('-');
199            }
200            pending = false;
201            out.push(c);
202        } else {
203            pending = true;
204        }
205    }
206    out
207}
208
209/// `s.replace(/([a-zA-Z\d]+)'([ts])(\s|$)/g, "$1$2$3")`.
210fn drop_contraction_apostrophes(s: &str) -> String {
211    let chars: Vec<char> = s.chars().collect();
212    let mut out = String::with_capacity(s.len());
213    let mut i = 0;
214    while i < chars.len() {
215        if !chars[i].is_ascii_alphanumeric() {
216            out.push(chars[i]);
217            i += 1;
218            continue;
219        }
220        let start = i;
221        while i < chars.len() && chars[i].is_ascii_alphanumeric() {
222            i += 1;
223        }
224        out.extend(&chars[start..i]);
225        if chars.get(i) == Some(&'\'')
226            && matches!(chars.get(i + 1), Some('t' | 's'))
227            && chars.get(i + 2).is_none_or(|c| is_js_whitespace(*c))
228        {
229            out.push(chars[i + 1]);
230            i += 2;
231            if let Some(c) = chars.get(i) {
232                out.push(*c);
233                i += 1;
234            }
235        }
236    }
237    out
238}
239
240// ---- url ----
241
242fn url_filter(input: &Value, args: &[Value], env: &FilterEnv) -> Result<Value, String> {
243    // The registered filter takes a truthy string argument as the path
244    // prefix, and uses the configured one, `/`, otherwise. A `SafeString`
245    // is an object, not a string.
246    let prefix = match args.first() {
247        Some(Value::String(s)) if !s.is_empty() && !env.args_safe.first().is_some_and(|x| *x) => {
248            s.to_string()
249        }
250        _ => "/".to_string(),
251    };
252    if env.input_safe {
253        // A `SafeString` is truthy. `new URL(it)` and `startsWith` read its
254        // text, so a URL comes back as the same object; anything else
255        // reaches `path.posix.join`, which wants a string.
256        let text = input.to_js_string_in(env.timezone);
257        return if is_valid_url(&text) || text.starts_with("//") {
258            env.returns_input();
259            Ok(input.clone())
260        } else {
261            Err(
262                "The \"path\" argument must be of type string. Received an instance of String"
263                    .to_string(),
264            )
265        };
266    }
267    if !input.js_truthy() {
268        return Ok(string(add_path_prefix("", &prefix)));
269    }
270    let Value::String(s) = input else {
271        // Only a string has `startsWith`. `new URL(value)` still runs first
272        // on the value's string form, so an array holding a URL passes.
273        // A `Date` never parses as a URL, so it throws, as in Eleventy.
274        return if is_valid_url(&input.to_js_string_in(env.timezone)) {
275            env.returns_input();
276            Ok(input.clone())
277        } else {
278            Err("url.startsWith is not a function".to_string())
279        };
280    };
281    if is_valid_url(s) || (s.starts_with("//") && &**s != "//") {
282        env.returns_input();
283        return Ok(input.clone());
284    }
285    Ok(string(add_path_prefix(s, &prefix)))
286}
287
288fn is_valid_url(s: &str) -> bool {
289    url::Url::parse(s).is_ok()
290}
291
292fn add_path_prefix(url: &str, prefix: &str) -> String {
293    let norm_url = normalize_url_path(&[url]);
294    let norm_root = normalize_url_path(&["/", prefix]);
295    let norm_full = normalize_url_path(&["/", prefix, url]);
296    if norm_url == "/" || norm_url == norm_root {
297        let slash = if norm_root.ends_with('/') { "" } else { "/" };
298        format!("{norm_root}{slash}")
299    } else if norm_url.starts_with('/') {
300        norm_full
301    } else {
302        norm_url
303    }
304}
305
306/// `TemplatePath.normalizeUrlPath`: `path.posix.join`, then trailing
307/// slashes collapse to one.
308fn normalize_url_path(parts: &[&str]) -> String {
309    let joined = posix_join(parts);
310    match joined.trim_end_matches('/').len() {
311        n if n == joined.len() => joined,
312        n => format!("{}/", &joined[..n]),
313    }
314}
315
316fn posix_join(parts: &[&str]) -> String {
317    let joined = parts
318        .iter()
319        .filter(|p| !p.is_empty())
320        .copied()
321        .collect::<Vec<_>>()
322        .join("/");
323    if joined.is_empty() {
324        ".".to_string()
325    } else {
326        posix_normalize(&joined)
327    }
328}
329
330/// Node's `path.posix.normalize`.
331fn posix_normalize(path: &str) -> String {
332    let absolute = path.starts_with('/');
333    let trailing = path.ends_with('/');
334    let mut stack: Vec<&str> = Vec::new();
335    for seg in path.split('/') {
336        match seg {
337            "" | "." => {}
338            ".." => {
339                if stack.last().is_some_and(|l| *l != "..") {
340                    stack.pop();
341                } else if !absolute {
342                    stack.push("..");
343                }
344            }
345            s => stack.push(s),
346        }
347    }
348    let mut out = stack.join("/");
349    if out.is_empty() {
350        return if absolute {
351            "/".to_string()
352        } else if trailing {
353            "./".to_string()
354        } else {
355            ".".to_string()
356        };
357    }
358    if trailing {
359        out.push('/');
360    }
361    if absolute { format!("/{out}") } else { out }
362}
363
364// ---- log ----
365
366/// Eleventy's `log` is `console.log(input, ...messages)`, then returns the
367/// input. This prints to stderr, so a build's own output stays clean.
368fn log_filter(input: &Value, args: &[Value], env: &FilterEnv) -> Result<Value, String> {
369    let mut all = Vec::with_capacity(args.len() + 1);
370    all.push(input.clone());
371    all.extend_from_slice(args);
372    // A closed stderr (`2>&1 | head -1`) must not panic mid-render.
373    let _ = writeln!(std::io::stderr(), "{}", console_format(&all));
374    env.returns_input();
375    Ok(input.clone())
376}
377
378/// What `console.log(...values)` prints: strings as they are, other values
379/// as `util.inspect` shows them, joined by spaces. Format specifiers such
380/// as `%s` are not interpreted, and nested values print in the single-line
381/// form Node uses when they fit in 80 columns.
382pub fn console_format(values: &[Value]) -> String {
383    values
384        .iter()
385        .map(|v| match v {
386            Value::String(s) => s.to_string(),
387            v => inspect(v, 0),
388        })
389        .collect::<Vec<_>>()
390        .join(" ")
391}
392
393fn inspect(v: &Value, depth: usize) -> String {
394    match v {
395        Value::String(s) => quote(s),
396        Value::Number(n) if *n == 0.0 && n.is_sign_negative() => "-0".to_string(),
397        Value::Number(n) => js_number_to_string(*n),
398        Value::Array(a) => {
399            if a.is_empty() {
400                "[]".to_string()
401            } else if depth > 2 {
402                "[Array]".to_string()
403            } else {
404                let items: Vec<String> = a.iter().map(|x| inspect(x, depth + 1)).collect();
405                wrap('[', ']', &items, depth)
406            }
407        }
408        Value::Object(o) => {
409            if o.is_empty() {
410                "{}".to_string()
411            } else if depth > 2 {
412                "[Object]".to_string()
413            } else {
414                let items: Vec<String> = Value::js_entries(o)
415                    .into_iter()
416                    .map(|(k, x)| format!("{}: {}", key(k), inspect(x, depth + 1)))
417                    .collect();
418                wrap('{', '}', &items, depth)
419            }
420        }
421        v => v.to_js_string(),
422    }
423}
424
425fn wrap(open: char, close: char, items: &[String], depth: usize) -> String {
426    let total: usize = items.iter().map(|s| s.len()).sum::<usize>() + items.len();
427    let start = items.len() + depth * 2 + 1 + 10;
428    if total + start <= 80 && items.iter().all(|s| !s.contains('\n')) {
429        format!("{open} {} {close}", items.join(", "))
430    } else {
431        let pad = "  ".repeat(depth);
432        format!(
433            "{open}\n{pad}  {}\n{pad}{close}",
434            items.join(&format!(",\n{pad}  "))
435        )
436    }
437}
438
439fn key(k: &str) -> String {
440    let mut chars = k.chars();
441    let ident = chars
442        .next()
443        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
444        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
445    if ident { k.to_string() } else { quote(k) }
446}
447
448fn quote(s: &str) -> String {
449    let q = if !s.contains('\'') {
450        '\''
451    } else if !s.contains('"') {
452        '"'
453    } else if !s.contains('`') {
454        '`'
455    } else {
456        '\''
457    };
458    let mut out = String::from(q);
459    for c in s.chars() {
460        match c {
461            '\n' => out.push_str("\\n"),
462            '\t' => out.push_str("\\t"),
463            '\r' => out.push_str("\\r"),
464            '\\' => out.push_str("\\\\"),
465            c if c == q => {
466                out.push('\\');
467                out.push(c);
468            }
469            c => out.push(c),
470        }
471    }
472    out.push(q);
473    out
474}