use std::future::Future;
use std::time::Duration;
use anyhow::Result;
use serde_json::json;
use crate::cdp::CdpClient;
use crate::session::crash::evaluate_with_crash_detection;
pub async fn with_page_session<T, F, Fut>(
client: &CdpClient,
target_id: &str,
timeout: Duration,
f: F,
) -> Result<T>
where
F: FnOnce(String) -> Fut,
Fut: Future<Output = Result<T>>,
{
let session_id = client.attach_to_target(target_id).await?;
let _ = client
.send_with_session("Inspector.enable", json!({}), Some(&session_id))
.await;
let fut = f(session_id.clone());
let result =
evaluate_with_crash_detection(client, target_id, Some(&session_id), fut, Some(timeout))
.await;
let _ = client
.send(
"Target.detachFromTarget",
json!({ "sessionId": session_id }),
)
.await;
result
}