Skip to main content

brep_script_core/
lib.rs

1//! The interpreter core: evaluate one script, call one global function with
2//! one JSON argument, and hand back its JSON result or its refusal.
3//!
4//! This crate depends on Boa and `serde_json` and nothing else — no file
5//! system, no network, no store — so the same interpreter runs natively and
6//! in a `wasm32-unknown-unknown` build. Everything that reaches outside the
7//! interpreter is installed by the caller through [`call`]'s `install`
8//! argument; [`boa_engine`] is re-exported so those bindings name the same
9//! engine version.
10//!
11//! Beside [`call`], [`modules::with_module`] evaluates an in-memory graph of
12//! ES modules, and [`worker`] is a restricted execution protocol driven by
13//! host messages ([`worker::Realm`]). See the README for an example.
14//!
15//! # A fresh interpreter per call
16//!
17//! Every call builds a new [`Context`], evaluates the file, and drops it. No
18//! state leaks from one hook call into the next, a script edited on disk is
19//! simply the script the next call evaluates, and a `Context` (which is not
20//! `Send`) never has to cross a thread.
21//!
22//! # What is bounded, honestly
23//!
24//! Boa's [`RuntimeLimits`](boa_engine::vm::RuntimeLimits) bound three things;
25//! the first two are set here and the stack size keeps Boa's default:
26//!
27//! * each CALL FRAME may run at most [`LOOP_ITERATION_LIMIT`] loop iterations
28//!   in total (Boa counts per frame, not per loop) — an infinite `while (true)`
29//!   throws instead of hanging, but a loop that calls a function whose own
30//!   loops stay under the limit is not bounded in total;
31//! * call depth is at most [`RECURSION_LIMIT`] — runaway recursion throws;
32//! * the VM stack size.
33//!
34//! There is NO wall-clock limit: Boa cannot pre-empt a running script. A script
35//! of many individually-bounded loops can still run long, and a script blocked
36//! inside a host function (an HTTP call, a child process) is bounded only by
37//! that host function's own timeout.
38
39use std::cell::RefCell;
40use std::rc::Rc;
41
42use boa_engine::object::ObjectInitializer;
43use boa_engine::property::Attribute;
44use boa_engine::{js_string, Context, JsError, JsResult, JsString, JsValue, NativeFunction, Source};
45use serde_json::Value;
46
47/// Boa itself, so a host names the same engine's types (`Context`, `JsValue`,
48/// `ObjectInitializer`) its bindings are built from without a Boa line of its
49/// own that could drift to another version.
50pub use boa_engine;
51
52/// The most loop iterations any one call frame may run before it throws.
53pub const LOOP_ITERATION_LIMIT: u64 = 10_000_000;
54
55/// The deepest call stack a script may build before it throws.
56pub const RECURSION_LIMIT: usize = 512;
57
58/// Lines a script wrote through `console.log`, kept for the caller — the test
59/// run shows them, and a failing hook's log goes to the server log.
60pub type Logs = Rc<RefCell<Vec<String>>>;
61
62/// A call that returned.
63#[derive(Debug, Clone)]
64pub struct Success {
65    /// What the function returned, as JSON. `undefined` reads as `null`.
66    pub value: Value,
67    pub logs: Vec<String>,
68}
69
70/// A call that threw, failed to parse, or named a function the file does not
71/// define. `message` is what a person reads: for `throw new Error("x")` it is
72/// `x`, for `throw "x"` it is `x`.
73#[derive(Debug, Clone)]
74pub struct Failure {
75    pub message: String,
76    pub logs: Vec<String>,
77}
78
79/// Evaluate `source` (named `file` in messages), then call the global
80/// function `function` with `input` as its single argument.
81///
82/// `install` runs after `console` is defined and before the file is
83/// evaluated, and is where a caller adds its host objects.
84pub fn call(
85    source: &str,
86    file: &str,
87    function: &str,
88    input: &Value,
89    install: &dyn Fn(&mut Context, &Logs) -> JsResult<()>,
90) -> Result<Success, Failure> {
91    let mut context = Context::default();
92    let limits = context.runtime_limits_mut();
93    limits.set_loop_iteration_limit(LOOP_ITERATION_LIMIT);
94    limits.set_recursion_limit(RECURSION_LIMIT);
95
96    let logs: Logs = Rc::new(RefCell::new(Vec::new()));
97    let fail = |message: String, logs: &Logs| Failure {
98        message,
99        logs: logs.borrow().clone(),
100    };
101
102    if let Err(error) = install_console(&mut context, &logs).and_then(|()| install(&mut context, &logs)) {
103        return Err(fail(format!("setting up the script host failed: {}", describe(error, &mut context)), &logs));
104    }
105
106    let path = std::path::Path::new(file);
107    if let Err(error) = context.eval(Source::from_bytes(source).with_path(path)) {
108        let message = describe(error, &mut context);
109        return Err(fail(format!("{file}: {message}"), &logs));
110    }
111
112    let global = context.global_object();
113    let callee = match global.get(JsString::from(function), &mut context) {
114        Ok(value) => value,
115        Err(error) => return Err(fail(describe(error, &mut context), &logs)),
116    };
117    let Some(callee) = callee.as_callable() else {
118        return Err(fail(format!("{file} defines no function {function}()"), &logs));
119    };
120
121    let argument = match JsValue::from_json(input, &mut context) {
122        Ok(value) => value,
123        Err(error) => return Err(fail(describe(error, &mut context), &logs)),
124    };
125    let returned = match callee.call(&JsValue::undefined(), &[argument], &mut context) {
126        Ok(value) => value,
127        Err(error) => return Err(fail(describe(error, &mut context), &logs)),
128    };
129    // A script may have queued promise jobs; run them so their side effects
130    // (a log line, a write) are not silently dropped.
131    let _ = context.run_jobs();
132
133    let value = match returned.to_json(&mut context) {
134        Ok(json) => json.unwrap_or(Value::Null),
135        Err(error) => {
136            return Err(fail(
137                format!("{function}() returned a value that is not JSON: {}", describe(error, &mut context)),
138                &logs,
139            ))
140        }
141    };
142    let logs = logs.borrow().clone();
143    Ok(Success { value, logs })
144}
145
146/// The message a person should read for `error`.
147pub fn describe(error: JsError, context: &mut Context) -> String {
148    if let Some(value) = error.as_opaque() {
149        if let Some(text) = value.as_string() {
150            return text.to_std_string_escaped();
151        }
152    }
153    match error.try_native(context) {
154        Ok(native) if !native.message().is_empty() => native.message().to_string(),
155        Ok(native) => native.to_string(),
156        Err(_) => {
157            // A thrown plain object: show it as JSON if it is JSON.
158            if let Some(value) = error.as_opaque() {
159                if let Ok(Some(json)) = value.to_json(context) {
160                    return json.to_string();
161                }
162            }
163            error.to_string()
164        }
165    }
166}
167
168/// One argument as the text a log line shows: strings verbatim, everything
169/// else as JSON.
170pub fn text_of(value: &JsValue, context: &mut Context) -> String {
171    if let Some(text) = value.as_string() {
172        return text.to_std_string_escaped();
173    }
174    match value.to_json(context) {
175        Ok(Some(json)) => json.to_string(),
176        Ok(None) => "undefined".to_string(),
177        Err(_) => value.display().to_string(),
178    }
179}
180
181/// `console.log / info / warn / error`, all writing into `logs`.
182fn install_console(context: &mut Context, logs: &Logs) -> JsResult<()> {
183    let make = |prefix: &'static str| {
184        let logs = logs.clone();
185        // SAFETY: the closure captures an `Rc<RefCell<Vec<String>>>`, which
186        // holds no garbage-collected value, so the collector has nothing in it
187        // to trace.
188        unsafe {
189            NativeFunction::from_closure(move |_, args, context| {
190                let line = args
191                    .iter()
192                    .map(|value| text_of(value, context))
193                    .collect::<Vec<_>>()
194                    .join(" ");
195                logs.borrow_mut().push(format!("{prefix}{line}"));
196                Ok(JsValue::undefined())
197            })
198        }
199    };
200    let console = ObjectInitializer::new(context)
201        .function(make(""), js_string!("log"), 0)
202        .function(make(""), js_string!("info"), 0)
203        .function(make("warn: "), js_string!("warn"), 0)
204        .function(make("error: "), js_string!("error"), 0)
205        .build();
206    context.register_global_property(js_string!("console"), console, Attribute::all())
207}
208
209
210pub mod modules;
211/// The code-mode worker process (a host binary started with its worker flag).
212pub mod worker;