1use std::time::Duration;
24
25use anyhow::Result;
26use serde_json::Value;
27
28use crate::cli::env_resolver::Source;
29use crate::cli::route;
30use crate::cli::trace::CommandTrace;
31use crate::session::backend::open_backend;
32use crate::session::freshness;
33use crate::session::{with_scratch_recovery, PageSession};
34
35pub async fn run(
36 browser: Option<String>,
37 expression: String,
38 target: Option<String>,
39 json: bool,
40 await_promise: bool,
41 timeout_ms: u64,
42 max_age: String,
43) -> Result<()> {
44 let mut trace = CommandTrace::new("eval");
45 let result = run_inner(
46 browser,
47 expression,
48 target,
49 json,
50 await_promise,
51 timeout_ms,
52 max_age,
53 &mut trace,
54 )
55 .await;
56 trace.finish(result)
57}
58
59#[allow(clippy::too_many_arguments)]
60async fn run_inner(
61 browser: Option<String>,
62 expression: String,
63 target: Option<String>,
64 json: bool,
65 await_promise: bool,
66 timeout_ms: u64,
67 max_age: String,
68 trace: &mut CommandTrace,
69) -> Result<()> {
70 let timeout = Duration::from_millis(timeout_ms);
71 let max_age = freshness::parse_max_age(&max_age)?;
72
73 let r = route::preamble(browser, target.as_deref(), trace).await?;
74 let resolved = &r.resolved;
75
76 let value = match (r.tab_name.clone(), target) {
77 (Some(name), None) => {
80 trace.route("named-tab").tab_name(&name);
81 let expr = expression.clone();
82 route::run_named_tab(
83 &r,
84 &name,
85 "named tabs (`<browser>/<name>`) require a registered browser; \
86 external endpoints can't carry tab names",
87 move |b, target_id| {
88 let expr = expr.clone();
89 async move {
90 b.ensure_fresh(&target_id, max_age).await?;
91 b.evaluate(&target_id, &expr, await_promise, timeout).await
92 }
93 },
94 )
95 .await?
96 }
97 (None, None) => {
100 if matches!(resolved.source, Source::External) {
101 trace.route("direct");
105 let session =
106 PageSession::attach(&resolved.endpoint, resolved.engine, None).await?;
107 session.ensure_fresh(max_age).await?;
108 let value = session
109 .evaluate_with_timeout(&expression, await_promise, Some(timeout))
110 .await;
111 session.close().await;
112 value?
113 } else {
114 trace.route("scratch");
115 let browser_name = match &resolved.source {
116 Source::Registered { name } => name.clone(),
117 _ => unreachable!("Source::External branch handled above"),
118 };
119 let backend = open_backend(&resolved.endpoint, resolved.engine).await?;
120 let expr = expression.clone();
121 with_scratch_recovery(&backend, &r.registry, &browser_name, move |b, target_id| {
122 let expr = expr.clone();
123 async move {
124 b.ensure_fresh(&target_id, max_age).await?;
125 b.evaluate(&target_id, &expr, await_promise, timeout).await
126 }
127 })
128 .await?
129 }
130 }
131 (None, Some(regex)) => {
133 trace.route("target-regex");
134 let session =
135 PageSession::attach(&resolved.endpoint, resolved.engine, Some(®ex)).await?;
136 session.ensure_fresh(max_age).await?;
137 let value = session
138 .evaluate_with_timeout(&expression, await_promise, Some(timeout))
139 .await;
140 session.close().await;
141 value?
142 }
143 _ => unreachable!("mutex was checked above"),
144 };
145
146 println!("{}", format_output(&value, json));
147 Ok(())
148}
149
150fn format_output(v: &Value, json: bool) -> String {
151 if json {
152 serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string())
153 } else if let Some(s) = v.as_str() {
154 s.to_string()
155 } else {
156 serde_json::to_string(v).unwrap_or_else(|_| v.to_string())
157 }
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163 use serde_json::json;
164
165 #[test]
166 fn eval_returns_string_unquoted_in_text_mode() {
167 let v = json!("hello");
168 assert_eq!(format_output(&v, false), "hello");
169 }
170
171 #[test]
172 fn eval_returns_number_as_json() {
173 let v = json!(42);
174 assert_eq!(format_output(&v, false), "42");
175 }
176
177 #[test]
178 fn eval_returns_json_envelope_when_json_flag() {
179 let v = json!({"a": 1});
180 let out = format_output(&v, true);
181 let parsed: Value = serde_json::from_str(&out).expect("valid JSON");
182 assert_eq!(parsed, v);
183 assert!(out.contains("\"a\""));
184 }
185
186 #[test]
187 fn eval_null_text_mode() {
188 let v = json!(null);
189 assert_eq!(format_output(&v, false), "null");
190 }
191
192 #[test]
193 fn eval_bool_text_mode() {
194 assert_eq!(format_output(&json!(true), false), "true");
195 }
196
197 use crate::detect::Engine;
198 use crate::session::PageSession;
199 use futures_util::{SinkExt, StreamExt};
200 use tokio_tungstenite::tungstenite::Message;
201
202 async fn spawn_cdp_mock(targets: Vec<Value>, eval_value: Value) -> String {
203 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
204 let addr = listener.local_addr().unwrap();
205 tokio::spawn(async move {
206 let (stream, _) = listener.accept().await.unwrap();
207 let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
208 while let Some(Ok(Message::Text(t))) = ws.next().await {
209 let req: Value = serde_json::from_str(&t).unwrap();
210 let id = req["id"].as_u64().unwrap();
211 let method = req["method"].as_str().unwrap_or("");
212 let result = match method {
213 "Target.getTargets" => json!({"targetInfos": targets.clone()}),
214 "Target.attachToTarget" => json!({"sessionId": "S1"}),
215 "Runtime.evaluate" => json!({"result": {"value": eval_value.clone()}}),
216 _ => json!({}),
217 };
218 let resp = json!({"id": id, "result": result});
219 ws.send(Message::Text(resp.to_string())).await.unwrap();
220 }
221 });
222 format!("ws://{addr}")
223 }
224
225 #[tokio::test]
226 async fn eval_mock_returns_string() {
227 let url = spawn_cdp_mock(
228 vec![json!({"targetId":"a","type":"page","url":"https://example.com/"})],
229 json!("hello"),
230 )
231 .await;
232 let s = PageSession::attach(&url, Engine::Cdp, None).await.unwrap();
233 let v = s.evaluate("'hello'", false).await.unwrap();
234 s.close().await;
235 assert_eq!(format_output(&v, false), "hello");
236 }
237
238 #[tokio::test]
239 async fn eval_mock_returns_object_json() {
240 let url = spawn_cdp_mock(
241 vec![json!({"targetId":"a","type":"page","url":"https://example.com/"})],
242 json!({"a": 1}),
243 )
244 .await;
245 let s = PageSession::attach(&url, Engine::Cdp, None).await.unwrap();
246 let v = s.evaluate("({a:1})", false).await.unwrap();
247 s.close().await;
248 let out = format_output(&v, true);
249 let parsed: Value = serde_json::from_str(&out).unwrap();
250 assert_eq!(parsed, json!({"a": 1}));
251 }
252}