ferridriver 0.3.0

Browser automation in Rust with a Playwright-compatible API. Four pluggable backends: CDP pipe, CDP WebSocket, Playwright WebKit, Firefox BiDi.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Structured error taxonomy for ferridriver's public API.
//!
//! Mirrors Playwright's error shape (`packages/playwright-core/src/client/errors.ts`)
//! so consumers can distinguish classes of failure via [`FerriError::is_timeout_error`]
//! / [`FerriError::is_target_closed_error`] and so NAPI consumers receive an
//! `error.name` that matches Playwright (`"TimeoutError"`, `"TargetClosedError"`).
//!
//! The enum is the single public error type. Internal modules should convert
//! their native errors into a [`FerriError`] variant at the public API boundary.

use thiserror::Error;

/// Every user-facing failure mode in the ferridriver core.
///
/// Any `Display` output of this type is the exact string that flows into
/// `error.message` on the NAPI surface; NAPI consumers use [`FerriError::name`]
/// to dispatch on error class. Keep the message wording aligned with Playwright
/// wherever possible so error-matching tests ported from Playwright keep working.
#[derive(Debug, Error, Clone)]
pub enum FerriError {
  /// Operation did not complete within its deadline. Mirrors Playwright's
  /// `TimeoutError` — message format `"Timeout {timeout_ms}ms exceeded"` with
  /// an optional `"while {operation}"` suffix.
  #[error("Timeout {timeout_ms}ms exceeded{}", .operation.as_ref().map(|op| format!(" while {op}")).unwrap_or_default())]
  Timeout {
    /// Short phrase describing what was being waited on, e.g. `"navigating to https://..."`.
    operation: Option<String>,
    timeout_ms: u64,
  },

  /// Target page, context, browser, or session has been closed. Mirrors
  /// Playwright's `TargetClosedError`.
  #[error("Target page, context or browser has been closed{}", .reason.as_ref().map(|r| format!(": {r}")).unwrap_or_default())]
  TargetClosed { reason: Option<String> },

  /// Locator resolved to more than one element under strict-mode evaluation.
  /// Playwright raises a plain `Error` with a specific message format; we
  /// surface it as a dedicated variant and mirror the message.
  #[error("strict mode violation: selector {selector:?} resolved to {count} elements")]
  StrictModeViolation { selector: String, count: usize },

  /// Navigation-specific failure (DNS, TLS, `ERR_ABORTED`, etc.).
  #[error("navigation to {url} failed: {message}")]
  Navigation { url: String, message: String },

  /// CDP/BiDi/WebKit protocol error surfaced by the transport layer.
  #[error("protocol error ({method}): {message}")]
  Protocol { method: String, message: String },

  /// Backend-level failure not otherwise classified (launch, connect, pipe
  /// read failure, etc.).
  #[error("backend error: {0}")]
  Backend(String),

  /// Selector string could not be parsed or contains an unknown engine.
  #[error("invalid selector {selector:?}: {reason}")]
  InvalidSelector { selector: String, reason: String },

  /// Caller is not connected to any browser target.
  #[error("not connected")]
  NotConnected,

  /// Long-running operation was cancelled by the caller or supervisor.
  #[error("interrupted: {0}")]
  Interrupted(String),

  /// Caller passed an argument that did not pass validation.
  #[error("invalid argument {name:?}: {reason}")]
  InvalidArgument { name: String, reason: String },

  /// Feature requested is valid Playwright API but not yet implemented for
  /// the active backend.
  #[error("unsupported operation: {0}")]
  Unsupported(String),

  /// `page.evaluate` / `locator.evaluate` threw inside the page.
  #[error("evaluation error: {0}")]
  Evaluation(String),

  /// Snapshot read/write/compare failure.
  #[error("snapshot error: {0}")]
  Snapshot(String),

  /// Filesystem / non-CDP I/O error. The original `std::io::Error` is
  /// stringified at conversion time so [`FerriError`] stays `Clone`.
  #[error("io error: {0}")]
  Io(String),

