Skip to main content

rightkit_browser/
capture.rs

1//! Typed page capture bound to the browser session that produced it (rightkit#821).
2//!
3//! [`capture`] launches its own session, loads one real URL at one viewport, and returns a
4//! [`CaptureReport`]: the load result, a PNG screenshot, navigation and paint metrics, the console
5//! and uncaught exceptions, and (feature `axe`) an axe-core accessibility result, each as a bounded
6//! artifact written under a private output directory with its length and SHA-256. The report binds
7//! all of it to the session, process, profile, page, frame, loader and execution context that
8//! produced it and to the caller's plan, source, probe and action digests, and ends with the
9//! terminal outcome of cleanup ([`StopReport`]), not a lifecycle event.
10//!
11//! Decision (rightkit#821, option 2): capture is built on [`BrowserSession`] and real pages, not
12//! on `FixtureSession`. A fixture session serves a sealed bundle of synthetic files and exposes no
13//! script; a Legion live-surface capture targets the project's real running pages. The terminal
14//! cleanup result that `shutdown()` discarded is now returned by [`BrowserSession::shutdown_report`]
15//! and [`BrowserSession::cancel_report`]. No general script evaluation is exposed: the runtime
16//! reads fixed observations, and axe runs in an isolated world so the page cannot replace it.
17//!
18//! Failure, timeout and cancellation still return what was collected plus the cleanup outcome;
19//! only a request that is invalid before anything launches returns `Err`.
20
21use crate::config::LaunchOptions;
22use crate::error::{cdp, BrowserError, Result};
23use crate::page::BrowserPage;
24use crate::policy::NetworkPolicy;
25use crate::session::{BrowserSession, PageSetup, StopReport};
26use chromiumoxide::cdp::browser_protocol::page::{CreateIsolatedWorldParams, GetFrameTreeParams};
27use chromiumoxide::cdp::js_protocol::runtime::{
28    EnableParams as RuntimeEnableParams, EvaluateParams, EventExecutionContextCreated,
29    ExecutionContextId,
30};
31use futures::StreamExt;
32use serde::Serialize;
33use serde_json::Value;
34use sha2::{Digest, Sha256};
35use std::path::{Path, PathBuf};
36use std::sync::{Arc, Mutex as StdMutex};
37use std::time::Duration;
38
39/// Schema tag of every [`CaptureReport`].
40pub const CAPTURE_SCHEMA: &str = "rightkit.browser.capture/1";
41/// Most console records kept.
42pub const MAX_CAPTURE_CONSOLE_RECORDS: usize = 500;
43/// Largest screenshot accepted, in bytes.
44pub const MAX_CAPTURE_SCREENSHOT_BYTES: usize = 32 * 1024 * 1024;
45/// Largest axe result kept, in bytes of JSON.
46pub const MAX_CAPTURE_AXE_BYTES: usize = 4 * 1024 * 1024;
47/// Largest viewport edge, in CSS pixels.
48pub const MAX_CAPTURE_VIEWPORT_EDGE: u32 = 16384;
49/// Longest accepted deadline.
50pub const MAX_CAPTURE_DEADLINE: Duration = Duration::from_secs(600);
51/// The vendored axe-core version (feature `axe`).
52#[cfg(feature = "axe")]
53pub const AXE_VERSION: &str = "4.14.0";
54/// SHA-256 of the vendored `axe.min.js` (feature `axe`); checked before every use.
55#[cfg(feature = "axe")]
56pub const AXE_SHA256: &str = "20c09fe157a8a34a30e241aaa1fcdade657734f08ab379ecfbeb7d45cc46e878";
57#[cfg(feature = "axe")]
58const AXE_SOURCE: &str = include_str!("../third-party/axe-core/4.14.0/axe.min.js");
59
60const MAX_DIGEST_CHARS: usize = 200;
61#[cfg(feature = "axe")]
62const MAX_AXE_TAGS: usize = 16;
63#[cfg(feature = "axe")]
64const MAX_AXE_TAG_CHARS: usize = 40;
65const SETTLE_WAIT: Duration = Duration::from_secs(10);
66
67/// The caller's own identity for the work being captured, carried verbatim into the report.
68/// Each digest is a non-empty string of at most 200 characters with no control characters; the
69/// format (for example `sha256:<hex>`) is the caller's.
70#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
71#[serde(rename_all = "camelCase")]
72pub struct CaptureBinding {
73    pub plan_digest: String,
74    pub source_digest: String,
75    pub probe_digest: String,
76    pub action_digest: String,
77}
78
79/// An accessibility check to run with the vendored axe-core.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct AxeSpec {
82    /// axe rule tags (for example `wcag2a`, `wcag2aa`); one to 16 of `a-z0-9-`, at most 40 characters each.
83    pub tags: Vec<String>,
84}
85
86impl AxeSpec {
87    /// WCAG 2.0 level A and AA.
88    pub fn wcag2_aa() -> Self {
89        Self {
90            tags: vec!["wcag2a".into(), "wcag2aa".into()],
91        }
92    }
93}
94
95/// One capture of one URL.
96#[derive(Clone, Debug)]
97pub struct CaptureRequest {
98    pub binding: CaptureBinding,
99    /// `http` or `https` URL of the real page.
100    pub url: String,
101    /// Viewport in CSS pixels, each edge 1 to [`MAX_CAPTURE_VIEWPORT_EDGE`].
102    pub viewport: (u32, u32),
103    /// Existing absolute directory; the capture writes a private `rk-capture-*` directory in it.
104    pub output_root: PathBuf,
105    /// Budget for the whole load and observation run (1 s to [`MAX_CAPTURE_DEADLINE`]). Launch
106    /// has its own bound; cleanup always runs.
107    pub deadline: Duration,
108    /// Network policy of the capture session. The default refuses loopback and private
109    /// addresses; allow a dev server's host explicitly.
110    pub network: NetworkPolicy,
111    /// Explicit browser executable; `None` resolves Chrome for Testing as a session does.
112    pub chrome_path: Option<PathBuf>,
113    /// Run axe-core with these tags; needs feature `axe`.
114    pub axe: Option<AxeSpec>,
115}
116
117impl CaptureRequest {
118    /// A request for `url` at 1280x800 with a 60 s budget, the default network policy and no axe.
119    pub fn new(
120        url: impl Into<String>,
121        binding: CaptureBinding,
122        output_root: impl Into<PathBuf>,
123    ) -> Self {
124        Self {
125            binding,
126            url: url.into(),
127            viewport: (1280, 800),
128            output_root: output_root.into(),
129            deadline: Duration::from_secs(60),
130            network: NetworkPolicy::default(),
131            chrome_path: None,
132            axe: None,
133        }
134    }
135
136    fn validate(&self) -> Result<()> {
137        for (name, value) in [
138            ("plan_digest", &self.binding.plan_digest),
139            ("source_digest", &self.binding.source_digest),
140            ("probe_digest", &self.binding.probe_digest),
141            ("action_digest", &self.binding.action_digest),
142        ] {
143            if value.is_empty()
144                || value.chars().count() > MAX_DIGEST_CHARS
145                || value.chars().any(char::is_control)
146            {
147                return Err(BrowserError::Invalid(format!(
148                    "{name} must be 1 to {MAX_DIGEST_CHARS} characters without control characters"
149                )));
150            }
151        }
152        let url = url::Url::parse(&self.url)
153            .map_err(|e| BrowserError::Invalid(format!("capture url: {e}")))?;
154        if !matches!(url.scheme(), "http" | "https") {
155            return Err(BrowserError::Invalid(
156                "capture url must be http or https".into(),
157            ));
158        }
159        let (w, h) = self.viewport;
160        if !(1..=MAX_CAPTURE_VIEWPORT_EDGE).contains(&w)
161            || !(1..=MAX_CAPTURE_VIEWPORT_EDGE).contains(&h)
162        {
163            return Err(BrowserError::Invalid(format!(
164                "viewport edges must be 1 to {MAX_CAPTURE_VIEWPORT_EDGE}"
165            )));
166        }
167        if self.deadline < Duration::from_secs(1) || self.deadline > MAX_CAPTURE_DEADLINE {
168            return Err(BrowserError::Invalid(
169                "capture deadline must be 1 s to 600 s".into(),
170            ));
171        }
172        if !self.output_root.is_absolute() || !self.output_root.is_dir() {
173            return Err(BrowserError::Invalid(
174                "output_root must be an existing absolute directory".into(),
175            ));
176        }
177        if let Some(axe) = &self.axe {
178            #[cfg(not(feature = "axe"))]
179            {
180                let _ = axe;
181                return Err(BrowserError::Unsupported(
182                    "axe capture needs the rightkit-browser feature `axe`".into(),
183                ));
184            }
185            #[cfg(feature = "axe")]
186            {
187                let ok = !axe.tags.is_empty()
188                    && axe.tags.len() <= MAX_AXE_TAGS
189                    && axe.tags.iter().all(|t| {
190                        !t.is_empty()
191                            && t.len() <= MAX_AXE_TAG_CHARS
192                            && t.bytes()
193                                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
194                    });
195                if !ok {
196                    return Err(BrowserError::Invalid(
197                        "axe tags: 1 to 16 tags of a-z, 0-9 and '-', at most 40 characters each"
198                            .into(),
199                    ));
200                }
201                if hex(&Sha256::digest(AXE_SOURCE.as_bytes())) != AXE_SHA256 {
202                    return Err(BrowserError::Invalid(
203                        "the vendored axe-core does not match its pinned hash".into(),
204                    ));
205                }
206            }
207        }
208        Ok(())
209    }
210}
211
212/// Sticky, cloneable cancellation signal for [`capture`].
213#[derive(Clone)]
214pub struct CaptureCancellation {
215    cancelled: tokio::sync::watch::Sender<bool>,
216}
217
218impl Default for CaptureCancellation {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl CaptureCancellation {
225    pub fn new() -> Self {
226        let (cancelled, _) = tokio::sync::watch::channel(false);
227        Self { cancelled }
228    }
229
230    pub fn cancel(&self) {
231        self.cancelled.send_replace(true);
232    }
233
234    pub fn is_cancelled(&self) -> bool {
235        *self.cancelled.borrow()
236    }
237
238    async fn cancelled(&self) {
239        let mut rx = self.cancelled.subscribe();
240        loop {
241            if *rx.borrow() {
242                return;
243            }
244            if rx.changed().await.is_err() {
245                std::future::pending::<()>().await;
246            }
247        }
248    }
249}
250
251/// How the capture ended.
252#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
253#[serde(rename_all = "camelCase")]
254pub enum CaptureStatus {
255    /// The page loaded successfully, every requested observation was obtained whole, and cleanup
256    /// succeeded.
257    Complete,
258    /// The run finished but something is missing or wrong: a failed load, an unavailable or
259    /// truncated observation, or incomplete cleanup. `reasons` says which.
260    Incomplete,
261    /// A step failed and stopped the run.
262    Failed,
263    /// The deadline passed.
264    TimedOut,
265    /// The caller cancelled.
266    Cancelled,
267}
268
269/// One file the capture wrote.
270#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
271#[serde(rename_all = "camelCase")]
272pub struct CaptureArtifact {
273    pub path: PathBuf,
274    pub len: u64,
275    pub sha256: String,
276}
277
278/// What produced the capture: the browser instance and the exact document observed, bound to the
279/// caller's digests.
280#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
281#[serde(rename_all = "camelCase")]
282pub struct CaptureIdentity {
283    pub binding: CaptureBinding,
284    /// SHA-256 of the canonical request (url, viewport, axe tags and hash, binding).
285    pub request_digest: String,
286    pub browser_session_id: String,
287    pub browser_pid: Option<u32>,
288    /// The profile directory of this session (a temporary directory removed at cleanup).
289    pub profile_dir: PathBuf,
290    pub page_id: String,
291    pub target_id: String,
292    pub frame_id: String,
293    pub loader_id: String,
294    /// CDP unique id of the main frame's default execution context, when seen.
295    pub unique_context_id: Option<String>,
296    pub requested_url: String,
297    /// The frame's URL after loading.
298    pub final_url: String,
299    pub viewport: (u32, u32),
300}
301
302/// The navigation result.
303#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
304#[serde(rename_all = "camelCase")]
305pub struct LoadObservation {
306    /// The navigation finished and the main document's HTTP status was below 400.
307    pub ok: bool,
308    /// HTTP status of the main document; `None` when the browser did not report one.
309    pub status: Option<u16>,
310    pub error: Option<String>,
311}
312
313/// PNG screenshot of the viewport.
314#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
315#[serde(rename_all = "camelCase")]
316pub struct ScreenshotArtifact {
317    pub artifact: CaptureArtifact,
318    pub width: u32,
319    pub height: u32,
320}
321
322/// Navigation and paint timings; values the browser did not report are JSON `null`.
323#[derive(Clone, Debug, PartialEq, Serialize)]
324#[serde(rename_all = "camelCase")]
325pub struct MetricsObservation {
326    pub artifact: CaptureArtifact,
327    pub values: Value,
328}
329
330#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
331#[serde(rename_all = "camelCase")]
332pub struct ConsoleRecord {
333    pub level: String,
334    pub text: String,
335}
336
337/// Console output and uncaught exceptions from page creation to the end of observation.
338#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
339#[serde(rename_all = "camelCase")]
340pub struct ConsoleObservation {
341    pub artifact: CaptureArtifact,
342    pub records: Vec<ConsoleRecord>,
343    pub error_records: usize,
344    pub exceptions: Vec<String>,
345    /// The console buffer reached its cap, so earlier lines may be missing.
346    pub truncated: bool,
347}
348
349#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
350#[serde(rename_all = "camelCase")]
351pub enum AxeStatus {
352    /// axe ran and found no violation for the tags.
353    Passed,
354    /// axe ran and reported violations (see the artifact).
355    Violations,
356    /// The result exceeded [`MAX_CAPTURE_AXE_BYTES`]; the count is known, the detail was not kept.
357    Truncated,
358}
359
360/// The axe-core result.
361#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
362#[serde(rename_all = "camelCase")]
363pub struct AxeObservation {
364    pub version: String,
365    pub script_sha256: String,
366    pub tags: Vec<String>,
367    pub status: AxeStatus,
368    pub violation_count: usize,
369    pub artifact: Option<CaptureArtifact>,
370}
371
372/// Terminal cleanup, as achieved.
373#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
374#[serde(rename_all = "camelCase")]
375pub struct CleanupReport {
376    /// A browser was launched (when false there was nothing to clean up).
377    pub launched: bool,
378    /// The session's own stop outcome; `None` when nothing launched.
379    pub stop: Option<StopReport>,
380    /// Every launched resource was released without error.
381    pub complete: bool,
382}
383
384/// Everything one capture produced.
385#[derive(Clone, Debug, Serialize)]
386#[serde(rename_all = "camelCase")]
387pub struct CaptureReport {
388    pub schema: &'static str,
389    pub status: CaptureStatus,
390    /// Why the status is not [`CaptureStatus::Complete`].
391    pub reasons: Vec<String>,
392    pub identity: Option<CaptureIdentity>,
393    pub load: Option<LoadObservation>,
394    pub screenshot: Option<ScreenshotArtifact>,
395    pub metrics: Option<MetricsObservation>,
396    pub console: Option<ConsoleObservation>,
397    pub axe: Option<AxeObservation>,
398    /// Private directory holding the artifacts and `report.json`; kept for the caller.
399    pub output_dir: PathBuf,
400    pub cleanup: CleanupReport,
401}
402
403fn hex(bytes: &[u8]) -> String {
404    bytes.iter().map(|b| format!("{b:02x}")).collect()
405}
406
407fn write_artifact(dir: &Path, name: &str, bytes: &[u8]) -> Result<CaptureArtifact> {
408    let path = dir.join(name);
409    std::fs::write(&path, bytes)?;
410    Ok(CaptureArtifact {
411        path,
412        len: bytes.len() as u64,
413        sha256: hex(&Sha256::digest(bytes)),
414    })
415}
416
417/// `(width, height)` from a PNG's IHDR, or `None` when the bytes are not a PNG.
418fn png_dimensions(png: &[u8]) -> Option<(u32, u32)> {
419    const SIGNATURE: &[u8] = &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
420    if png.len() < 24 || &png[..8] != SIGNATURE || &png[12..16] != b"IHDR" {
421        return None;
422    }
423    let w = u32::from_be_bytes(png[16..20].try_into().ok()?);
424    let h = u32::from_be_bytes(png[20..24].try_into().ok()?);
425    (w > 0 && h > 0).then_some((w, h))
426}
427
428struct AbortOnDrop(tokio::task::JoinHandle<()>);
429
430impl Drop for AbortOnDrop {
431    fn drop(&mut self) {
432        self.0.abort();
433    }
434}
435
436const METRICS_SCRIPT: &str = r#"(() => {
437  const num = (v) => (typeof v === 'number' && isFinite(v)) ? v : null;
438  const nav = performance.getEntriesByType('navigation')[0];
439  const paint = {};
440  for (const p of performance.getEntriesByType('paint')) { paint[p.name] = num(p.startTime); }
441  return {
442    navigation: nav ? {
443      type: nav.type,
444      responseStart: num(nav.responseStart),
445      responseEnd: num(nav.responseEnd),
446      domContentLoadedEventEnd: num(nav.domContentLoadedEventEnd),
447      loadEventEnd: nav.loadEventEnd > 0 ? num(nav.loadEventEnd) : null,
448      duration: num(nav.duration),
449      transferSize: num(nav.transferSize),
450      encodedBodySize: num(nav.encodedBodySize),
451      decodedBodySize: num(nav.decodedBodySize),
452      responseStatus: num(nav.responseStatus)
453    } : null,
454    paint: {
455      firstPaint: num(paint['first-paint']),
456      firstContentfulPaint: num(paint['first-contentful-paint'])
457    },
458    resourceCount: performance.getEntriesByType('resource').length
459  };
460})()"#;
461
462/// Evaluate `expression` in the isolated execution context `context` and return its value.
463async fn eval_isolated(
464    page: &BrowserPage,
465    context: ExecutionContextId,
466    expression: String,
467) -> Result<Value> {
468    let params = EvaluateParams::builder()
469        .expression(expression)
470        .context_id(context)
471        .return_by_value(true)
472        .await_promise(true)
473        .build()
474        .map_err(BrowserError::Invalid)?;
475    let response = page.raw().execute(params).await.map_err(cdp)?;
476    if let Some(exception) = response.result.exception_details {
477        return Err(BrowserError::Cdp(format!(
478            "observation script failed: {}",
479            exception.text
480        )));
481    }
482    Ok(response.result.result.value.unwrap_or(Value::Null))
483}
484
485/// Capture `request`. See the module docs for what is returned on each ending.
486///
487/// Returns `Err` only when the request is invalid or the output directory cannot be created,
488/// before any browser launches. A browser that cannot launch yields a [`CaptureStatus::Failed`]
489/// report with `cleanup.launched == false`.
490pub async fn capture(
491    request: CaptureRequest,
492    cancel: &CaptureCancellation,
493) -> Result<CaptureReport> {
494    request.validate()?;
495    let output_dir = tempfile::Builder::new()
496        .prefix("rk-capture-")
497        .tempdir_in(&request.output_root)?
498        .keep();
499    let mut report = CaptureReport {
500        schema: CAPTURE_SCHEMA,
501        status: CaptureStatus::Failed,
502        reasons: Vec::new(),
503        identity: None,
504        load: None,
505        screenshot: None,
506        metrics: None,
507        console: None,
508        axe: None,
509        output_dir: output_dir.clone(),
510        cleanup: CleanupReport {
511            launched: false,
512            stop: None,
513            complete: true,
514        },
515    };
516    let launch = LaunchOptions {
517        headless: true,
518        mute_audio: true,
519        viewport: request.viewport,
520        chrome_path: request.chrome_path.clone(),
521        network: request.network.clone(),
522        launch_timeout: request.deadline.min(Duration::from_secs(60)),
523        request_timeout: request.deadline.min(Duration::from_secs(30)),
524        ..LaunchOptions::default()
525    };
526    let session = match BrowserSession::launch(launch).await {
527        Ok(session) => session,
528        Err(error) => {
529            report
530                .reasons
531                .push(format!("browser did not launch: {error}"));
532            finish_report(&report);
533            return Ok(report);
534        }
535    };
536    report.cleanup.launched = true;
537
538    let outcome = tokio::select! {
539        result = tokio::time::timeout(
540            request.deadline,
541            observe(&request, &session, &output_dir, &mut report),
542        ) => match result {
543            Ok(Ok(())) => CaptureStatus::Complete,
544            Ok(Err(error)) => {
545                report.reasons.push(format!("capture stopped: {error}"));
546                CaptureStatus::Failed
547            }
548            Err(_) => {
549                report.reasons.push("the capture deadline passed".into());
550                CaptureStatus::TimedOut
551            }
552        },
553        _ = cancel.cancelled() => {
554            report.reasons.push("capture was cancelled".into());
555            CaptureStatus::Cancelled
556        }
557    };
558
559    let stop = if outcome == CaptureStatus::Complete {
560        session.shutdown_report().await
561    } else {
562        session.cancel_report().await
563    };
564    report.cleanup.complete = stop.process_stopped && stop.profile_released;
565    if let Some(error) = &stop.process_error {
566        report.reasons.push(format!("browser process: {error}"));
567    }
568    if let Some(error) = &stop.profile_error {
569        report.reasons.push(format!("browser profile: {error}"));
570    }
571    report.cleanup.stop = Some(stop);
572    drop(session);
573
574    report.status = if outcome == CaptureStatus::Complete
575        && (!report.reasons.is_empty() || !report.cleanup.complete)
576    {
577        CaptureStatus::Incomplete
578    } else {
579        outcome
580    };
581    finish_report(&report);
582    Ok(report)
583}
584
585/// Write `report.json` beside the artifacts; best effort, the returned report is the record.
586fn finish_report(report: &CaptureReport) {
587    if let Ok(bytes) = serde_json::to_vec_pretty(report) {
588        let _ = std::fs::write(report.output_dir.join("report.json"), bytes);
589    }
590}
591
592fn request_digest(request: &CaptureRequest) -> String {
593    #[cfg(feature = "axe")]
594    let axe_hash = request.axe.as_ref().map(|_| AXE_SHA256);
595    #[cfg(not(feature = "axe"))]
596    let axe_hash: Option<&str> = None;
597    let canonical = serde_json::json!({
598        "schema": CAPTURE_SCHEMA,
599        "url": request.url,
600        "viewport": [request.viewport.0, request.viewport.1],
601        "axeTags": request.axe.as_ref().map(|a| a.tags.clone()),
602        "axeSha256": axe_hash,
603        "binding": request.binding,
604    });
605    format!(
606        "sha256:{}",
607        hex(&Sha256::digest(canonical.to_string().as_bytes()))
608    )
609}
610
611/// The observation run. Fills `report` as it goes so a timeout or cancellation keeps the partial
612/// output.
613async fn observe(
614    request: &CaptureRequest,
615    session: &BrowserSession,
616    out: &Path,
617    report: &mut CaptureReport,
618) -> Result<()> {
619    let page = session
620        .new_page_with("about:blank", PageSetup::default())
621        .await?;
622    page.set_viewport(request.viewport.0, request.viewport.1, 1.0)
623        .await?;
624    let raw = page.raw();
625
626    let contexts: Arc<StdMutex<Vec<(String, String)>>> = Arc::default();
627    let mut created = raw
628        .event_listener::<EventExecutionContextCreated>()
629        .await
630        .map_err(cdp)?;
631    let sink = contexts.clone();
632    let _contexts_task = AbortOnDrop(tokio::spawn(async move {
633        while let Some(event) = created.next().await {
634            let aux = event.context.aux_data.as_ref();
635            let is_default = aux
636                .and_then(|v| v.get("isDefault"))
637                .and_then(Value::as_bool)
638                .unwrap_or(false);
639            let frame = aux
640                .and_then(|v| v.get("frameId"))
641                .and_then(Value::as_str)
642                .map(str::to_owned);
643            if let (true, Some(frame)) = (is_default, frame) {
644                sink.lock()
645                    .unwrap_or_else(|e| e.into_inner())
646                    .push((frame, event.context.unique_id.clone()));
647            }
648        }
649    }));
650    raw.execute(RuntimeEnableParams::default())
651        .await
652        .map_err(cdp)?;
653    page.clear_console().await;
654    page.clear_exceptions();
655
656    let navigation = page.goto(&request.url).await;
657    // Document complete and the load event recorded, bounded; metrics report what exists.
658    let _ = page
659        .wait_eval("document.readyState === 'complete'", SETTLE_WAIT)
660        .await;
661    let _ = page
662        .wait_eval(
663            "(performance.getEntriesByType('navigation')[0] || {loadEventEnd: 1}).loadEventEnd > 0",
664            SETTLE_WAIT,
665        )
666        .await;
667
668    let frame = raw
669        .execute(GetFrameTreeParams::default())
670        .await
671        .map_err(cdp)?
672        .result
673        .frame_tree
674        .frame;
675    let frame_id = frame.id.as_ref().to_string();
676    let unique_context_id = contexts
677        .lock()
678        .unwrap_or_else(|e| e.into_inner())
679        .iter()
680        .rev()
681        .find(|(f, _)| *f == frame_id)
682        .map(|(_, unique)| unique.clone());
683    report.identity = Some(CaptureIdentity {
684        binding: request.binding.clone(),
685        request_digest: request_digest(request),
686        browser_session_id: session.id().to_string(),
687        browser_pid: session.process_id(),
688        profile_dir: session.profile_dir().to_path_buf(),
689        page_id: page.id().to_string(),
690        target_id: page.target_id().to_string(),
691        frame_id: frame_id.clone(),
692        loader_id: frame.loader_id.as_ref().to_string(),
693        unique_context_id,
694        requested_url: request.url.clone(),
695        final_url: frame.url.clone(),
696        viewport: request.viewport,
697    });
698    if report
699        .identity
700        .as_ref()
701        .is_some_and(|identity| identity.unique_context_id.is_none())
702    {
703        report
704            .reasons
705            .push("the main frame's execution context was not observed".into());
706    }
707
708    // An isolated world: the page's scripts cannot replace what observes it.
709    let mut world = CreateIsolatedWorldParams::new(frame.id.clone());
710    world.world_name = Some(format!("rightkit-capture-{}", session.id()));
711    world.grant_univeral_access = Some(false);
712    let context = raw
713        .execute(world)
714        .await
715        .map_err(cdp)?
716        .result
717        .execution_context_id;
718
719    let metrics = eval_isolated(&page, context, METRICS_SCRIPT.to_string()).await;
720    let status = metrics
721        .as_ref()
722        .ok()
723        .and_then(|v| v.pointer("/navigation/responseStatus"))
724        .and_then(Value::as_u64)
725        .and_then(|s| u16::try_from(s).ok());
726    let load = match &navigation {
727        Ok(()) => LoadObservation {
728            ok: status.is_some_and(|s| s < 400),
729            status,
730            error: None,
731        },
732        Err(error) => LoadObservation {
733            ok: false,
734            status,
735            error: Some(error.to_string()),
736        },
737    };
738    if !load.ok {
739        report.reasons.push(match (&load.error, load.status) {
740            (Some(error), _) => format!("navigation failed: {error}"),
741            (None, Some(status)) => format!("navigation returned HTTP {status}"),
742            (None, None) => "the browser reported no HTTP status for the page".into(),
743        });
744    }
745    report.load = Some(load);
746
747    match metrics {
748        Ok(values) if !values.is_null() => {
749            let bytes = serde_json::to_vec_pretty(&values)
750                .map_err(|e| BrowserError::Invalid(e.to_string()))?;
751            report.metrics = Some(MetricsObservation {
752                artifact: write_artifact(out, "metrics.json", &bytes)?,
753                values,
754            });
755        }
756        Ok(_) => report.reasons.push("metrics were unavailable".into()),
757        Err(error) => report
758            .reasons
759            .push(format!("metrics were unavailable: {error}")),
760    }
761
762    match page.screenshot().await {
763        Ok(png) if png.len() > MAX_CAPTURE_SCREENSHOT_BYTES => report.reasons.push(format!(
764            "screenshot exceeded {MAX_CAPTURE_SCREENSHOT_BYTES} bytes"
765        )),
766        Ok(png) => match png_dimensions(&png) {
767            Some((width, height)) => {
768                report.screenshot = Some(ScreenshotArtifact {
769                    artifact: write_artifact(out, "screenshot.png", &png)?,
770                    width,
771                    height,
772                });
773            }
774            None => report
775                .reasons
776                .push("the screenshot was not a valid PNG".into()),
777        },
778        Err(error) => report
779            .reasons
780            .push(format!("screenshot was unavailable: {error}")),
781    }
782
783    if let Some(axe) = &request.axe {
784        run_axe(&page, context, axe, out, report).await?;
785    }
786
787    let lines = page.console().await;
788    let truncated = lines.len() >= MAX_CAPTURE_CONSOLE_RECORDS;
789    let records: Vec<ConsoleRecord> = lines
790        .into_iter()
791        .take(MAX_CAPTURE_CONSOLE_RECORDS)
792        .map(|line| ConsoleRecord {
793            level: line.level,
794            text: line.text,
795        })
796        .collect();
797    let exceptions: Vec<String> = page
798        .exceptions()
799        .into_iter()
800        .map(|e| e.description.unwrap_or(e.text))
801        .collect();
802    let error_records = records
803        .iter()
804        .filter(|r| r.level.eq_ignore_ascii_case("error"))
805        .count();
806    let body = serde_json::json!({
807        "records": records,
808        "exceptions": exceptions,
809        "truncated": truncated,
810    });
811    let bytes =
812        serde_json::to_vec_pretty(&body).map_err(|e| BrowserError::Invalid(e.to_string()))?;
813    report.console = Some(ConsoleObservation {
814        artifact: write_artifact(out, "console.json", &bytes)?,
815        records,
816        error_records,
817        exceptions,
818        truncated,
819    });
820    if truncated {
821        report
822            .reasons
823            .push("the console buffer was full; earlier lines may be missing".into());
824    }
825    Ok(())
826}
827
828#[cfg(feature = "axe")]
829async fn run_axe(
830    page: &BrowserPage,
831    context: ExecutionContextId,
832    axe: &AxeSpec,
833    out: &Path,
834    report: &mut CaptureReport,
835) -> Result<()> {
836    if let Err(error) = eval_isolated(page, context, AXE_SOURCE.to_string()).await {
837        report
838            .reasons
839            .push(format!("axe-core could not be loaded: {error}"));
840        return Ok(());
841    }
842    let version = eval_isolated(page, context, "axe.version".to_string()).await;
843    if version.as_ref().ok().and_then(Value::as_str) != Some(AXE_VERSION) {
844        report
845            .reasons
846            .push("axe-core reported a version other than the pinned one".into());
847        return Ok(());
848    }
849    let tags =
850        serde_json::to_string(&axe.tags).map_err(|e| BrowserError::Invalid(e.to_string()))?;
851    let script = format!(
852        "axe.run(document, {{ runOnly: {{ type: 'tag', values: {tags} }}, resultTypes: ['violations'] }})\
853         .then((r) => JSON.stringify({{ url: r.url, testEngine: r.testEngine, \
854         violations: r.violations.map((v) => ({{ id: v.id, impact: v.impact, help: v.help, \
855         helpUrl: v.helpUrl, tags: v.tags, nodes: v.nodes.map((n) => ({{ target: n.target, \
856         html: (n.html || '').slice(0, 300) }})) }})) }}))"
857    );
858    let result = match eval_isolated(page, context, script).await {
859        Ok(value) => value,
860        Err(error) => {
861            report
862                .reasons
863                .push(format!("axe-core did not finish: {error}"));
864            return Ok(());
865        }
866    };
867    let Some(text) = result.as_str() else {
868        report.reasons.push("axe-core returned no result".into());
869        return Ok(());
870    };
871    let parsed: Value = match serde_json::from_str(text) {
872        Ok(value) => value,
873        Err(error) => {
874            report
875                .reasons
876                .push(format!("axe-core result was not JSON: {error}"));
877            return Ok(());
878        }
879    };
880    let count = parsed
881        .get("violations")
882        .and_then(Value::as_array)
883        .map_or(0, Vec::len);
884    let (status, artifact) = if text.len() > MAX_CAPTURE_AXE_BYTES {
885        report.reasons.push(format!(
886            "the axe result exceeded {MAX_CAPTURE_AXE_BYTES} bytes and was not kept"
887        ));
888        (AxeStatus::Truncated, None)
889    } else {
890        let bytes =
891            serde_json::to_vec_pretty(&parsed).map_err(|e| BrowserError::Invalid(e.to_string()))?;
892        let status = if count == 0 {
893            AxeStatus::Passed
894        } else {
895            AxeStatus::Violations
896        };
897        (status, Some(write_artifact(out, "axe.json", &bytes)?))
898    };
899    report.axe = Some(AxeObservation {
900        version: AXE_VERSION.to_string(),
901        script_sha256: AXE_SHA256.to_string(),
902        tags: axe.tags.clone(),
903        status,
904        violation_count: count,
905        artifact,
906    });
907    Ok(())
908}
909
910#[cfg(not(feature = "axe"))]
911async fn run_axe(
912    _page: &BrowserPage,
913    _context: ExecutionContextId,
914    _axe: &AxeSpec,
915    _out: &Path,
916    report: &mut CaptureReport,
917) -> Result<()> {
918    report
919        .reasons
920        .push("axe was requested but the `axe` feature is off".into());
921    Ok(())
922}