rig-boa 0.1.0

A minimal Boa JavaScript executor for Rig applications.
Documentation
//! Lightweight execution of [Boa](https://github.com/boa-dev/boa) JavaScript programs.
//!
//! `BoaExecutor` creates a fresh JavaScript context for each call, keeping
//! globals from separate application or agent requests isolated.

use boa_engine::{Context, JsError, JsValue, Source};

/// Errors returned while evaluating JavaScript.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct BoaError(#[from] JsError);

/// Executes JavaScript in a fresh Boa context.
#[derive(Clone, Copy, Debug, Default)]
pub struct BoaExecutor;

impl BoaExecutor {
    /// Evaluates `source` and returns its completion value.
    ///
    /// A fresh Boa context is used on each call, preventing globals from leaking
    /// between independent application or agent requests.
    pub fn eval(&self, source: impl AsRef<[u8]>) -> Result<JsValue, BoaError> {
        let mut context = Context::default();
        Ok(context.eval(Source::from_bytes(source.as_ref()))?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn evaluates_javascript() {
        let value = BoaExecutor.eval("const x = 20; x + 22").unwrap();

        assert_eq!(value.display().to_string(), "42");
    }

    #[test]
    fn does_not_share_globals_between_calls() {
        let executor = BoaExecutor;
        executor.eval("globalThis.answer = 42").unwrap();

        assert_eq!(
            executor
                .eval("typeof answer")
                .unwrap()
                .display()
                .to_string(),
            "\"undefined\""
        );
    }
}