  /// JSON (de)serialization error from the protocol layer. Stringified at
  /// conversion time so [`FerriError`] stays `Clone`.
  #[error("json error: {0}")]
  Json(String),
}

impl FerriError {
  /// Matches Playwright's `isTimeoutError(err)` helper.
  #[must_use]
  pub fn is_timeout_error(&self) -> bool {
    matches!(self, Self::Timeout { .. })
  }

  /// Matches Playwright's `TargetClosedError` detection.
  #[must_use]
  pub fn is_target_closed_error(&self) -> bool {
    matches!(self, Self::TargetClosed { .. })
  }

  /// Matches Playwright's strict-mode violation detection.
  #[must_use]
  pub fn is_strict_mode_violation(&self) -> bool {
    matches!(self, Self::StrictModeViolation { .. })
  }

  /// The `name` attribute mirrored on the JS side via NAPI.
  ///
  /// `"TimeoutError"` / `"TargetClosedError"` match Playwright's names exactly;
  /// everything else reports `"FerriError"` so TS consumers can fall back to
  /// message-based matching without colliding with Playwright class names.
  #[must_use]
  pub fn name(&self) -> &'static str {
    match self {
      Self::Timeout { .. } => "TimeoutError",
      Self::TargetClosed { .. } => "TargetClosedError",
      _ => "FerriError",
    }
  }

  /// True for variants whose JS-side counterpart is a dedicated class
  /// instance (`TimeoutError`, `TargetClosedError`). Drives the
  /// `"<Name>: <message>"` prefix convention used at every error boundary
  /// (NAPI, `QuickJS`, reporter strings) so the TS bridge can re-hydrate
  /// the typed class from the prefix.
  #[must_use]
  pub fn has_named_prefix(&self) -> bool {
    matches!(self, Self::Timeout { .. } | Self::TargetClosed { .. })
  }

  /// Render the error message with the Playwright-style class prefix
  /// for distinguishable variants, plain `Display` output otherwise.
  /// Single source of truth — every boundary helper (`to_napi`,
  /// `to_rq_error`, `TestFailure::from`/`wrap`) routes through this.
  #[must_use]
  pub fn display_named(&self) -> String {
    if self.has_named_prefix() {
      format!("{}: {self}", self.name())
    } else {
      self.to_string()
    }
  }

  /// Builder for [`FerriError::Timeout`] with an operation description.
  #[must_use]
  pub fn timeout(operation: impl Into<String>, timeout_ms: u64) -> Self {
    Self::Timeout {
      operation: Some(operation.into()),
      timeout_ms,
    }
  }

  /// Builder for [`FerriError::Timeout`] with no operation description.
  #[must_use]
  pub fn timeout_plain(timeout_ms: u64) -> Self {
    Self::Timeout {
      operation: None,
      timeout_ms,
    }
  }

  /// Builder for [`FerriError::StrictModeViolation`].
  #[must_use]
  pub fn strict(selector: impl Into<String>, count: usize) -> Self {
    Self::StrictModeViolation {
      selector: selector.into(),
      count,
    }
  }

  /// Builder for [`FerriError::TargetClosed`] with optional reason.
  #[must_use]
  pub fn target_closed(reason: Option<String>) -> Self {
    Self::TargetClosed { reason }
  }

  /// Builder for [`FerriError::Protocol`].
  #[must_use]
  pub fn protocol(method: impl Into<String>, message: impl Into<String>) -> Self {
    Self::Protocol {
      method: method.into(),
      message: message.into(),
    }
  }

  /// Builder for [`FerriError::InvalidArgument`].
  #[must_use]
  pub fn invalid_argument(name: impl Into<String>, reason: impl Into<String>) -> Self {
    Self::InvalidArgument {
      name: name.into(),
      reason: reason.into(),
    }
  }

  /// Builder for [`FerriError::InvalidSelector`].
  #[must_use]
  pub fn invalid_selector(selector: impl Into<String>, reason: impl Into<String>) -> Self {
    Self::InvalidSelector {
      selector: selector.into(),
      reason: reason.into(),
    }
  }

  /// Builder for [`FerriError::Evaluation`].
  #[must_use]
  pub fn evaluation(message: impl Into<String>) -> Self {
    Self::Evaluation(message.into())
  }

  /// Builder for [`FerriError::Backend`].
  #[must_use]
  pub fn backend(message: impl Into<String>) -> Self {
    Self::Backend(message.into())
  }

  /// Builder for [`FerriError::Unsupported`].
  #[must_use]
  pub fn unsupported(reason: impl Into<String>) -> Self {
    Self::Unsupported(reason.into())
  }

  /// Builder for [`FerriError::Interrupted`].
  #[must_use]
  pub fn interrupted(reason: impl Into<String>) -> Self {
    Self::Interrupted(reason.into())
  }

  /// Builder for [`FerriError::Navigation`].
  #[must_use]
  pub fn navigation(url: impl Into<String>, message: impl Into<String>) -> Self {
    Self::Navigation {
      url: url.into(),
      message: message.into(),
    }
  }

  /// Builder for [`FerriError::Snapshot`].
  #[must_use]
  pub fn snapshot(message: impl Into<String>) -> Self {
    Self::Snapshot(message.into())
  }

  /// True for any [`FerriError::Unsupported`] variant.
  #[must_use]
  pub fn is_unsupported(&self) -> bool {
    matches!(self, Self::Unsupported(_))
  }
}

