|
| 1 | +use rusty_jsc::JSContext; |
| 2 | +use rusty_jsc::JSObject; |
| 3 | +use rusty_jsc::JSValue; |
| 4 | + |
| 5 | +fn inner_log( |
| 6 | + loglevel: log::Level, |
| 7 | + context: JSContext, |
| 8 | + _function: JSObject, |
| 9 | + _this: JSObject, |
| 10 | + args: &[JSValue], |
| 11 | +) -> Result<JSValue, JSValue> { |
| 12 | + let out: Result<Vec<String>, JSValue> = args |
| 13 | + .iter() |
| 14 | + .map(|x| { |
| 15 | + let y = x.to_string(&context)?; |
| 16 | + Ok(y.to_string()) |
| 17 | + }) |
| 18 | + .collect(); |
| 19 | + let out = out?.join(" "); |
| 20 | + log::log!(loglevel, "{:?}", out); |
| 21 | + |
| 22 | + Ok(JSValue::undefined(&context)) |
| 23 | +} |
| 24 | + |
| 25 | +#[rusty_jsc::callback] |
| 26 | +fn debug(context: JSContext, function: JSObject, this: JSObject, args: &[JSValue]) { |
| 27 | + inner_log(log::Level::Debug, context, function, this, args) |
| 28 | +} |
| 29 | + |
| 30 | +#[rusty_jsc::callback] |
| 31 | +fn info(context: JSContext, function: JSObject, this: JSObject, args: &[JSValue]) { |
| 32 | + inner_log(log::Level::Info, context, function, this, args) |
| 33 | +} |
| 34 | + |
| 35 | +#[rusty_jsc::callback] |
| 36 | +fn warn(context: JSContext, function: JSObject, this: JSObject, args: &[JSValue]) { |
| 37 | + inner_log(log::Level::Warn, context, function, this, args) |
| 38 | +} |
| 39 | + |
| 40 | +#[rusty_jsc::callback] |
| 41 | +fn error(context: JSContext, function: JSObject, this: JSObject, args: &[JSValue]) { |
| 42 | + inner_log(log::Level::Error, context, function, this, args) |
| 43 | +} |
| 44 | + |
| 45 | +pub fn run(script: &str) -> Result<(), JSValue> { |
| 46 | + let mut context = JSContext::default(); |
| 47 | + |
| 48 | + let console = JSObject::new(&context); |
| 49 | + let callback = JSValue::callback(&context, Some(info)); |
| 50 | + console.set_property(&context, "log", callback)?; |
| 51 | + let callback = JSValue::callback(&context, Some(info)); |
| 52 | + console.set_property(&context, "info", callback)?; |
| 53 | + let callback = JSValue::callback(&context, Some(debug)); |
| 54 | + console.set_property(&context, "debug", callback)?; |
| 55 | + let callback = JSValue::callback(&context, Some(warn)); |
| 56 | + console.set_property(&context, "warn", callback)?; |
| 57 | + let callback = JSValue::callback(&context, Some(error)); |
| 58 | + console.set_property(&context, "error", callback)?; |
| 59 | + |
| 60 | + let global = context.get_global_object(); |
| 61 | + global.set_property(&context, "console", console.to_jsvalue())?; |
| 62 | + |
| 63 | + if let Ok(_value) = context.evaluate_script(script, 0) { |
| 64 | + () |
| 65 | + } |
| 66 | + Ok(()) |
| 67 | +} |
0 commit comments