Skip to main content

brrrty_js/
runtime.rs

1//! What crosses from a JavaScript runtime (the site's own Node, run by
2//! `brrrty-node`) into a build: decoded values, function handles, errors,
3//! and the trait a build drives the runtime through.
4
5use std::path::{Path, PathBuf};
6
7use crate::Value;
8pub use crate::functions::{Settle, This};
9
10pub use crate::value::FnHandle;
11
12/// One step of a path inside a data file's value.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum PathPart {
15    Key(String),
16    Index(usize),
17}
18
19/// What the worker's encoding says of a plain object it refused for holding
20/// properties templates could see but Brrrty can't list.
21pub const UNLISTED_OBJECT: &str = "an object with properties Brrrty can't list";
22
23/// Whether a refusal is of a plain object, which 11ty merges as data, as
24/// opposed to a value 11ty ignores as a data file's whole result.
25pub fn refused_plain_object(what: &str) -> bool {
26    what.starts_with(UNLISTED_OBJECT)
27}
28
29/// A path inside a data file's value, shown as `data.posts[3].date`.
30pub fn path_text(path: &[PathPart]) -> String {
31    // A very deep path keeps its first and last parts.
32    const KEEP: usize = 6;
33    let mut out = String::from("data");
34    for (n, part) in path.iter().enumerate() {
35        if path.len() > 3 * KEEP && n >= KEEP && n < path.len() - KEEP {
36            if n == KEEP {
37                out.push_str(&format!("<{} levels>", path.len() - 2 * KEEP));
38            }
39            continue;
40        }
41        match part {
42            PathPart::Index(i) => out.push_str(&format!("[{i}]")),
43            PathPart::Key(k) => {
44                let plain = k
45                    .chars()
46                    .next()
47                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
48                    && k.chars()
49                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
50                if plain {
51                    out.push('.');
52                    out.push_str(k);
53                } else {
54                    out.push('[');
55                    out.push_str(&serde_json::Value::String(k.clone()).to_string());
56                    out.push(']');
57                }
58            }
59        }
60    }
61    out
62}
63
64/// A value from the runtime. A function is a [`Value::Function`] in
65/// `value`; a refused value is [`Value::Undefined`]. Both are listed by
66/// path.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Decoded {
69    pub value: Value,
70    /// Every function value, by its path from the value's root.
71    pub functions: Vec<(Vec<PathPart>, FnHandle)>,
72    /// Every value that can't cross exactly, by path, with what it is
73    /// ("a Map object").
74    pub refused: Vec<(Vec<PathPart>, String)>,
75}
76
77impl Decoded {
78    /// True when the whole value crossed: no functions and nothing refused.
79    pub fn is_exact(&self) -> bool {
80        self.functions.is_empty() && self.refused.is_empty()
81    }
82}
83
84/// An exception thrown (or a promise rejected) by the site's code.
85#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub struct JsError {
87    /// `TypeError`, or empty when a non-Error value was thrown.
88    pub name: String,
89    pub message: String,
90    pub stack: String,
91    /// Where the error is reported: the first stack frame inside the
92    /// project and outside `node_modules`, else the first frame.
93    pub file: Option<PathBuf>,
94    pub line: Option<u32>,
95    pub column: Option<u32>,
96    /// 11ty's own refusal of a JavaScript template ("No JavaScript template
97    /// returned from ..."), not the site's code throwing.
98    pub invalid: bool,
99}
100
101/// Why the runtime can't go on at all.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct RuntimeFailure {
104    /// What happened, in one line (`Node exited with status 3`).
105    pub message: String,
106    /// The last lines Node wrote to stderr.
107    pub stderr_tail: Vec<String>,
108    /// Brrrty stopped the runtime itself (Ctrl-C, SIGTERM): not a failure
109    /// of the data.
110    pub stopped: bool,
111    /// The runtime asks for the build to be run again: it took a shortcut
112    /// it can't stand behind for this site, and the next runtime won't.
113    pub again: bool,
114}
115
116/// The outcome of one request: a value, the site's own exception, a value
117/// Brrrty refused to hand on, or a runtime that stopped.
118#[derive(Debug, Clone, PartialEq)]
119pub enum JsResult<T> {
120    Ok(T),
121    Thrown(JsError),
122    /// The request ran, but its outcome can't be used exactly.
123    Refused(Refusal),
124    Failed(RuntimeFailure),
125}
126
127/// Why a call's outcome can't be used exactly.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Refusal {
130    /// The reason, naming the function: it reads what Brrrty can't hand
131    /// it, changes its arguments, or returns something that can't cross.
132    pub why: String,
133    /// The function gave different results for the same data: it keeps
134    /// state between calls, so any page's result from it may differ from
135    /// 11ty's.
136    pub impure: bool,
137}
138
139impl Refusal {
140    pub fn new(why: impl Into<String>) -> Refusal {
141        Refusal {
142            why: why.into(),
143            impure: false,
144        }
145    }
146}
147
148/// Runs one of Brrrty's filters for a JavaScript template's `this`:
149/// `(name, arguments)`. `Err` refuses the render, with why.
150pub type FilterCall<'a> = dyn FnMut(&str, &[Value]) -> Result<Value, String> + 'a;
151
152/// Brrrty's filters by name, shared: see [`JsRuntime::set_filters`].
153pub type Filters = std::sync::Arc<dyn Fn(&str, &[Value]) -> Result<Value, String> + Send + Sync>;
154
155/// A JavaScript template or layout (`.11ty.js`) loaded in the runtime: its
156/// instance stays there, by this id.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158pub struct TemplateId(pub u64);
159
160/// What loading a JavaScript template gave: its id, and its data (what
161/// 11ty takes as its front matter).
162#[derive(Debug, Clone, PartialEq)]
163pub struct LoadedTemplate {
164    pub id: TemplateId,
165    pub data: Decoded,
166}
167
168/// An operation the pages make while they build, for [`JsRuntime::begin`].
169#[derive(Debug, Clone, Copy)]
170pub enum Op<'a> {
171    /// [`JsRuntime::call`].
172    Call {
173        f: FnHandle,
174        this: This<'a>,
175        args: &'a [Value],
176        settle: Settle,
177    },
178    /// [`JsRuntime::page_once`].
179    PageOnce {
180        data: &'a Value,
181        traps: &'a [(String, String)],
182        defaults: &'a [String],
183        f: FnHandle,
184    },
185    /// [`JsRuntime::page_open_with_vars`]: the results are the open's and
186    /// each function's list, or the one that failed.
187    PageOpenWithVars {
188        data: &'a Value,
189        traps: &'a [(String, String)],
190        defaults: &'a [String],
191        functions: &'a [FnHandle],
192        keys: &'a [String],
193    },
194    /// [`JsRuntime::page_run`].
195    PageRun {
196        page: PageId,
197        steps: &'a [PageStep<'a>],
198    },
199    /// [`JsRuntime::render`].
200    Render {
201        template: TemplateId,
202        data: &'a Value,
203        first: Option<&'a Value>,
204        traps: &'a [(String, String)],
205    },
206}
207
208/// An operation begun (see [`JsRuntime::begin`]).
209pub enum Begun {
210    /// It is over already.
211    Done(Finished),
212    /// It was sent: wait for it without holding the runtime, then hand
213    /// what came to [`JsRuntime::finish`].
214    Sent(Box<dyn Pending>),
215}
216
217/// An operation on its way.
218pub trait Pending: Send {
219    /// Wait for it, answering the runtime's questions (a filter a
220    /// JavaScript template calls on `this`) with `filters`.
221    fn wait(self: Box<Self>, filters: &mut FilterCall<'_>) -> Waited;
222}
223
224/// What came of a [`Pending`] operation, for the runtime that sent it.
225pub struct Waited(pub Box<dyn std::any::Any + Send>);
226
227/// How an operation ended.
228pub enum Finished {
229    /// Its results, and the page it opened.
230    Results {
231        results: Vec<JsResult<Decoded>>,
232        page: Option<PageId>,
233    },
234    /// The runtime lost the values it referred to before it ran (another
235    /// page's call changed one): begin it again.
236    Again,
237}
238
239/// One step of a page's computed data, for [`JsRuntime::page_run`].
240#[derive(Debug, Clone, Copy)]
241pub enum PageStep<'a> {
242    /// Call the function with the page's data, and set its result at the
243    /// dotted key.
244    Call(FnHandle, Option<&'a str>),
245    /// Set the dotted key to the value.
246    Set(&'a str, &'a Value),
247}
248
249/// One page's data, kept in the runtime while its computed values run, as
250/// 11ty keeps one data object per page.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252pub struct PageId(pub u64);
253
254/// A JavaScript runtime that loads data files and calls the functions in
255/// them, one request at a time.
256pub trait JsRuntime: Send {
257    /// The data 11ty hands an exported function (`addGlobalData` values and
258    /// `eleventy`), sent once before any file loads.
259    fn set_argument(&mut self, arg: &Value) -> JsResult<()>;
260    /// Import `file` (absolute) as 11ty does; when `call` and the export is
261    /// a function, call it with the argument and await it.
262    fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded>;
263    /// Evaluate the `---js` front matter `code` of `file` as 11ty 3 does: top-level
264    /// declarations become the data (a block starting with `{` is an object literal).
265    fn front_matter(&mut self, _code: &str, _file: &Path, _input_path: &str) -> JsResult<Decoded> {
266        JsResult::Refused(Refusal::new(
267            "this runtime can't evaluate front matter".to_string(),
268        ))
269    }
270
271    /// Import the site's 11ty config file (absolute) as 11ty does and call
272    /// its export with a recording `eleventyConfig`. The value is
273    /// `{ returned, values, functions, unsupported }`.
274    fn load_config(&mut self, _file: &Path) -> JsResult<Decoded> {
275        JsResult::Refused(Refusal::new(
276            "this runtime can't load an 11ty config".to_string(),
277        ))
278    }
279    /// Call a function value from a template with `this` and `args`.
280    fn call(
281        &mut self,
282        f: FnHandle,
283        this: This<'_>,
284        args: &[Value],
285        settle: Settle,
286    ) -> JsResult<Decoded>;
287    /// Keep `data` as a page's data object. Each of `traps` (a top-level
288    /// key and why) is a key Brrrty can't supply: reading it refuses the
289    /// call. Each of `defaults` (a dotted computed key) that is undefined
290    /// is set to `""`, as 11ty's computed data proxy does.
291    fn page_open(
292        &mut self,
293        data: &Value,
294        traps: &[(String, String)],
295        defaults: &[String],
296    ) -> JsResult<PageId>;
297    /// The keys `f` reads of the page's data, as 11ty's
298    /// `ComputedDataProxy.findVarsUsed` finds them (`keys` are the page's
299    /// computed keys).
300    fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>>;
301    /// Call `f` with the page's data, as 11ty calls a computed function or
302    /// a permalink function, awaiting it; with `set`, store the result at
303    /// that dotted key of the page's data.
304    fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded>;
305    /// Set a dotted key of the page's data, as 11ty's `lodash.set` does.
306    fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()>;
307    /// Forget the page's data.
308    fn page_close(&mut self, page: PageId);
309    /// Begin an operation. A runtime that can run several at once sends it
310    /// and gives back [`Begun::Sent`]: the render threads then wait for
311    /// their results at the same time, and the runtime never waits on
312    /// Brrrty between one request and the next. Any other runs it here.
313    fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
314        let results = match op {
315            Op::Call {
316                f,
317                this,
318                args,
319                settle,
320            } => vec![self.call(f, this, args, settle)],
321            Op::PageOnce {
322                data,
323                traps,
324                defaults,
325                f,
326            } => vec![self.page_once(data, traps, defaults, f)],
327            Op::PageOpenWithVars {
328                data,
329                traps,
330                defaults,
331                functions,
332                keys,
333            } => {
334                return Begun::Done(
335                    match self.page_open_with_vars(data, traps, defaults, functions, keys) {
336                        JsResult::Ok((page, found)) => Finished::Results {
337                            results: std::iter::once(Value::Null)
338                                .chain(found.into_iter().map(|list| {
339                                    Value::Array(std::sync::Arc::new(
340                                        list.into_iter().map(|s| Value::String(s.into())).collect(),
341                                    ))
342                                }))
343                                .map(|value| {
344                                    JsResult::Ok(Decoded {
345                                        value,
346                                        functions: Vec::new(),
347                                        refused: Vec::new(),
348                                    })
349                                })
350                                .collect(),
351                            page: Some(page),
352                        },
353                        JsResult::Thrown(e) => Finished::Results {
354                            results: vec![JsResult::Thrown(e)],
355                            page: None,
356                        },
357                        JsResult::Refused(r) => Finished::Results {
358                            results: vec![JsResult::Refused(r)],
359                            page: None,
360                        },
361                        JsResult::Failed(f) => Finished::Results {
362                            results: vec![JsResult::Failed(f)],
363                            page: None,
364                        },
365                    },
366                );
367            }
368            Op::PageRun { page, steps } => self.page_run(page, steps),
369            Op::Render {
370                template,
371                data,
372                first,
373                traps,
374            } => vec![self.render(template, data, first, traps, filters)],
375        };
376        Begun::Done(Finished::Results {
377            results,
378            page: None,
379        })
380    }
381    /// What came of an operation [`JsRuntime::begin`] sent.
382    fn finish(&mut self, _waited: Waited) -> Finished {
383        Finished::Results {
384            results: vec![JsResult::Failed(RuntimeFailure {
385                message: "this runtime sends nothing ahead".into(),
386                stderr_tail: Vec::new(),
387                stopped: false,
388                again: false,
389            })],
390            page: None,
391        }
392    }
393    /// [`JsRuntime::page_open`], one [`JsRuntime::page_call`] of `f` with
394    /// nothing set, and [`JsRuntime::page_close`]: a permalink function
395    /// called for a page with no computed data open.
396    fn page_once(
397        &mut self,
398        data: &Value,
399        traps: &[(String, String)],
400        defaults: &[String],
401        f: FnHandle,
402    ) -> JsResult<Decoded> {
403        let page = match self.page_open(data, traps, defaults) {
404            JsResult::Ok(p) => p,
405            JsResult::Thrown(e) => return JsResult::Thrown(e),
406            JsResult::Refused(r) => return JsResult::Refused(r),
407            JsResult::Failed(f) => return JsResult::Failed(f),
408        };
409        let r = self.page_call(page, f, None);
410        self.page_close(page);
411        r
412    }
413    /// [`JsRuntime::page_open`], then [`JsRuntime::page_vars`] of each of
414    /// `functions` in order: the page, and what each reads. When one of
415    /// them gives no list, the page is closed and that is the result.
416    fn page_open_with_vars(
417        &mut self,
418        data: &Value,
419        traps: &[(String, String)],
420        defaults: &[String],
421        functions: &[FnHandle],
422        keys: &[String],
423    ) -> JsResult<(PageId, Vec<Vec<String>>)> {
424        let page = match self.page_open(data, traps, defaults) {
425            JsResult::Ok(p) => p,
426            JsResult::Thrown(e) => return JsResult::Thrown(e),
427            JsResult::Refused(r) => return JsResult::Refused(r),
428            JsResult::Failed(f) => return JsResult::Failed(f),
429        };
430        let mut found = Vec::with_capacity(functions.len());
431        for f in functions {
432            match self.page_vars(page, *f, keys) {
433                JsResult::Ok(list) => found.push(list),
434                other => {
435                    self.page_close(page);
436                    return match other {
437                        JsResult::Thrown(e) => JsResult::Thrown(e),
438                        JsResult::Refused(r) => JsResult::Refused(r),
439                        JsResult::Failed(f) => JsResult::Failed(f),
440                        JsResult::Ok(_) => unreachable!("handled above"),
441                    };
442                }
443            }
444        }
445        JsResult::Ok((page, found))
446    }
447    /// The `steps` in order, each as [`JsRuntime::page_call`] or
448    /// [`JsRuntime::page_set`] would run it. The list ends with the first
449    /// result that isn't a value (a runtime may have run the steps after
450    /// it all the same: nothing is made of them).
451    fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
452        let mut out = Vec::with_capacity(steps.len());
453        for step in steps {
454            let r = match step {
455                PageStep::Call(f, set) => self.page_call(page, *f, *set),
456                PageStep::Set(key, value) => match self.page_set(page, key, value) {
457                    JsResult::Ok(()) => JsResult::Ok(Decoded {
458                        value: Value::Undefined,
459                        functions: Vec::new(),
460                        refused: Vec::new(),
461                    }),
462                    JsResult::Thrown(e) => JsResult::Thrown(e),
463                    JsResult::Refused(r) => JsResult::Refused(r),
464                    JsResult::Failed(f) => JsResult::Failed(f),
465                },
466            };
467            let stop = !matches!(r, JsResult::Ok(_));
468            out.push(r);
469            if stop {
470                break;
471            }
472        }
473        out
474    }
475    /// Every file the site's code read or loaded so far, absolute.
476    fn reads(&mut self) -> JsResult<Vec<PathBuf>>;
477    /// The global data files are loaded: each of their values that a later
478    /// one changed (by its file), as it is now, which is what 11ty's pages
479    /// see.
480    fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>>;
481    /// The data files are loaded; what follows are the pages' calls.
482    /// `Refused` when a template or directory data file changed a value
483    /// another file gave, or a built-in prototype.
484    fn begin_calls(&mut self) -> JsResult<()>;
485    /// Brrrty's filters, which JavaScript calls on `this` (a template, a
486    /// computed or permalink function): `(name, arguments)`.
487    fn set_filters(&mut self, filters: Filters);
488    /// The names 11ty puts on a JavaScript template's `this` as functions
489    /// (its filters and shortcodes), in its order. Sent before any template
490    /// loads.
491    fn template_setup(&mut self, filters: &[String], node: &[(String, u32)]) -> JsResult<()>;
492    /// Import the JavaScript template or layout `file` (absolute) as 11ty
493    /// does, make its instance, and read its `data`.
494    fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate>;
495    /// Make a template of `file` (absolute), a file of the custom extension `ext` the JS config
496    /// added (`addExtension`): its `content` (the file without its front matter) goes to the
497    /// extension's `compile`, and the page's data to the render function that makes.
498    fn load_custom_template(
499        &mut self,
500        file: &Path,
501        ext: &str,
502        content: &str,
503    ) -> JsResult<LoadedTemplate>;
504    /// Render a loaded template with the page's `data` (for a layout, with
505    /// `content`), as 11ty's JavaScript engine does: `first` is the `page`
506    /// 11ty's first render of it set as `this.page`. Each of `traps` (a
507    /// top-level key and why) is a key Brrrty can't supply. A filter the
508    /// template calls on `this` runs as `filters(name, arguments)`; `Err`
509    /// refuses the render with why.
510    fn render(
511        &mut self,
512        template: TemplateId,
513        data: &Value,
514        first: Option<&Value>,
515        traps: &[(String, String)],
516        filters: &mut FilterCall<'_>,
517    ) -> JsResult<Decoded>;
518    /// Check that no call's result depended on the calls made before it:
519    /// run the same calls again, in fresh runtimes, in other orders, and
520    /// compare every result. `Refused` (marked impure) names the first
521    /// difference.
522    fn verify(&mut self) -> JsResult<()>;
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn paths_read_like_javascript() {
531        let p = [
532            PathPart::Key("posts".into()),
533            PathPart::Index(3),
534            PathPart::Key("a b".into()),
535            PathPart::Key("$ok_1".into()),
536        ];
537        assert_eq!(path_text(&p), r#"data.posts[3]["a b"].$ok_1"#);
538        assert_eq!(path_text(&[]), "data");
539    }
540
541    #[test]
542    fn a_very_deep_path_keeps_its_ends() {
543        let p: Vec<PathPart> = (0..40).map(|_| PathPart::Key("c".into())).collect();
544        assert_eq!(path_text(&p), "data.c.c.c.c.c.c<28 levels>.c.c.c.c.c.c");
545    }
546}