impl From<std::io::Error> for FerriError {
  fn from(e: std::io::Error) -> Self {
    Self::Io(e.to_string())
  }
}

impl From<serde_json::Error> for FerriError {
  fn from(e: serde_json::Error) -> Self {
    Self::Json(e.to_string())
  }
}

/// Unrouted string errors (subprocess stderr, third-party libraries surfacing
/// `String` errors via `?`) land in [`FerriError::Backend`]. This conversion
/// is permanent — it routes raw strings to a typed variant rather than
/// keeping an `Other`-shaped escape hatch. Modules that can classify their
/// errors (timeouts, protocol failures, unsupported features) build the
/// matching variant explicitly. The `"unsupported:"` prefix is recognised
/// and upgraded to [`FerriError::Unsupported`] so legacy backend code that
/// emitted that sentinel keeps producing the right typed variant.
impl From<String> for FerriError {
  fn from(s: String) -> Self {
    if let Some(reason) = s.strip_prefix("unsupported:") {
      return Self::Unsupported(reason.trim().to_string());
    }
    Self::Backend(s)
  }
}

impl From<&str> for FerriError {
  fn from(s: &str) -> Self {
    if let Some(reason) = s.strip_prefix("unsupported:") {
      return Self::Unsupported(reason.trim().to_string());
    }
    Self::Backend(s.to_string())
  }
}

