use serde_json::{Value, json};
use crate::client::CdpClient;
use crate::error::{CdpError, Result};
use crate::types::EvaluateResult;
fn thrown_message(details: &Value) -> String {
let exception = &details["exception"];
if let Some(description) = exception["description"].as_str() {
return description
.lines()
.next()
.unwrap_or(description)
.to_string();
}
match &exception["value"] {
Value::Null => details["text"].as_str().unwrap_or("uncaught").to_string(),
Value::String(thrown) => thrown.clone(),
thrown => thrown.to_string(),
}
}
impl CdpClient {
pub async fn eval(&self, expression: &str) -> Result<String> {
let outcome = self.evaluate(expression).await?;
if let Some(details) = &outcome.exception_details {
return Err(CdpError::Protocol(format!(
"evaluation threw: {}",
thrown_message(details)
)));
}
Ok(outcome
.result
.value
.map(|v| match v {
Value::String(s) => s,
other => other.to_string(),
})
.unwrap_or_default())
}
pub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult> {
let result = self
.send_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
Ok(serde_json::from_value(result)?)
}
}