jsandbox 0.7.0

JavaScript sandbox using deno runtime.
Documentation
use async_trait::async_trait;
use jsandbox::serde_json;
use jsandbox::AnyError;

#[tokio::test]
async fn call() {
    let mut script = jsandbox::Script::from_string("function add(a, b) { return a + b; }")
        .build()
        .unwrap();
    let result: u32 = script.call("add", (1, 2)).await.unwrap();

    assert_eq!(result, 3);
}

#[tokio::test]
async fn call_async() {
    let mut script = jsandbox::Script::from_string(
        "async function add(a, b) { return new Promise((resolve) => resolve(a + b)); }",
    )
    .build()
    .unwrap();
    let result: u32 = script.call("add", (1, 2)).await.unwrap();

    assert_eq!(result, 3);
}

#[tokio::test]
async fn call_timeout() {
    let mut script = jsandbox::Script::from_string("function timeout() { for(;;){} }")
        .build()
        .unwrap()
        .timeout(std::time::Duration::from_millis(100));
    let result: Result<String, jsandbox::AnyError> = script.call("timeout", ()).await;
    let err = result.unwrap_err();

    assert_eq!(err.to_string(), "Uncaught Error: execution terminated");
}

#[tokio::test]
async fn forgot_build() {
    let mut script = jsandbox::Script::from_string("function func() { }");
    let result: Result<String, jsandbox::AnyError> = script.call("func", ()).await;
    let err = result.unwrap_err();

    assert!(err
        .to_string()
        .contains("Script is not properly initialized"));
}

#[tokio::test]
async fn var_state() {
    let mut script = jsandbox::Script::from_string(
        "
        let val = 1;
        function get_val() { return val++; }
        ",
    )
    .build()
    .unwrap();

    let mut result: u32 = script.call("get_val", ()).await.unwrap();
    assert_eq!(result, 1);

    result = script.call("get_val", ()).await.unwrap();
    assert_eq!(result, 2);
}

struct MyCallback {
    value: i32,
}
#[async_trait]
impl jsandbox::Callback for MyCallback {
    async fn callback(&mut self, value: serde_json::Value) -> Result<serde_json::Value, AnyError> {
        assert_eq!(self.value, value);

        Ok(jsandbox::serde_json::to_value(789)?)
    }
}

#[tokio::test]
async fn func_callback() {
    let mut script = jsandbox::Script::from_string(
        "
        async function call_my_callback() {
            return await my_callback(123);
        }
        ",
    )
    .function("my_callback".to_string(), MyCallback { value: 123_i32 })
    .build()
    .unwrap();

    let result: u32 = script.call("call_my_callback", ()).await.unwrap();
    assert_eq!(result, 789);
}