/// Convenience alias. Every new public API function should return this.
pub type Result<T> = std::result::Result<T, FerriError>;

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn timeout_message_matches_playwright_shape() {
    let err = FerriError::timeout("navigating to https://example.com", 30_000);
    assert_eq!(
      err.to_string(),
      "Timeout 30000ms exceeded while navigating to https://example.com"
    );
    assert_eq!(err.name(), "TimeoutError");
    assert!(err.is_timeout_error());
    assert!(!err.is_target_closed_error());
  }

  #[test]
  fn timeout_without_operation_omits_while_clause() {
    let err = FerriError::timeout_plain(5_000);
    assert_eq!(err.to_string(), "Timeout 5000ms exceeded");
  }

  #[test]
  fn target_closed_with_reason() {
    let err = FerriError::target_closed(Some("browser crashed".into()));
    assert_eq!(
      err.to_string(),
      "Target page, context or browser has been closed: browser crashed"
    );
    assert_eq!(err.name(), "TargetClosedError");
    assert!(err.is_target_closed_error());
  }

  #[test]
  fn target_closed_without_reason() {
    let err = FerriError::target_closed(None);
    assert_eq!(err.to_string(), "Target page, context or browser has been closed");
  }

  #[test]
  fn strict_mode_violation_reports_selector_and_count() {
    let err = FerriError::strict("button.primary", 3);
    assert_eq!(
      err.to_string(),
      r#"strict mode violation: selector "button.primary" resolved to 3 elements"#
    );
    assert_eq!(err.name(), "FerriError");
    assert!(err.is_strict_mode_violation());
  }

  #[test]
  fn name_dispatch_covers_all_named_variants() {
    assert_eq!(FerriError::timeout_plain(1).name(), "TimeoutError");
    assert_eq!(FerriError::target_closed(None).name(), "TargetClosedError");
    assert_eq!(FerriError::Backend("x".into()).name(), "FerriError");
    assert_eq!(FerriError::NotConnected.name(), "FerriError");
  }

  #[test]
  fn from_string_routes_to_backend_variant() {
    let from_string: FerriError = String::from("legacy").into();
    let from_str: FerriError = "legacy".into();
    assert!(matches!(from_string, FerriError::Backend(ref s) if s == "legacy"));
    assert!(matches!(from_str, FerriError::Backend(ref s) if s == "legacy"));
  }

  #[test]
  fn from_string_unsupported_prefix_routes_to_unsupported_variant() {
    let err: FerriError = String::from("unsupported: pdf on webkit").into();
    assert!(matches!(err, FerriError::Unsupported(ref s) if s == "pdf on webkit"));
  }

  #[test]
  fn ferri_error_is_clone() {
    let err = FerriError::backend("oops");
    let cloned = err.clone();
    assert_eq!(err.to_string(), cloned.to_string());
  }

  #[test]
  fn io_and_json_errors_convert_via_question_mark() {
    fn io_fail() -> Result<()> {
      let _: std::fs::File = std::fs::File::open("/definitely/does/not/exist/ferri-test")?;
      Ok(())
    }
    fn json_fail() -> Result<()> {
      let _: serde_json::Value = serde_json::from_str("{")?;
      Ok(())
    }
    assert!(matches!(io_fail().unwrap_err(), FerriError::Io(_)));
    assert!(matches!(json_fail().unwrap_err(), FerriError::Json(_)));
  }

  #[test]
  fn navigation_error_formats_url_and_message() {
    let err = FerriError::Navigation {
      url: "https://example.com".into(),
      message: "net::ERR_NAME_NOT_RESOLVED".into(),
    };
    assert_eq!(
      err.to_string(),
      "navigation to https://example.com failed: net::ERR_NAME_NOT_RESOLVED"
    );
  }

  #[test]
  fn protocol_error_formats_method() {
    let err = FerriError::protocol("Page.navigate", "session detached");
    assert_eq!(err.to_string(), "protocol error (Page.navigate): session detached");
  }

  #[test]
  fn invalid_argument_quotes_name() {
    let err = FerriError::invalid_argument("timeout", "must be non-negative");
    assert_eq!(err.to_string(), r#"invalid argument "timeout": must be non-negative"#);
  }

  #[test]
  fn invalid_selector_quotes_selector() {
    let err = FerriError::invalid_selector("???", "unknown engine");
    assert_eq!(err.to_string(), r#"invalid selector "???": unknown engine"#);
  }

  #[test]
  fn display_named_prepends_class_for_distinguishable_variants() {
    assert_eq!(
      FerriError::timeout("navigating", 30_000).display_named(),
      "TimeoutError: Timeout 30000ms exceeded while navigating"
    );
    assert_eq!(
      FerriError::target_closed(Some("crashed".into())).display_named(),
      "TargetClosedError: Target page, context or browser has been closed: crashed"
    );
  }

  #[test]
  fn display_named_passes_unnamed_through_verbatim() {
    assert_eq!(
      FerriError::backend("launch failed").display_named(),
      "backend error: launch failed"
    );
    assert_eq!(
      FerriError::strict("button", 3).display_named(),
      r#"strict mode violation: selector "button" resolved to 3 elements"#
    );
  }

  #[test]
  fn has_named_prefix_matches_name() {
    assert!(FerriError::timeout_plain(1).has_named_prefix());
    assert!(FerriError::target_closed(None).has_named_prefix());
    assert!(!FerriError::backend("x").has_named_prefix());
    assert!(!FerriError::strict("s", 2).has_named_prefix());
  }
}