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
#![doc = include_str!("../README.md")]
use anyhow::Result;
use deno_core::{FsModuleLoader, JsRuntime, RuntimeOptions};
use std::{collections::HashMap, fmt::Display, rc::Rc};
pub use deno_core::{anyhow, op};
pub use tokio::runtime::Runtime;
pub struct DenoRunner {
runtime: JsRuntime,
}
impl DenoRunner {
pub async fn run<C, K, V>(
mut self,
custom_code: C,
vars: Option<HashMap<K, V>>,
) -> Result<String>
where
C: ToString,
K: Display,
V: Display + std::fmt::Debug,
{
if let Some(vars) = vars {
for (key, value) in vars {
self.runtime
.execute_script("[runner]", &format!("let {} = {:?}", key, value))?;
}
}
let result = self
.runtime
.execute_script("code.js", &custom_code.to_string())?;
let mut scope = self.runtime.handle_scope();
unsafe { Ok(result.into_raw().as_ref().to_rust_string_lossy(&mut scope)) }
}
}
pub struct Builder {
pub ops: Vec<deno_core::OpDecl>,
}
impl Builder {
pub fn new() -> Self {
Self { ops: vec![] }
}
pub fn add_op(mut self, op: deno_core::OpDecl) -> Self {
self.ops.push(op);
self
}
pub fn build(self) -> DenoRunner {
let extensions = vec![
deno_console::init(),
deno_core::Extension::builder().ops(self.ops).build(),
];
let mut runtime = JsRuntime::new(RuntimeOptions {
module_loader: Some(Rc::new(FsModuleLoader)),
extensions,
..Default::default()
});
runtime
.execute_script("[deno:runtime.js]", include_str!("./runtime.js"))
.unwrap();
DenoRunner { runtime }
}
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! gen_test {
($code:expr, $value:expr, $expected:expr) => {{
let runner = Builder::default().build();
let vars = HashMap::from([("value", $value)]);
let actual = runner.run($code, Some(vars)).await.unwrap();
assert_eq!($expected, actual);
}};
}
#[tokio::test]
async fn monkey_test() {
gen_test!("value + \"hihi\"", "a", "ahihi");
gen_test!("let a = value + \"hihi\"; a", "a", "ahihi");
gen_test!("var out = \"hihi\"; out", "random", "hihi");
gen_test!("var out = value; out", "hihi", "hihi");
gen_test!("let out = parseInt(value) + 1; out", "1", "2");
gen_test!(
"let out = parseInt(value) + 1; out",
"this-is-not-a-number",
"NaN"
);
}
#[tokio::test]
async fn test_bind_string() {
let custom_code = r#"a + b"#;
let runner = Builder::default().build();
let vars = HashMap::from([("a", "11"), ("b", "22")]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "1122".to_string());
}
#[tokio::test]
async fn test_bind_numberic() {
let custom_code = r#"a + b"#;
let runner = Builder::default().build();
let vars = HashMap::from([("a", 1), ("b", 2)]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "3");
}
#[tokio::test]
async fn test_deno_console() {
let custom_code = r#"
console.log(value);
console.error(value);
value
"#;
let runner = Builder::default().build();
let vars = HashMap::from([("value", "hello")]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "hello");
}
#[tokio::test]
#[should_panic(expected = "ReferenceError: a is not defined")]
async fn test_exception() {
let custom_code = r#"
a + 1
"#;
let runner = Builder::default().build();
let vars = HashMap::from([("value", "")]);
let _ = runner.run(custom_code, Some(vars)).await.unwrap();
}
#[op]
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[op]
async fn add_async(a: i32, b: i32) -> i32 {
a + b
}
#[tokio::test]
async fn test_register_rust_function_to_js_function_sync() {
let custom_code = r#"
const out = Deno.core.opSync('add', 1, 2);
out
"#;
let runner = Builder::default().add_op(add::decl()).build();
let vars = HashMap::from([("value", "")]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "3");
}
#[tokio::test]
async fn test_register_rust_function_to_js_function_sync_global() {
let custom_code = r#"
const out = add(1, 2);
out
"#;
let runner = Builder::default().add_op(add::decl()).build();
let result = runner
.run::<&str, String, String>(custom_code, None)
.await
.unwrap();
assert_eq!(result, "3");
}
#[tokio::test]
async fn test_register_rust_function_to_js_function_async() {
let custom_code = r#"
(async() => {
return await Deno.core.opAsync('add_async', 1, 2)
})()
"#;
let runner = Builder::default().add_op(add_async::decl()).build();
let vars = HashMap::from([("value", "")]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "[object Promise]");
}
#[tokio::test]
async fn global_should_works() {
let custom_code = r#"
globalThis.a = 1;
globalThis.a
"#;
let runner = Builder::default().build();
let vars = HashMap::from([("value", "")]);
let result = runner.run(custom_code, Some(vars)).await.unwrap();
assert_eq!(result, "1");
}
}