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