use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::oneshot;
use super::{
ActorCommand, DebuggerAdapterKind, DebuggerManager, DebuggerSession, DebuggerSnapshot, now_ms,
};
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerBrowserState {
pub url: Option<String>,
pub frame_id: Option<String>,
pub requests: Vec<BrowserNetworkRequest>,
pub websocket_frames: Vec<BrowserWebSocketFrame>,
pub page_events: Vec<BrowserPageEvent>,
pub mocks: Vec<BrowserMockRule>,
pub device: Option<String>,
pub throttle: Option<String>,
pub coverage: Option<BrowserCoverageSnapshot>,
pub flow_actions: Vec<BrowserFlowAction>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserFlowAction {
pub sequence: u64,
pub at: u64,
pub kind: String,
pub selector: Option<String>,
pub fallback_path: Option<String>,
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserNavigation {
pub action: String,
pub url: String,
pub frame_id: Option<String>,
pub ready_state: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserDomNode {
pub node_id: u64,
pub tag: String,
pub id: String,
pub class_name: String,
pub text: String,
pub attributes: Vec<(String, String)>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserStyle {
pub node_id: u64,
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserCookie {
pub name: String,
pub value: String,
pub domain: String,
pub path: String,
pub expires: f64,
pub size: u64,
pub http_only: bool,
pub secure: bool,
pub same_site: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserStorageEntry {
pub kind: String,
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserMetric {
pub name: String,
pub value: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserInteraction {
pub selector: String,
pub node_id: u64,
pub x: Option<f64>,
pub y: Option<f64>,
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserScreenshot {
pub png_base64: Option<String>,
pub artifact: DebuggerArtifact,
pub bytes: u64,
pub width: u64,
pub height: u64,
pub selector: Option<String>,
pub state: Option<String>,
pub full_page: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerArtifact {
pub id: String,
pub kind: String,
pub media_type: String,
pub bytes: u64,
pub path: String,
pub created_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserNetworkRequest {
pub id: String,
pub method: String,
pub url: String,
pub resource_type: String,
pub status: Option<u16>,
pub mime_type: Option<String>,
pub request_headers: Value,
pub response_headers: Value,
pub started_at: f64,
pub completed_at: Option<f64>,
pub encoded_bytes: Option<u64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserNetworkBody {
pub request_id: String,
pub body: String,
pub base64_encoded: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserWebSocketFrame {
pub id: u64,
pub request_id: String,
pub opcode: u64,
pub data: String,
pub at: f64,
pub direction: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserPageEvent {
pub id: u64,
pub name: String,
pub at: f64,
pub frame_id: Option<String>,
pub url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserMockRule {
pub id: String,
pub pattern: String,
pub body: String,
pub status: u16,
pub headers: Vec<(String, String)>,
pub created_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserCoverageRange {
pub start: u64,
pub end: u64,
pub count: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserCoverageEntry {
pub url: String,
pub total_bytes: u64,
pub used_bytes: u64,
pub used_percent: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BrowserCoverageSnapshot {
pub captured_at: u64,
pub entries: Vec<BrowserCoverageEntry>,
}
impl DebuggerManager {
async fn put_browser_state(
&self,
session: &DebuggerSession,
browser: DebuggerBrowserState,
) -> Result<(), String> {
let (reply, response) = oneshot::channel();
session
.commands
.send(ActorCommand::BrowserState { browser, reply })
.map_err(|_| format!("Debugger session \"{}\" is disconnected", session.id))?;
response
.await
.map_err(|_| "Debugger browser state actor stopped".to_string())
}
pub async fn browser_state(&self, id: &str) -> Result<DebuggerBrowserState, String> {
Ok(self.snapshot(id).await?.browser)
}
pub async fn browser_network(&self, id: &str) -> Result<Vec<BrowserNetworkRequest>, String> {
Ok(self.browser_state(id).await?.requests)
}
pub async fn browser_websocket_frames(
&self,
id: &str,
) -> Result<Vec<BrowserWebSocketFrame>, String> {
Ok(self.browser_state(id).await?.websocket_frames)
}
pub async fn browser_page_events(&self, id: &str) -> Result<Vec<BrowserPageEvent>, String> {
Ok(self.browser_state(id).await?.page_events)
}
pub(super) async fn initialize_browser_session(
&self,
session: &Arc<DebuggerSession>,
) -> Result<(), String> {
for method in [
"Page.enable",
"DOM.enable",
"Network.enable",
"CSS.enable",
"Performance.enable",
] {
session.send(method, json!({})).await?;
}
session
.send("Page.setLifecycleEventsEnabled", json!({"enabled": true}))
.await?;
let browser = session.state.borrow().browser.clone();
if !browser.mocks.is_empty() {
session
.send("Fetch.enable", json!({"patterns":[{"urlPattern":"*"}]}))
.await?;
}
if let Some(device) = browser.device.as_deref() {
self.browser_emulate(&session.id, device).await?;
}
if let Some(throttle) = browser.throttle.as_deref() {
self.browser_throttle(&session.id, throttle).await?;
}
Ok(())
}
async fn browser_session(&self, id: &str) -> Result<Arc<DebuggerSession>, String> {
let record = self.record(id)?;
if record.adapter != DebuggerAdapterKind::BrowserCdp {
return Err(format!("Debugger session \"{id}\" is not a page target"));
}
self.session(id).await
}
pub async fn browser_navigate(
&self,
id: &str,
action: &str,
target: Option<&str>,
timeout: Duration,
) -> Result<BrowserNavigation, String> {
let session = self.browser_session(id).await?;
let after_event = session
.state
.borrow()
.browser
.page_events
.last()
.map_or(0, |event| event.id);
let frame_id = match action {
"url" => {
let url = target.ok_or_else(|| "URL navigation requires a target".to_string())?;
let result = session.send("Page.navigate", json!({"url": url})).await?;
if let Some(error) = result.get("errorText").and_then(Value::as_str) {
return Err(format!("Navigation failed: {error}"));
}
result
.get("frameId")
.and_then(Value::as_str)
.map(ToString::to_string)
}
"reload" => {
session.send("Page.reload", json!({})).await?;
None
}
"back" | "forward" => {
let history = session.send("Page.getNavigationHistory", json!({})).await?;
let current = history
.get("currentIndex")
.and_then(Value::as_i64)
.unwrap_or(0);
let entries = history
.get("entries")
.and_then(Value::as_array)
.ok_or_else(|| "Browser returned no navigation history".to_string())?;
let index = if action == "back" {
current - 1
} else {
current + 1
};
let entry = usize::try_from(index)
.ok()
.and_then(|index| entries.get(index))
.ok_or_else(|| format!("No {action} navigation history entry"))?;
let entry_id = entry
.get("id")
.and_then(Value::as_i64)
.ok_or_else(|| "History entry has no identity".to_string())?;
session
.send("Page.navigateToHistoryEntry", json!({"entryId": entry_id}))
.await?;
None
}
other => return Err(format!("Unknown browser navigation action \"{other}\"")),
};
let ready_state = self
.wait_for_browser_ready(&session, after_event, timeout)
.await?;
let url = self.browser_url(&session).await?;
Ok(BrowserNavigation {
action: action.to_string(),
url,
frame_id,
ready_state,
})
}
async fn browser_url(&self, session: &DebuggerSession) -> Result<String, String> {
let result = session
.send(
"Runtime.evaluate",
json!({"expression":"location.href","returnByValue":true}),
)
.await?;
Ok(result
.pointer("/result/value")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string())
}
async fn wait_for_browser_ready(
&self,
session: &DebuggerSession,
after_event: u64,
timeout: Duration,
) -> Result<String, String> {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let result = session
.send(
"Runtime.evaluate",
json!({"expression":"document.readyState","returnByValue":true}),
)
.await?;
let state = result
.pointer("/result/value")
.and_then(Value::as_str)
.unwrap_or("unavailable");
let navigated = session
.state
.borrow()
.browser
.page_events
.iter()
.any(|event| event.id > after_event && event.name == "frameNavigated");
if navigated && matches!(state, "interactive" | "complete") {
return Ok(state.to_string());
}
if tokio::time::Instant::now() >= deadline {
return Err(format!(
"Timed out waiting for page readiness; state was {state}"
));
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
}
async fn browser_node(&self, session: &DebuggerSession, selector: &str) -> Result<u64, String> {
if selector.trim().is_empty() {
return Err("CSS selector cannot be empty".to_string());
}
let document = session
.send("DOM.getDocument", json!({"depth":0,"pierce":true}))
.await?;
let root = document
.pointer("/root/nodeId")
.and_then(Value::as_u64)
.ok_or_else(|| "Browser returned no DOM document root".to_string())?;
let result = session
.send(
"DOM.querySelector",
json!({"nodeId":root,"selector":selector}),
)
.await?;
result
.get("nodeId")
.and_then(Value::as_u64)
.filter(|id| *id != 0)
.ok_or_else(|| format!("No element matches selector \"{selector}\""))
}
pub async fn browser_dom(
&self,
id: &str,
selector: &str,
) -> Result<Vec<BrowserDomNode>, String> {
let session = self.browser_session(id).await?;
let document = session
.send("DOM.getDocument", json!({"depth":0,"pierce":true}))
.await?;
let root = document
.pointer("/root/nodeId")
.and_then(Value::as_u64)
.ok_or_else(|| "Browser returned no DOM document root".to_string())?;
let result = session
.send(
"DOM.querySelectorAll",
json!({"nodeId":root,"selector":selector}),
)
.await?;
let mut nodes = Vec::new();
for node_id in result
.get("nodeIds")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_u64)
.take(1_000)
{
let description = session
.send("DOM.describeNode", json!({"nodeId":node_id}))
.await?;
let node = description
.get("node")
.ok_or_else(|| "Browser returned no DOM node description".to_string())?;
let attributes = node
.get("attributes")
.and_then(Value::as_array)
.map(|values| {
values
.chunks(2)
.filter_map(|pair| {
Some((
pair.first()?.as_str()?.to_string(),
pair.get(1)?.as_str()?.to_string(),
))
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
let resolved = session
.send("DOM.resolveNode", json!({"nodeId":node_id}))
.await?;
let text = if let Some(object_id) =
resolved.pointer("/object/objectId").and_then(Value::as_str)
{
session
.send(
"Runtime.callFunctionOn",
json!({
"objectId":object_id,
"functionDeclaration":"function(){return (this.textContent || '').trim().slice(0,1000)}",
"returnByValue":true
}),
)
.await?
.pointer("/result/value")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
} else {
String::new()
};
nodes.push(BrowserDomNode {
node_id,
tag: node
.get("nodeName")
.and_then(Value::as_str)
.unwrap_or_default()
.to_ascii_lowercase(),
id: attribute(&attributes, "id"),
class_name: attribute(&attributes, "class"),
text,
attributes,
});
}
Ok(nodes)
}
pub async fn browser_styles(
&self,
id: &str,
selector: &str,
) -> Result<Vec<BrowserStyle>, String> {
let session = self.browser_session(id).await?;
let node_id = self.browser_node(&session, selector).await?;
let result = session
.send("CSS.getComputedStyleForNode", json!({"nodeId":node_id}))
.await?;
Ok(result
.get("computedStyle")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|style| {
Some(BrowserStyle {
node_id,
name: style.get("name")?.as_str()?.to_string(),
value: style.get("value")?.as_str()?.to_string(),
})
})
.collect())
}
pub async fn browser_cookies(&self, id: &str) -> Result<Vec<BrowserCookie>, String> {
let session = self.browser_session(id).await?;
let result = session.send("Network.getCookies", json!({})).await?;
Ok(result
.get("cookies")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|cookie| {
Some(BrowserCookie {
name: cookie.get("name")?.as_str()?.to_string(),
value: cookie.get("value")?.as_str()?.to_string(),
domain: cookie.get("domain")?.as_str()?.to_string(),
path: cookie.get("path")?.as_str()?.to_string(),
expires: cookie.get("expires").and_then(Value::as_f64).unwrap_or(0.0),
size: cookie.get("size").and_then(Value::as_u64).unwrap_or(0),
http_only: cookie
.get("httpOnly")
.and_then(Value::as_bool)
.unwrap_or(false),
secure: cookie
.get("secure")
.and_then(Value::as_bool)
.unwrap_or(false),
same_site: cookie
.get("sameSite")
.and_then(Value::as_str)
.map(ToString::to_string),
})
})
.collect())
}
pub async fn browser_storage(
&self,
id: &str,
kind: &str,
) -> Result<Vec<BrowserStorageEntry>, String> {
let session = self.browser_session(id).await?;
let object = match kind {
"local" => "localStorage",
"session" => "sessionStorage",
other => return Err(format!("Unknown browser storage kind \"{other}\"")),
};
let expression = format!("Object.entries({object})");
let result = session
.send(
"Runtime.evaluate",
json!({"expression":expression,"returnByValue":true}),
)
.await?;
Ok(result
.pointer("/result/value")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let pair = entry.as_array()?;
Some(BrowserStorageEntry {
kind: kind.to_string(),
key: pair.first()?.as_str()?.to_string(),
value: pair.get(1)?.as_str()?.to_string(),
})
})
.collect())
}
pub async fn browser_performance(&self, id: &str) -> Result<Vec<BrowserMetric>, String> {
let session = self.browser_session(id).await?;
let result = session.send("Performance.getMetrics", json!({})).await?;
Ok(result
.get("metrics")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|metric| {
Some(BrowserMetric {
name: metric.get("name")?.as_str()?.to_string(),
value: metric.get("value")?.as_f64()?,
})
})
.collect())
}
pub async fn browser_click(
&self,
id: &str,
selector: &str,
) -> Result<BrowserInteraction, String> {
let session = self.browser_session(id).await?;
let node_id = self.browser_node(&session, selector).await?;
session
.send("DOM.scrollIntoViewIfNeeded", json!({"nodeId":node_id}))
.await?;
let box_model = session
.send("DOM.getBoxModel", json!({"nodeId":node_id}))
.await?;
let quad = box_model
.pointer("/model/content")
.and_then(Value::as_array)
.ok_or_else(|| format!("Element \"{selector}\" has no clickable box"))?;
let coordinates = quad.iter().filter_map(Value::as_f64).collect::<Vec<_>>();
if coordinates.len() != 8 {
return Err(format!(
"Element \"{selector}\" has an invalid clickable box"
));
}
let x = (coordinates[0] + coordinates[2] + coordinates[4] + coordinates[6]) / 4.0;
let y = (coordinates[1] + coordinates[3] + coordinates[5] + coordinates[7]) / 4.0;
for (kind, button) in [
("mouseMoved", None),
("mousePressed", Some("left")),
("mouseReleased", Some("left")),
] {
let mut params = json!({"type":kind,"x":x,"y":y,"clickCount":1});
if let Some(button) = button {
params["button"] = Value::String(button.to_string());
}
session.send("Input.dispatchMouseEvent", params).await?;
}
Ok(BrowserInteraction {
selector: selector.to_string(),
node_id,
x: Some(x),
y: Some(y),
value: None,
})
}
pub async fn browser_type(
&self,
id: &str,
selector: &str,
text: &str,
) -> Result<BrowserInteraction, String> {
let session = self.browser_session(id).await?;
let node_id = self.browser_node(&session, selector).await?;
session.send("DOM.focus", json!({"nodeId":node_id})).await?;
for character in text.chars() {
let text = character.to_string();
session
.send(
"Input.dispatchKeyEvent",
json!({"type":"keyDown","text":text}),
)
.await?;
session
.send(
"Input.dispatchKeyEvent",
json!({"type":"keyUp","text":text}),
)
.await?;
}
Ok(BrowserInteraction {
selector: selector.to_string(),
node_id,
x: None,
y: None,
value: Some(text.to_string()),
})
}
pub async fn browser_select(
&self,
id: &str,
selector: &str,
value: &str,
) -> Result<BrowserInteraction, String> {
let session = self.browser_session(id).await?;
let node_id = self.browser_node(&session, selector).await?;
let resolved = session
.send("DOM.resolveNode", json!({"nodeId":node_id}))
.await?;
let object_id = resolved
.pointer("/object/objectId")
.and_then(Value::as_str)
.ok_or_else(|| format!("Element \"{selector}\" has no runtime object"))?;
let result = session
.send(
"Runtime.callFunctionOn",
json!({
"objectId":object_id,
"functionDeclaration":"function(value){this.value=value;this.dispatchEvent(new Event('input',{bubbles:true}));this.dispatchEvent(new Event('change',{bubbles:true}));return this.value}",
"arguments":[{"value":value}],
"returnByValue":true
}),
)
.await?;
let selected = result
.pointer("/result/value")
.and_then(Value::as_str)
.unwrap_or_default();
if selected != value {
return Err(format!(
"Selector \"{selector}\" did not accept option value \"{value}\""
));
}
Ok(BrowserInteraction {
selector: selector.to_string(),
node_id,
x: None,
y: None,
value: Some(value.to_string()),
})
}
pub async fn browser_screenshot(
&self,
id: &str,
selector: Option<&str>,
full_page: bool,
viewport: Option<(u64, u64)>,
state: Option<&str>,
inline: bool,
) -> Result<BrowserScreenshot, String> {
let session = self.browser_session(id).await?;
if state.is_some() && selector.is_none() {
return Err("A forced screenshot state requires a selector".to_string());
}
if let Some(state) = state
&& !matches!(state, "hover" | "active" | "focus" | "visited")
{
return Err(format!("Unknown forced screenshot state \"{state}\""));
}
let prior_device = session.state.borrow().browser.device.clone();
if let Some((width, height)) = viewport {
session
.send(
"Emulation.setDeviceMetricsOverride",
json!({
"width":width,
"height":height,
"deviceScaleFactor":1,
"mobile":false
}),
)
.await?;
}
let mut forced_node = None;
let capture = async {
let clip = if let Some(selector) = selector {
let node_id = self.browser_node(&session, selector).await?;
if let Some(state) = state {
session
.send(
"CSS.forcePseudoState",
json!({"nodeId":node_id,"forcedPseudoClasses":[state]}),
)
.await?;
forced_node = Some(node_id);
}
let box_model = session
.send("DOM.getBoxModel", json!({"nodeId":node_id}))
.await?;
let border = box_model
.pointer("/model/border")
.and_then(Value::as_array)
.ok_or_else(|| format!("Element \"{selector}\" has no capture box"))?
.iter()
.filter_map(Value::as_f64)
.collect::<Vec<_>>();
Some(quad_clip(&border)?)
} else if full_page {
let metrics = session.send("Page.getLayoutMetrics", json!({})).await?;
Some(json!({
"x":0,
"y":0,
"width":metrics.pointer("/cssContentSize/width").or_else(|| metrics.pointer("/contentSize/width")).and_then(Value::as_f64).unwrap_or(0.0),
"height":metrics.pointer("/cssContentSize/height").or_else(|| metrics.pointer("/contentSize/height")).and_then(Value::as_f64).unwrap_or(0.0),
"scale":1
}))
} else {
None
};
let mut params =
json!({"format":"png","fromSurface":true,"captureBeyondViewport":full_page});
if let Some(clip) = clip {
params["clip"] = clip;
}
let result = session.send("Page.captureScreenshot", params).await?;
let png_base64 = result
.get("data")
.and_then(Value::as_str)
.ok_or_else(|| "Browser returned no PNG screenshot bytes".to_string())?
.to_string();
let bytes = base64::engine::general_purpose::STANDARD
.decode(&png_base64)
.map_err(|error| format!("Browser returned invalid PNG base64: {error}"))?;
let (width, height) = png_dimensions(&bytes)?;
let record = self.record(id)?;
let artifact = self.store.put_debugger_artifact(
id,
record.execution_id.as_deref(),
"browser_screenshot",
"image/png",
&bytes,
)?;
Ok(BrowserScreenshot {
png_base64: inline.then_some(png_base64),
artifact,
bytes: bytes.len() as u64,
width,
height,
selector: selector.map(ToString::to_string),
state: state.map(ToString::to_string),
full_page,
})
}
.await;
let mut cleanup_error = None;
if let Some(node_id) = forced_node
&& let Err(error) = session
.send(
"CSS.forcePseudoState",
json!({"nodeId":node_id,"forcedPseudoClasses":[]}),
)
.await
{
cleanup_error = Some(format!(
"Could not restore forced screenshot state: {error}"
));
}
if viewport.is_some() {
let restored = match prior_device {
Some(device) => self.browser_emulate(id, &device).await.map(|_| ()),
None => session
.send("Emulation.clearDeviceMetricsOverride", json!({}))
.await
.map(|_| ()),
};
if let Err(error) = restored {
cleanup_error = Some(format!("Could not restore screenshot viewport: {error}"));
}
}
match (capture, cleanup_error) {
(_, Some(error)) => Err(error),
(result, None) => result,
}
}
pub async fn browser_network_body(
&self,
id: &str,
request_id: &str,
) -> Result<BrowserNetworkBody, String> {
let session = self.browser_session(id).await?;
let result = session
.send("Network.getResponseBody", json!({"requestId":request_id}))
.await?;
Ok(BrowserNetworkBody {
request_id: request_id.to_string(),
body: result
.get("body")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
base64_encoded: result
.get("base64Encoded")
.and_then(Value::as_bool)
.unwrap_or(false),
})
}
pub async fn browser_emulate(&self, id: &str, preset: &str) -> Result<String, String> {
let session = self.browser_session(id).await?;
if preset == "reset" {
session
.send("Emulation.clearDeviceMetricsOverride", json!({}))
.await?;
session
.send(
"Emulation.setTouchEmulationEnabled",
json!({"enabled":false}),
)
.await?;
let mut browser = session.state.borrow().browser.clone();
browser.device = None;
self.put_browser_state(&session, browser).await?;
return Ok("reset".to_string());
}
let (width, height, scale, mobile, user_agent) = device_preset(preset)?;
session
.send(
"Emulation.setDeviceMetricsOverride",
json!({
"width":width,"height":height,"deviceScaleFactor":scale,"mobile":mobile
}),
)
.await?;
session
.send(
"Emulation.setUserAgentOverride",
json!({"userAgent":user_agent}),
)
.await?;
session
.send(
"Emulation.setTouchEmulationEnabled",
json!({"enabled":mobile}),
)
.await?;
let mut browser = session.state.borrow().browser.clone();
browser.device = Some(preset.to_string());
self.put_browser_state(&session, browser).await?;
Ok(preset.to_string())
}
pub async fn browser_throttle(&self, id: &str, preset: &str) -> Result<String, String> {
let session = self.browser_session(id).await?;
let (offline, latency, download, upload) = throttle_preset(preset)?;
session
.send(
"Network.emulateNetworkConditions",
json!({
"offline":offline,
"latency":latency,
"downloadThroughput":download,
"uploadThroughput":upload
}),
)
.await?;
let mut browser = session.state.borrow().browser.clone();
browser.throttle = (preset != "off").then(|| preset.to_string());
self.put_browser_state(&session, browser).await?;
Ok(preset.to_string())
}
pub async fn browser_mock(
&self,
id: &str,
pattern: String,
body: String,
status: u16,
headers: Vec<(String, String)>,
) -> Result<BrowserMockRule, String> {
if pattern.is_empty() {
return Err("Browser mock pattern cannot be empty".to_string());
}
if !(100..=599).contains(&status) {
return Err("Browser mock status must be from 100 through 599".to_string());
}
let session = self.browser_session(id).await?;
let rule = BrowserMockRule {
id: uuid::Uuid::now_v7().to_string(),
pattern: pattern.clone(),
body,
status,
headers,
created_at: now_ms(),
};
let mut browser = session.state.borrow().browser.clone();
let had_mocks = !browser.mocks.is_empty();
browser.mocks.retain(|existing| existing.pattern != pattern);
browser.mocks.push(rule.clone());
session
.send("Fetch.enable", json!({"patterns":[{"urlPattern":"*"}]}))
.await?;
if let Err(error) = self.put_browser_state(&session, browser).await {
if !had_mocks {
let _ = session.send("Fetch.disable", json!({})).await;
}
return Err(error);
}
Ok(rule)
}
pub async fn browser_unmock(
&self,
id: &str,
pattern: Option<&str>,
) -> Result<Vec<BrowserMockRule>, String> {
let session = self.browser_session(id).await?;
let mut browser = session.state.borrow().browser.clone();
if let Some(pattern) = pattern {
let before = browser.mocks.len();
browser.mocks.retain(|rule| rule.pattern != pattern);
if browser.mocks.len() == before {
return Err(format!("No browser mock matches \"{pattern}\""));
}
} else {
browser.mocks.clear();
}
let remaining = browser.mocks.clone();
if remaining.is_empty() {
session.send("Fetch.disable", json!({})).await?;
}
if let Err(error) = self.put_browser_state(&session, browser).await {
if remaining.is_empty() {
let _ = session
.send("Fetch.enable", json!({"patterns":[{"urlPattern":"*"}]}))
.await;
}
return Err(error);
}
Ok(remaining)
}
pub async fn browser_coverage_start(&self, id: &str) -> Result<(), String> {
let session = self.browser_session(id).await?;
session.send("Profiler.enable", json!({})).await?;
session
.send(
"Profiler.startPreciseCoverage",
json!({"callCount":true,"detailed":true}),
)
.await?;
let _ = session.send("CSS.startRuleUsageTracking", json!({})).await;
Ok(())
}
pub async fn browser_coverage_stop(&self, id: &str) -> Result<BrowserCoverageSnapshot, String> {
let session = self.browser_session(id).await?;
let javascript = session
.send("Profiler.takePreciseCoverage", json!({}))
.await?;
let css = session
.send("CSS.takeCoverageDelta", json!({}))
.await
.unwrap_or_else(|_| json!({"coverage":[]}));
let _ = session
.send("Profiler.stopPreciseCoverage", json!({}))
.await;
let _ = session.send("Profiler.disable", json!({})).await;
let _ = session.send("CSS.stopRuleUsageTracking", json!({})).await;
let snapshot = coverage_snapshot(&javascript, &css);
let mut browser = session.state.borrow().browser.clone();
browser.coverage = Some(snapshot.clone());
self.put_browser_state(&session, browser).await?;
Ok(snapshot)
}
}
fn attribute(attributes: &[(String, String)], name: &str) -> String {
attributes
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.clone())
.unwrap_or_default()
}
fn quad_clip(quad: &[f64]) -> Result<Value, String> {
if quad.len() != 8 {
return Err("Browser returned an invalid capture quadrilateral".to_string());
}
let min_x = quad
.iter()
.step_by(2)
.copied()
.fold(f64::INFINITY, f64::min);
let max_x = quad
.iter()
.step_by(2)
.copied()
.fold(f64::NEG_INFINITY, f64::max);
let min_y = quad
.iter()
.skip(1)
.step_by(2)
.copied()
.fold(f64::INFINITY, f64::min);
let max_y = quad
.iter()
.skip(1)
.step_by(2)
.copied()
.fold(f64::NEG_INFINITY, f64::max);
Ok(json!({"x":min_x,"y":min_y,"width":max_x-min_x,"height":max_y-min_y,"scale":1}))
}
fn png_dimensions(bytes: &[u8]) -> Result<(u64, u64), String> {
if bytes.len() < 24 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" {
return Err("Browser screenshot is not a PNG image".to_string());
}
Ok((
u32::from_be_bytes(bytes[16..20].try_into().expect("PNG width slice")) as u64,
u32::from_be_bytes(bytes[20..24].try_into().expect("PNG height slice")) as u64,
))
}
fn device_preset(preset: &str) -> Result<(u64, u64, f64, bool, &'static str), String> {
match preset {
"iphone-14" => Ok((
390,
844,
3.0,
true,
"Mozilla/5.0 (iPhone) AppleWebKit/605.1.15 Mobile Safari/604.1",
)),
"iphone-se" => Ok((
375,
667,
2.0,
true,
"Mozilla/5.0 (iPhone) AppleWebKit/605.1.15 Mobile Safari/604.1",
)),
"ipad" => Ok((
810,
1080,
2.0,
true,
"Mozilla/5.0 (iPad) AppleWebKit/605.1.15 Mobile Safari/604.1",
)),
"pixel-7" => Ok((
412,
915,
2.625,
true,
"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 Chrome Mobile Safari/537.36",
)),
other => Err(format!("Unknown device preset \"{other}\"")),
}
}
fn throttle_preset(preset: &str) -> Result<(bool, i64, i64, i64), String> {
match preset {
"3g" => Ok((false, 100, 750 * 1024, 250 * 1024)),
"slow-3g" => Ok((false, 2_000, 50 * 1024, 50 * 1024)),
"fast-3g" => Ok((false, 562, 180 * 1024, 86_400)),
"4g" => Ok((false, 20, 4 * 1024 * 1024, 3 * 1024 * 1024)),
"offline" => Ok((true, 0, 0, 0)),
"off" => Ok((false, 0, -1, -1)),
other => Err(format!("Unknown throttle preset \"{other}\"")),
}
}
fn coverage_snapshot(javascript: &Value, css: &Value) -> BrowserCoverageSnapshot {
let mut entries = Vec::new();
for script in javascript
.get("result")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let mut total = 0_u64;
let mut used = 0_u64;
for range in script
.get("functions")
.and_then(Value::as_array)
.into_iter()
.flatten()
.flat_map(|function| {
function
.get("ranges")
.and_then(Value::as_array)
.into_iter()
.flatten()
})
{
let start = range
.get("startOffset")
.and_then(Value::as_u64)
.unwrap_or(0);
let end = range
.get("endOffset")
.and_then(Value::as_u64)
.unwrap_or(start);
let bytes = end.saturating_sub(start);
total = total.saturating_add(bytes);
if range.get("count").and_then(Value::as_u64).unwrap_or(0) > 0 {
used = used.saturating_add(bytes);
}
}
if total > 0 {
entries.push(BrowserCoverageEntry {
url: script
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
total_bytes: total,
used_bytes: used,
used_percent: used as f64 / total as f64 * 100.0,
});
}
}
for entry in css
.get("coverage")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let start = entry
.get("startOffset")
.and_then(Value::as_u64)
.unwrap_or(0);
let end = entry
.get("endOffset")
.and_then(Value::as_u64)
.unwrap_or(start);
let total = end.saturating_sub(start);
if total > 0 {
let used = entry.get("used").and_then(Value::as_bool).unwrap_or(false);
entries.push(BrowserCoverageEntry {
url: format!(
"css:{}",
entry
.get("styleSheetId")
.and_then(Value::as_str)
.unwrap_or_default()
),
total_bytes: total,
used_bytes: if used { total } else { 0 },
used_percent: if used { 100.0 } else { 0.0 },
});
}
}
BrowserCoverageSnapshot {
captured_at: now_ms(),
entries,
}
}
pub(super) fn update_browser_state(
method: &str,
params: Option<&Value>,
snapshot: &mut DebuggerSnapshot,
) -> bool {
let Some(params) = params else {
return false;
};
match method {
"Network.requestWillBeSent" => {
let id = params
.get("requestId")
.and_then(Value::as_str)
.unwrap_or_default();
snapshot.browser.requests.retain(|request| request.id != id);
snapshot.browser.requests.push(BrowserNetworkRequest {
id: id.to_string(),
method: params
.pointer("/request/method")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
url: params
.pointer("/request/url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
resource_type: params
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
status: None,
mime_type: None,
request_headers: params
.pointer("/request/headers")
.cloned()
.unwrap_or_else(|| json!({})),
response_headers: json!({}),
started_at: params
.get("timestamp")
.and_then(Value::as_f64)
.unwrap_or_default(),
completed_at: None,
encoded_bytes: None,
error: None,
});
retain_browser(&mut snapshot.browser.requests, 2_000);
true
}
"Network.responseReceived" => {
if let Some(request) = browser_request_mut(snapshot, params) {
request.status = params
.pointer("/response/status")
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok());
request.mime_type = params
.pointer("/response/mimeType")
.and_then(Value::as_str)
.map(ToString::to_string);
request.response_headers = params
.pointer("/response/headers")
.cloned()
.unwrap_or_else(|| json!({}));
}
true
}
"Network.loadingFinished" => {
if let Some(request) = browser_request_mut(snapshot, params) {
request.completed_at = params.get("timestamp").and_then(Value::as_f64);
request.encoded_bytes = params
.get("encodedDataLength")
.and_then(Value::as_f64)
.map(|value| value.max(0.0) as u64);
}
true
}
"Network.loadingFailed" => {
if let Some(request) = browser_request_mut(snapshot, params) {
request.completed_at = params.get("timestamp").and_then(Value::as_f64);
request.error = params
.get("errorText")
.and_then(Value::as_str)
.map(ToString::to_string);
}
true
}
"Network.webSocketFrameReceived" | "Network.webSocketFrameSent" => {
let id = snapshot
.browser
.websocket_frames
.last()
.map_or(1, |frame| frame.id + 1);
snapshot
.browser
.websocket_frames
.push(BrowserWebSocketFrame {
id,
request_id: params
.get("requestId")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
opcode: params
.pointer("/response/opcode")
.and_then(Value::as_u64)
.unwrap_or(0),
data: params
.pointer("/response/payloadData")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
at: params
.get("timestamp")
.and_then(Value::as_f64)
.unwrap_or_default(),
direction: if method.ends_with("Received") {
"received".to_string()
} else {
"sent".to_string()
},
});
retain_browser(&mut snapshot.browser.websocket_frames, 2_000);
true
}
"Page.lifecycleEvent" => {
let id = snapshot
.browser
.page_events
.last()
.map_or(1, |event| event.id + 1);
snapshot.browser.page_events.push(BrowserPageEvent {
id,
name: params
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
at: params
.get("timestamp")
.and_then(Value::as_f64)
.unwrap_or_default(),
frame_id: params
.get("frameId")
.and_then(Value::as_str)
.map(ToString::to_string),
url: snapshot.browser.url.clone(),
});
retain_browser(&mut snapshot.browser.page_events, 2_000);
true
}
"Page.frameNavigated" => {
if params.pointer("/frame/parentId").is_some() {
return false;
}
snapshot.browser.url = params
.pointer("/frame/url")
.and_then(Value::as_str)
.map(ToString::to_string);
snapshot.browser.frame_id = params
.pointer("/frame/id")
.and_then(Value::as_str)
.map(ToString::to_string);
let id = snapshot
.browser
.page_events
.last()
.map_or(1, |event| event.id + 1);
snapshot.browser.page_events.push(BrowserPageEvent {
id,
name: "frameNavigated".to_string(),
at: now_ms() as f64,
frame_id: snapshot.browser.frame_id.clone(),
url: snapshot.browser.url.clone(),
});
retain_browser(&mut snapshot.browser.page_events, 2_000);
true
}
"Runtime.bindingCalled"
if params.get("name").and_then(Value::as_str) == Some("__apoc_flow__") =>
{
let Some(payload) = params
.get("payload")
.and_then(Value::as_str)
.and_then(|payload| serde_json::from_str::<Value>(payload).ok())
else {
return false;
};
let kind = payload
.get("kind")
.and_then(Value::as_str)
.unwrap_or_default();
if !matches!(kind, "click" | "input" | "keypress" | "scroll") {
return false;
}
let sequence = snapshot
.browser
.flow_actions
.last()
.map_or(1, |action| action.sequence + 1);
snapshot.browser.flow_actions.push(BrowserFlowAction {
sequence,
at: now_ms(),
kind: kind.to_string(),
selector: payload
.get("selector")
.and_then(Value::as_str)
.map(ToString::to_string),
fallback_path: payload
.get("fallbackPath")
.and_then(Value::as_str)
.map(ToString::to_string),
value: payload
.get("value")
.and_then(Value::as_str)
.map(ToString::to_string),
});
retain_browser(&mut snapshot.browser.flow_actions, 2_000);
true
}
_ => false,
}
}
fn browser_request_mut<'a>(
snapshot: &'a mut DebuggerSnapshot,
params: &Value,
) -> Option<&'a mut BrowserNetworkRequest> {
let id = params.get("requestId").and_then(Value::as_str)?;
snapshot
.browser
.requests
.iter_mut()
.find(|request| request.id == id)
}
fn retain_browser<T>(values: &mut Vec<T>, limit: usize) {
if values.len() > limit {
values.drain(..values.len() - limit);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retains_network_failures_websocket_frames_and_navigation_events() {
let mut snapshot = DebuggerSnapshot::default();
assert!(update_browser_state(
"Network.requestWillBeSent",
Some(&json!({
"requestId":"request-1",
"timestamp":1.0,
"type":"Fetch",
"request":{"method":"GET","url":"https://example.test/fail","headers":{}}
})),
&mut snapshot,
));
assert!(update_browser_state(
"Network.loadingFailed",
Some(&json!({
"requestId":"request-1",
"timestamp":2.0,
"errorText":"net::ERR_CONNECTION_REFUSED"
})),
&mut snapshot,
));
for (method, direction, data) in [
("Network.webSocketFrameSent", "sent", "hello"),
("Network.webSocketFrameReceived", "received", "world"),
] {
assert!(update_browser_state(
method,
Some(&json!({
"requestId":"socket-1",
"timestamp":3.0,
"response":{"opcode":1,"payloadData":data}
})),
&mut snapshot,
));
assert_eq!(
snapshot.browser.websocket_frames.last().unwrap().direction,
direction
);
}
assert!(!update_browser_state(
"Page.frameNavigated",
Some(
&json!({"frame":{"id":"frame-child","parentId":"frame-1","url":"https://example.test/frame"}})
),
&mut snapshot,
));
assert!(snapshot.browser.page_events.is_empty());
assert!(snapshot.browser.url.is_none());
assert!(update_browser_state(
"Page.frameNavigated",
Some(&json!({"frame":{"id":"frame-1","url":"https://example.test/next"}})),
&mut snapshot,
));
assert_eq!(snapshot.browser.requests.len(), 1);
assert_eq!(
snapshot.browser.requests[0].error.as_deref(),
Some("net::ERR_CONNECTION_REFUSED")
);
assert_eq!(snapshot.browser.websocket_frames.len(), 2);
assert_eq!(snapshot.browser.websocket_frames[0].data, "hello");
assert_eq!(snapshot.browser.websocket_frames[1].data, "world");
assert_eq!(snapshot.browser.page_events.len(), 1);
assert_eq!(snapshot.browser.page_events[0].name, "frameNavigated");
assert_eq!(
snapshot.browser.page_events[0].url.as_deref(),
Some("https://example.test/next")
);
}
}