1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
use std::path::Path;
use crate::traits::ToModuleSpecifier;
use crate::{Error, Module, ModuleWrapper, Runtime, RuntimeOptions};
/// Evaluate a piece of non-ECMAScript-module JavaScript code
/// Effects on the global scope will not persist
/// For a persistant variant, see [`Runtime::eval`]
///
/// # Arguments
/// * `javascript` - A single javascript expression
///
/// # Returns
/// A `Result` containing the deserialized result of the expression if successful,
/// or an error if execution fails, or the result cannot be deserialized.
///
/// # Errors
/// Will return an error if the runtime cannot be started (usually due to extension issues)
/// Or if the expression is invalid, or if the result cannot be deserialized into the given type
///
/// # Example
///
/// ```rust
/// let result: i64 = rustyscript::evaluate("5 + 5").expect("The expression was invalid!");
/// assert_eq!(10, result);
/// ```
pub fn evaluate<T>(javascript: &str) -> Result<T, Error>
where
T: deno_core::serde::de::DeserializeOwned,
{
let mut runtime = Runtime::new(RuntimeOptions::default())?;
runtime.eval(javascript)
}
/// Validates the syntax of some JS
///
/// # Arguments
/// * `javascript` - A snippet of JS code
///
/// # Returns
/// A `Result` containing a boolean determining the validity of the JS
///
/// # Errors
/// Will return an error if the runtime cannot be started (usually due to extension issues)
/// Or if something went wrong and the validity could not be determined
///
/// # Example
///
/// ```rust
/// assert!(rustyscript::validate("5 + 5").expect("Something went wrong!"));
/// ```
pub fn validate(javascript: &str) -> Result<bool, Error> {
let module = Module::new("test.js", javascript);
let mut runtime = Runtime::new(RuntimeOptions::default())?;
match runtime.load_modules(&module, vec![]) {
Ok(_) => Ok(true),
Err(Error::Runtime(_) | Error::JsError(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// Imports a JS module into a new runtime
///
/// # Arguments
/// * `path` - Path to the JS module to import
///
/// # Returns
/// A `Result` containing a handle to the imported module,
/// or an error if something went wrong.
///
/// # Errors
/// Will return an error if the file cannot be found, execution fails, or the runtime
/// cannot be started (usually due to extension issues)
///
/// # Example
///
/// ```no_run
/// let mut module = rustyscript::import("js/my_module.js").expect("Something went wrong!");
/// ```
pub fn import(path: &str) -> Result<ModuleWrapper, Error> {
ModuleWrapper::new_from_file(path, RuntimeOptions::default())
}
/// Resolve a path to absolute path, relative to the current working directory
/// or an optional base directory
///
/// # Arguments
/// * `path` - A path
/// * `base_dir` - An optional base directory to resolve the path from
/// If not provided, the current working directory is used
///
/// # Errors
/// Will return an error if the given path is invalid
///
/// # Example
///
/// ```rust
/// let full_path = rustyscript::resolve_path("test.js", None).expect("Something went wrong!");
/// assert!(full_path.ends_with("test.js"));
/// ```
pub fn resolve_path(path: &str, base_dir: Option<&Path>) -> Result<String, Error> {
Ok(path.to_module_specifier(base_dir)?.to_string())
}
/// Explicitly initialize the V8 platform
/// Note that all runtimes must have a common parent thread that initalized the V8 platform
///
/// This is done automatically the first time [`Runtime::new`] is called,
/// but for multi-threaded applications, it may be necessary to call this function manually
pub fn init_platform(thread_pool_size: u32, idle_task_support: bool) {
let platform = deno_core::v8::Platform::new(thread_pool_size, idle_task_support);
deno_core::JsRuntime::init_platform(Some(platform.into()));
}
#[macro_use]
mod runtime_macros {
/// Map a series of values into a form which javascript functions can understand
/// Accepts a maximum of 16 arguments, of any combination of compatible types
/// For more than 16 arguments, use `big_json_args!` instead
///
/// NOTE: Since 0.6.0, this macro is now effectively a no-op
/// It simply builds a tuple reference from the provided arguments
///
/// You can also just pass a &tuple directly, or an &array, or even a single value
///
/// # Example
/// ```rust
/// use rustyscript::{ Runtime, RuntimeOptions, Module, json_args };
/// use std::time::Duration;
///
/// # fn main() -> Result<(), rustyscript::Error> {
/// let module = Module::new("test.js", "
/// function load(a, b) {
/// console.log(`Hello world: a=${a}, b=${b}`);
/// }
/// rustyscript.register_entrypoint(load);
/// ");
///
/// Runtime::execute_module(
/// &module, vec![],
/// Default::default(),
/// json_args!("test", 5)
/// )?;
/// # Ok(())
/// # }
/// ```
///
#[macro_export]
macro_rules! json_args {
($($arg:expr),*) => {
&($($arg),*)
};
}
/// Map a series of values into a form which javascript functions can understand
/// This forms a `Vec<serde_json::Value>` from the provided arguments
///
/// Useful if you need more than 16 arguments for a single function call
/// Warning: This macro is far slower than `json_args!` and should be used sparingly
/// Benchmarks place the performance difference at nearly 1,000 times slower!
///
/// # Example
/// ```rust
/// use rustyscript::{ Runtime, RuntimeOptions, Module, big_json_args };
/// use std::time::Duration;
///
/// # fn main() -> Result<(), rustyscript::Error> {
/// let module = Module::new("test.js", "
/// function load(a, b) {
/// console.log(`Hello world: a=${a}, b=${b}`);
/// }
/// rustyscript.register_entrypoint(load);
/// ");
///
/// Runtime::execute_module(
/// &module, vec![],
/// Default::default(),
/// big_json_args!("test", 5)
/// )?;
/// # Ok(())
/// # }
/// ```
///
#[macro_export]
macro_rules! big_json_args {
($($arg:expr),*) => {
&vec![
$($crate::deno_core::serde_json::Value::from($arg)),*
]
};
}
/// A simple helper macro to create a callback for use with `Runtime::register_function`
/// Takes care of deserializing arguments and serializing the result
///
/// # Example
/// ```rust
/// use rustyscript::{ Error, sync_callback };
/// let add = sync_callback!(
/// |a: i64, b: i64| {
/// Ok::<i64, Error>(a + b)
/// }
/// );
/// ```
#[macro_export]
macro_rules! sync_callback {
(|$($arg:ident: $arg_ty:ty),*| $body:expr) => {
|args: &[$crate::serde_json::Value]| {
let mut args = args.iter();
$(
let $arg: $arg_ty = match args.next() {
Some(arg) => $crate::serde_json::from_value(arg.clone())?,
None => return Err($crate::Error::Runtime("Invalid number of arguments".to_string())),
};
)*
let result = $body?;
$crate::serde_json::Value::try_from(result).map_err(|e| $crate::Error::Runtime(e.to_string()))
}
}
}
/// A simple helper macro to create a callback for use with `Runtime::register_async_function`
/// Takes care of deserializing arguments and serializing the result
///
/// # Example
/// ```rust
/// use rustyscript::{ Error, async_callback };
/// let add = async_callback!(
/// |a: i64, b: i64| async move {
/// Ok::<i64, Error>(a + b)
/// }
/// );
/// ```
#[macro_export]
macro_rules! async_callback {
(|$($arg:ident: $arg_ty:ty),*| $body:expr) => {
|args: Vec<$crate::serde_json::Value>| Box::pin(async move {
let mut args = args.iter();
$(
let $arg: $arg_ty = match args.next() {
Some(arg) => $crate::serde_json::from_value(arg.clone()).map_err(|e| $crate::Error::Runtime(e.to_string()))?,
None => return Err($crate::Error::Runtime("Invalid number of arguments".to_string())),
};
)*
// Now consume the future to inject JSON serialization
let result = $body.await?;
$crate::serde_json::Value::try_from(result).map_err(|e| $crate::Error::Runtime(e.to_string()))
})
}
}
}
#[cfg(test)]
mod test_runtime {
use super::*;
use deno_core::{futures::FutureExt, serde_json};
#[test]
fn test_callback() {
let add = sync_callback!(|a: i64, b: i64| { Ok::<i64, Error>(a + b) });
let add2 = async_callback!(|a: i64, b: i64| async move { Ok::<i64, Error>(a + b) });
let args = vec![
serde_json::Value::Number(5.into()),
serde_json::Value::Number(5.into()),
];
let result = add(&args).unwrap();
assert_eq!(serde_json::Value::Number(10.into()), result);
let result = add2(args).now_or_never().unwrap().unwrap();
assert_eq!(serde_json::Value::Number(10.into()), result);
}
#[test]
fn test_evaluate() {
assert_eq!(5, evaluate::<i64>("3 + 2").expect("invalid expression"));
evaluate::<i64>("a5; 3 + 2").expect_err("Expected an error");
}
#[test]
fn test_validate() {
assert!(validate("3 + 2").expect("invalid expression"));
assert!(!validate("5;+-").expect("invalid expression"));
}
#[test]
fn test_resolve_path() {
assert!(resolve_path("test.js", None)
.expect("invalid path")
.ends_with("test.js"));
}
}