Skip to main content

vs_engine_webkit/
engine.rs

1//! The [`Engine`] trait — the daemon's view of "a browser".
2//!
3//! The trait is small, synchronous, and platform-agnostic. The daemon
4//! drives an `Engine` from a Tokio context but never directly: every
5//! call is dispatched onto the engine's dedicated thread (see
6//! [`crate::runtime`]), where the platform-specific WebKit port runs.
7//!
8//! For the live wire types — [`Tree`], [`Node`], [`Ref`], [`Role`],
9//! [`Op`] — see [`vs_protocol`].
10
11use std::path::PathBuf;
12use std::time::Duration;
13
14use vs_protocol::{Op, Ref, Tree};
15
16/// Default `User-Agent` the engine sets on each page. Mirrors a recent
17/// shipping Safari on macOS so anti-bot fingerprinters that match on
18/// the WKWebView default (which lacks the `Version/X Safari/X`
19/// suffix) don't flag every request. Backends that support
20/// per-webview UA (WKWebView via `setCustomUserAgent`, WebKitGTK via
21/// `webkit_settings_set_user_agent`, WebView2 via `Profile2` /
22/// `coreWebView2.Settings.UserAgent`) apply this string at construction.
23pub const DEFAULT_USER_AGENT: &str =
24    "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/605.1.15 \
25     (KHTML, like Gecko) Version/17.5 Safari/605.1.15";
26
27/// An opaque engine-side handle to a page. The daemon associates each
28/// `PageHandle` with one `pages` row in [`vs-store`](vs_protocol).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
30pub struct PageHandle(pub u64);
31
32/// What [`Engine::act`] targets on a page.
33#[derive(Debug, Clone)]
34pub enum ActTarget {
35    /// A live ref from the most recent snapshot.
36    Ref(Ref),
37    /// A persistent mark, identified by name.
38    Mark(String),
39}
40
41/// Coordinate-addressed input operations: `vs move-to`, `vs click-at`,
42/// `vs hover-at`, `vs drag`. Native event dispatch on backends that
43/// support it (macOS today; Linux + Windows fall through to
44/// `ENGINE_UNSUPPORTED` until M7 wires GDK / CDP input).
45#[derive(Debug, Clone, Copy)]
46pub enum CursorOp {
47    /// Move the pointer to `(x, y)` without clicking.
48    MoveTo { x: f64, y: f64 },
49    /// Click at `(x, y)`. Includes a humanized lead-in from the last
50    /// known cursor position when the mode is `Human`.
51    ClickAt { x: f64, y: f64 },
52    /// Hover (mouseover) at `(x, y)`.
53    HoverAt { x: f64, y: f64 },
54    /// Press at `(x1, y1)`, drag along a humanized path to `(x2, y2)`,
55    /// release.
56    Drag { x1: f64, y1: f64, x2: f64, y2: f64 },
57}
58
59/// Input humanization mode. Wire form: `--mode={human,careful,robotic}`.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum InputMode {
62    Human,
63    Careful,
64    Robotic,
65}
66
67impl InputMode {
68    #[must_use]
69    pub fn parse(s: &str) -> Option<Self> {
70        match s.to_ascii_lowercase().as_str() {
71            "human" | "h" => Some(Self::Human),
72            "careful" | "c" => Some(Self::Careful),
73            "robotic" | "r" => Some(Self::Robotic),
74            _ => None,
75        }
76    }
77    #[must_use]
78    pub fn as_str(self) -> &'static str {
79        match self {
80            Self::Human => "human",
81            Self::Careful => "careful",
82            Self::Robotic => "robotic",
83        }
84    }
85}
86
87/// What [`Engine::act`] does at the target.
88#[derive(Debug, Clone)]
89pub enum Action {
90    /// Activate (mouse click or `Enter`).
91    Click,
92    /// Replace the text content of an editable target.
93    Fill { value: String },
94    /// Scroll the target into view.
95    Scroll,
96    /// Send a key chord (`Enter`, `Ctrl+K`, …).
97    Key { chord: String },
98    /// Submit the enclosing form.
99    Submit,
100    /// Move the pointer over the target.
101    Hover,
102    /// Move keyboard focus.
103    Focus,
104}
105
106impl Action {
107    /// The protocol [`Op`](vs_protocol::Op) corresponding to this action.
108    #[must_use]
109    pub fn op(&self) -> Op {
110        match self {
111            Self::Click => Op::Click,
112            Self::Fill { .. } => Op::Fill,
113            Self::Scroll => Op::Scroll,
114            Self::Key { .. } => Op::Key,
115            Self::Submit => Op::Submit,
116            Self::Hover => Op::Hover,
117            Self::Focus => Op::Focus,
118        }
119    }
120}
121
122/// A condition for [`Engine::wait`].
123#[derive(Debug, Clone)]
124pub enum WaitCondition {
125    /// A11y tree stable for 250ms.
126    Stable,
127    /// Network idle (`<= 0` in-flight requests for 500ms).
128    NetIdle,
129    /// `Ref(r)` appears in the tree.
130    RefAppears(Ref),
131    /// `Ref(r)` disappears from the tree.
132    RefGone(Ref),
133    /// Substring matches anywhere in the tree.
134    Text(String),
135    /// `state_token` changes.
136    TokenChange,
137}
138
139/// Scope of a [`Engine::capture`] call.
140#[derive(Debug, Clone)]
141pub enum CaptureScope {
142    Viewport,
143    Element(Ref),
144    FullPage,
145}
146
147/// A viewport definition. Sizes are in CSS pixels; `dpr` is the
148/// device-pixel ratio.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct Viewport {
151    pub width: u32,
152    pub height: u32,
153    pub dpr: u32,
154}
155
156impl Viewport {
157    pub const MOBILE_S: Self = Self::new(320, 568, 2);
158    pub const MOBILE: Self = Self::new(390, 844, 2);
159    pub const MOBILE_L: Self = Self::new(414, 896, 2);
160    pub const TABLET: Self = Self::new(768, 1024, 2);
161    pub const TABLET_L: Self = Self::new(1024, 768, 2);
162    pub const LAPTOP: Self = Self::new(1366, 768, 2);
163    pub const DESKTOP: Self = Self::new(1920, 1080, 2);
164    pub const DESKTOP_XL: Self = Self::new(2560, 1440, 2);
165    pub const WIDE: Self = Self::new(3440, 1440, 2);
166
167    #[must_use]
168    pub const fn new(width: u32, height: u32, dpr: u32) -> Self {
169        Self { width, height, dpr }
170    }
171
172    /// Look up a preset by its protocol name (e.g. `"mobile"`,
173    /// `"desktop-xl"`). Returns `None` for unknown presets.
174    #[must_use]
175    pub fn preset(name: &str) -> Option<Self> {
176        match name {
177            "mobile-s" => Some(Self::MOBILE_S),
178            "mobile" => Some(Self::MOBILE),
179            "mobile-l" => Some(Self::MOBILE_L),
180            "tablet" => Some(Self::TABLET),
181            "tablet-l" => Some(Self::TABLET_L),
182            "laptop" => Some(Self::LAPTOP),
183            "desktop" => Some(Self::DESKTOP),
184            "desktop-xl" => Some(Self::DESKTOP_XL),
185            "wide" => Some(Self::WIDE),
186            _ => None,
187        }
188    }
189}
190
191/// What [`Engine::download`] should hand back.
192#[derive(Debug, Clone)]
193pub enum DownloadSource {
194    /// Read `url` from inside the page, with the page's own cookies and
195    /// referer. Relative URLs resolve against the current document.
196    Url(String),
197    /// Drain the newest download the page *tried* to perform (a
198    /// `download` anchor, a `blob:` navigation, a viewer's save button)
199    /// and that the shim captured. `id` selects a specific buffered
200    /// entry; `None` takes the newest completed one.
201    Captured { id: Option<u64> },
202}
203
204/// One download the engine holds in memory, on its way to disk.
205#[derive(Debug, Clone)]
206pub struct Download {
207    pub bytes: Vec<u8>,
208    /// Suggested file name, from `Content-Disposition`, the anchor's
209    /// `download` attribute, or the URL's last path segment.
210    pub filename: String,
211    /// MIME type as reported by the blob or the response. May be empty.
212    pub mime: String,
213    /// The URL the bytes came from. `blob:` for in-page saves.
214    pub url: String,
215}
216
217/// A captured download intent, without its payload. Listed by
218/// [`Engine::download_list`] so an agent can see what the page tried
219/// to save before committing to reading any of it.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct DownloadEntry {
222    pub id: u64,
223    pub filename: String,
224    pub mime: String,
225    pub url: String,
226    pub size: u64,
227    /// `Some(msg)` when the capture failed (revoked blob, HTTP error,
228    /// over the size cap). The entry is kept so the failure is visible
229    /// instead of the download silently vanishing.
230    pub error: Option<String>,
231    pub done: bool,
232}
233
234/// Result of [`Engine::layout`]: the computed box for a single ref.
235#[derive(Debug, Clone, Copy, PartialEq)]
236pub struct LayoutBox {
237    pub r: Ref,
238    pub x: f64,
239    pub y: f64,
240    pub width: f64,
241    pub height: f64,
242    pub visible: bool,
243    pub z_index: i32,
244}
245
246/// What an engine declares it can and cannot do.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248#[allow(clippy::struct_excessive_bools)]
249pub struct EngineCapabilities {
250    /// Renders pixels (pages are visually realized; `capture` works).
251    pub renders: bool,
252    /// Honors `set_viewport` requests.
253    pub honors_viewport: bool,
254    /// Computes layout boxes (`layout` works).
255    pub measures_layout: bool,
256    /// Persists and restores cookies / storage (`save_auth` / `load_auth` work).
257    pub persists_auth: bool,
258    /// Captures `console.*` and uncaught exceptions in a ring buffer
259    /// (M5.7 PR1+). Surfaced via `vs_inspect console`.
260    pub inspector_console: bool,
261    /// Captures network requests in a ring buffer (M5.7 PR1+).
262    /// Surfaced via `vs_inspect network`.
263    pub inspector_network: bool,
264    /// Captures cookie-store ADD/REMOVE events in a ring buffer
265    /// (v0.1.6+). Surfaced via `vs_inspect cookie-events`. macOS and
266    /// Linux only — Windows reports `false` because `webview2-com` has
267    /// no cookie-changed observer.
268    pub inspector_cookie_events: bool,
269    /// Short identifier reported in `vs_status`.
270    pub name: &'static str,
271    /// Engine version string. Empty for the stub.
272    pub version: &'static str,
273}
274
275impl EngineCapabilities {
276    /// Capabilities advertised by the in-memory `TestEngine` (in
277    /// `test_support`). Sealed behind the `test-support` Cargo
278    /// feature; production builds of the daemon never see this.
279    pub const TEST: Self = Self {
280        renders: true,
281        honors_viewport: true,
282        measures_layout: true,
283        persists_auth: true,
284        inspector_console: true,
285        inspector_network: true,
286        inspector_cookie_events: true,
287        name: "test",
288        version: "",
289    };
290}
291
292/// Opaque encrypted-by-the-engine auth payload. The daemon hands the
293/// bytes to [`vs_store`](vs_protocol) for at-rest encryption.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct AuthBlob {
296    pub bytes: Vec<u8>,
297}
298
299/// What can go wrong when driving an engine.
300#[derive(Debug, Clone, thiserror::Error)]
301#[non_exhaustive]
302pub enum EngineError {
303    /// The engine cannot service this primitive on this platform.
304    #[error("engine `{engine}` does not support `{primitive}`")]
305    Unsupported {
306        engine: &'static str,
307        primitive: &'static str,
308    },
309
310    /// Operation exceeded its deadline.
311    #[error("timeout after {budget:?}: {primitive}")]
312    Timeout {
313        budget: Duration,
314        primitive: &'static str,
315    },
316
317    /// The named ref or mark is not present.
318    #[error("not found: {kind} {id}")]
319    NotFound { kind: &'static str, id: String },
320
321    /// The engine thread panicked or is otherwise non-responsive.
322    #[error("engine thread crashed")]
323    Crashed,
324
325    /// The engine has shut down and is no longer accepting commands.
326    #[error("engine has shut down")]
327    Closed,
328
329    /// Backend recognizes the primitive but has not implemented it.
330    /// Distinct from [`Self::Unsupported`]: the platform *can* support
331    /// it, the port just isn't there yet.
332    #[error("engine `{engine}` has not implemented `{primitive}`")]
333    NotImplemented {
334        engine: &'static str,
335        primitive: &'static str,
336    },
337
338    /// Anything else (engine-specific failure mode).
339    #[error("{0}")]
340    Other(String),
341}
342
343/// Convenience [`Result`] with [`EngineError`] as the error type.
344pub type EngineResult<T> = std::result::Result<T, EngineError>;
345
346/// One recorded frame streamed from the engine during automation.
347///
348/// `record_begin` sets up a channel; the backend then captures a frame
349/// at each input step (mouse move, keystroke, click settle) and sends
350/// it here without releasing the main thread. `cx`/`cy` are the cursor
351/// position in *frame pixels* (already scaled to the recorded frame's
352/// resolution) so the recorder can composite a pointer, and `click` is
353/// a ripple phase (`1.0` at press, decaying to `0.0`; `0.0` = no ripple).
354/// This is what lets a recording show real, continuous mouse motion
355/// instead of a before/after slideshow: the frames are grabbed *inside*
356/// the move loop, not by a poller that is blocked behind it.
357pub struct RecFrame {
358    pub png: Vec<u8>,
359    pub cx: f64,
360    pub cy: f64,
361    pub click: f32,
362    /// Intended elapsed time (ms) this frame represents on the input
363    /// path, independent of how long the synchronous capture actually
364    /// took. The recorder advances its media clock by this so motion
365    /// plays at natural speed even though each snapshot inflates the real
366    /// wall-clock of the move. `0` = use real elapsed time (idle frames).
367    pub dt_ms: u32,
368}
369
370/// The browser engine, as the daemon sees it.
371///
372/// All methods are synchronous from the daemon's perspective. The
373/// [`runtime`](crate::runtime) layer dispatches calls onto a dedicated
374/// thread that owns the platform run loop; implementations should
375/// assume they are running on that thread.
376pub trait Engine {
377    /// Open a fresh page navigated to `url`.
378    fn open(&mut self, url: &str) -> EngineResult<PageHandle>;
379
380    /// Navigate an existing page to `url` in place, reusing its
381    /// web view (and web-content process) instead of creating a new
382    /// one. The page handle is unchanged; the document is replaced, so
383    /// callers must re-baseline (all refs are fresh). Much cheaper than
384    /// `open` for successive navigations.
385    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()>;
386
387    /// Install a virtual WebAuthn authenticator on `page`: a pure-JS
388    /// software authenticator that overrides `navigator.credentials`
389    /// so passkey registration and login work headlessly, with no
390    /// platform authenticator and no automation protocol. Applies to
391    /// the current document and (where the backend supports it) to
392    /// subsequent navigations in the same page.
393    fn enable_webauthn(&mut self, page: PageHandle) -> EngineResult<()>;
394
395    /// Close a page. Idempotent — closing a closed page is a no-op.
396    fn close(&mut self, page: PageHandle) -> EngineResult<()>;
397
398    /// Snapshot the a11y tree at `page`.
399    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree>;
400
401    /// Perform `action` on `target` at `page`.
402    fn act(
403        &mut self,
404        page: PageHandle,
405        target: ActTarget,
406        action: Action,
407        mode: InputMode,
408    ) -> EngineResult<()>;
409
410    /// Wait for `cond` at `page` until satisfied or `budget` elapses.
411    fn wait(&mut self, page: PageHandle, cond: WaitCondition, budget: Duration)
412        -> EngineResult<()>;
413
414    /// Take a screenshot. Returns the path on disk where the image was
415    /// written.
416    fn capture(&mut self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf>;
417
418    /// Capture a live frame (watch / record) at a reduced width
419    /// (`max_width` px, `0` = full resolution). Cheaper to produce and
420    /// encode than a full-resolution screenshot. The default delegates
421    /// to [`Self::capture`]; backends that can render a smaller snapshot
422    /// override it.
423    fn capture_live(&mut self, page: PageHandle, _max_width: u32) -> EngineResult<PathBuf> {
424        self.capture(page, CaptureScope::Viewport)
425    }
426
427    /// Begin streaming recording frames for `page`. While active, the
428    /// backend captures a frame at each input step (mouse move,
429    /// keystroke, click) and sends it on `tx` with the cursor position,
430    /// so the recorder composites a pointer and encodes smooth motion
431    /// without a poller racing the automation. `max_width` downscales
432    /// each frame (`0` = full resolution). The default is unsupported so
433    /// the daemon can fall back to time-based polling.
434    fn record_begin(
435        &mut self,
436        _page: PageHandle,
437        _tx: std::sync::mpsc::Sender<RecFrame>,
438        _fps: u32,
439        _max_width: u32,
440    ) -> EngineResult<()> {
441        Err(EngineError::Unsupported {
442            engine: "generic",
443            primitive: "record_begin",
444        })
445    }
446
447    /// Stop streaming recording frames for `page` (drops the sender so
448    /// the recorder's drain loop ends). Idempotent.
449    fn record_end(&mut self, _page: PageHandle) -> EngineResult<()> {
450        Ok(())
451    }
452
453    /// Compute layout boxes for `refs` at `page`.
454    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>;
455
456    /// Read a file out of `page` — either a URL fetched with the page's
457    /// credentials, or a download the page itself initiated and the
458    /// capture shim parked. Returns the bytes; the daemon owns where
459    /// they land on disk.
460    ///
461    /// Headless web views have no download delegate, so a download the
462    /// page starts is otherwise dropped without an event. Backends with
463    /// a working JS bridge get this for free via
464    /// [`common::run_download`](crate::backend); the default is
465    /// unsupported.
466    fn download(
467        &mut self,
468        _page: PageHandle,
469        _source: DownloadSource,
470        _budget: Duration,
471    ) -> EngineResult<Download> {
472        Err(EngineError::Unsupported {
473            engine: self.capabilities().name,
474            primitive: "download",
475        })
476    }
477
478    /// List the download intents the shim has captured on `page`,
479    /// payloads excluded.
480    fn download_list(&mut self, _page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
481        Err(EngineError::Unsupported {
482            engine: self.capabilities().name,
483            primitive: "download",
484        })
485    }
486
487    /// Set the viewport at `page`. Triggers a re-baseline for the next
488    /// `snapshot`.
489    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()>;
490
491    /// Snapshot cookies/storage for `page` as an opaque [`AuthBlob`].
492    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob>;
493
494    /// Apply a previously saved [`AuthBlob`] to `page`.
495    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()>;
496
497    /// Snapshot the always-captured console ring buffer for `page`.
498    /// Default impl returns empty (engines without console capture).
499    fn console_entries(
500        &mut self,
501        _page: PageHandle,
502    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
503        Ok(Vec::new())
504    }
505
506    /// Snapshot the always-captured network ring buffer for `page`.
507    /// Default impl returns empty (engines without network capture).
508    fn network_entries(
509        &mut self,
510        _page: PageHandle,
511    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
512        Ok(Vec::new())
513    }
514
515    /// Look up the full detail (headers + bodies) for a single
516    /// captured network request. Returns `None` if the seq isn't in
517    /// the buffer. Default impl returns `None`.
518    fn request_detail(
519        &mut self,
520        _page: PageHandle,
521        _seq: u64,
522    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
523        Ok(None)
524    }
525
526    /// Evaluate `expr` in main world. Default impl returns
527    /// `EvalResult::Thrown { kind: "NotImplemented", ... }`.
528    fn eval_js(
529        &mut self,
530        _page: PageHandle,
531        _expr: &str,
532    ) -> EngineResult<crate::inspector::EvalResult> {
533        Ok(crate::inspector::EvalResult::Thrown {
534            kind: "NotImplemented".into(),
535            message: "engine does not implement vs_inspect eval".into(),
536        })
537    }
538
539    /// List storage entries for the requested scope.
540    fn storage(
541        &mut self,
542        _page: PageHandle,
543        _scope: crate::inspector::StorageScope,
544    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
545        Ok(Vec::new())
546    }
547
548    /// List cookie store ADD/REMOVE events observed since the page
549    /// opened. Engines without a cookie-changed observer (Windows, the
550    /// stub) return an empty vec or `ENGINE_UNSUPPORTED` via their
551    /// capability flag.
552    fn cookie_events(
553        &mut self,
554        _page: PageHandle,
555    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
556        Ok(Vec::new())
557    }
558
559    /// Trusted keyboard typing into the focused element. Sends real
560    /// per-character key events (KeyDown/KeyUp) so the page sees
561    /// isTrusted=true keydown → beforeinput → input, which
562    /// rich-text editors (DraftJS/ProseMirror/contenteditable) and
563    /// framework-controlled inputs require — the prototype-setter
564    /// `fill` path bypasses their change pipeline. The caller places
565    /// the caret first (e.g. `vs_click_at`). Backends without native
566    /// keyboard dispatch fall through to `ENGINE_UNSUPPORTED`.
567    fn type_text(&mut self, _page: PageHandle, _text: &str, _mode: InputMode) -> EngineResult<()> {
568        Err(EngineError::Unsupported {
569            engine: self.capabilities().name,
570            primitive: "type_text",
571        })
572    }
573
574    /// Coordinate-addressed cursor operation. Backends that don't
575    /// implement native input dispatch fall through to the default
576    /// `ENGINE_UNSUPPORTED` here; agents see `! ENGINE_UNSUPPORTED`
577    /// on the wire and can switch to ref-based `vs act` instead.
578    fn cursor_op(
579        &mut self,
580        _page: PageHandle,
581        _op: CursorOp,
582        _mode: InputMode,
583    ) -> EngineResult<()> {
584        Err(EngineError::Unsupported {
585            engine: self.capabilities().name,
586            primitive: "cursor_op",
587        })
588    }
589    /// List scripts loaded by the page.
590    fn scripts(&mut self, _page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
591        Ok(Vec::new())
592    }
593
594    /// Source of one script by `seq`. Returns `None` if the seq isn't
595    /// in the script registry.
596    fn script_source(
597        &mut self,
598        _page: PageHandle,
599        _seq: u64,
600    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
601        Ok(None)
602    }
603
604    /// Outer HTML + computed styles for a ref. Caller-requested
605    /// computed properties land in `extra_props`; the engine merges
606    /// them with its default property set. Returns `None` for unknown
607    /// refs.
608    fn dom(
609        &mut self,
610        _page: PageHandle,
611        _r: vs_protocol::Ref,
612        _extra_props: &[String],
613    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
614        Ok(None)
615    }
616
617    /// Web Vitals + heap + DOM stats. Returns zero-filled defaults if
618    /// the engine can't measure them.
619    fn performance(
620        &mut self,
621        _page: PageHandle,
622    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
623        Ok(crate::inspector::PerformanceMetrics::default())
624    }
625    /// Capabilities the daemon should advertise for this engine.
626    fn capabilities(&self) -> EngineCapabilities;
627}
628
629/// The role a node in `Node` would carry — re-exported for convenience.
630pub use vs_protocol::Role as NodeRole;
631
632#[cfg(test)]
633mod tests {
634    use super::DEFAULT_USER_AGENT;
635
636    /// Pins the UA contract: must look like a current shipping
637    /// Safari, including the `Version/X` and `Safari/Y` suffixes.
638    /// The whole reason this constant exists is that the WKWebView
639    /// default UA drops both — sites that fingerprint UAs (Google,
640    /// Cloudflare, etc.) flag every request without them.
641    ///
642    /// If this test fails because you bumped the version, that's
643    /// fine — update the literal. If it fails because the format
644    /// changed, think hard before relaxing it.
645    #[test]
646    fn default_user_agent_has_safari_suffix() {
647        let ua = DEFAULT_USER_AGENT;
648        assert!(
649            ua.starts_with("Mozilla/5.0 "),
650            "UA should start with `Mozilla/5.0 `; got {ua:?}",
651        );
652        assert!(
653            ua.contains("AppleWebKit/"),
654            "UA should advertise WebKit; got {ua:?}",
655        );
656        assert!(
657            ua.contains("Version/"),
658            "UA missing `Version/X` — anti-bot will flag it; got {ua:?}",
659        );
660        assert!(
661            ua.contains("Safari/"),
662            "UA missing `Safari/X` — anti-bot will flag it; got {ua:?}",
663        );
664        // Single-line — extra whitespace inside is fine, but no
665        // newlines / tabs.
666        assert!(
667            !ua.contains('\n') && !ua.contains('\r') && !ua.contains('\t'),
668            "UA must be a single line; got {ua:?}",
669        );
670    }
671}