Skip to main content

rustenium_cdp_definitions/
base.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Command;
4
5#[derive(Debug, Clone, Serialize)]
6pub struct CommandMessage {
7    #[serde(rename = "id")]
8    pub id: u16,
9    #[serde(flatten)]
10    pub command_data: Command,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct CommandResponse {
15    pub id: u16,
16    pub result: serde_json::Value,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct ErrorInfo {
21    pub code: i64,
22    pub message: String,
23}
24
25impl std::fmt::Display for ErrorInfo {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        write!(f, "CDP Error[{}]: {}", self.code, self.message)
28    }
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct ErrorResponse {
33    #[serde(skip_serializing_if = "Option::is_none")]
34    #[serde(default)]
35    pub id: Option<u16>,
36    pub error: ErrorInfo,
37}
38
39impl std::fmt::Display for ErrorResponse {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        match self.id {
42            Some(id) => write!(f, "Error for command {}: {}", id, self.error),
43            None => write!(f, "Error: {}", self.error),
44        }
45    }
46}
47
48/// CDP events arrive as `{"method": "Domain.event", "params": {...}}` with no
49/// outer envelope distinguishing them from commands/errors (unlike BiDi which
50/// wraps events in a typed structure). `EventResponse` captures this raw shape
51/// so we can route by method name and then deserialize into concrete event
52/// types on demand via `TryInto`.
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct EventResponse {
55    pub method: String,
56    pub params: serde_json::Value,
57}
58
59impl EventResponse {
60    /// Attempt to convert this raw event into a concrete CDP event type.
61    ///
62    /// The concrete type (e.g. `TargetCreated`) is expected to deserialize from
63    /// the full `{"method": "...", "params": {...}}` shape — not just the params.
64    pub fn try_into_event<T: serde::de::DeserializeOwned>(self) -> Result<T, serde_json::Error> {
65        let value = serde_json::json!({
66            "method": self.method,
67            "params": self.params,
68        });
69        serde_json::from_value(value)
70    }
71
72    pub fn identifier(&self) -> &str {
73        &self.method
74    }
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(untagged)]
79pub enum Message {
80    ErrorResponse(ErrorResponse),
81    CommandResponse(CommandResponse),
82    Event(EventResponse),
83}