viewpoint_core/context/
mod.rs

1//! # Browser Context Management
2//!
3//! Browser contexts are isolated environments within a browser, similar to incognito windows.
4//! Each context has its own cookies, cache, localStorage, and other browser storage.
5//!
6//! ## Features
7//!
8//! - **Isolation**: Each context is completely isolated from others
9//! - **Cookie Management**: Add, get, and clear cookies with [`BrowserContext::add_cookies`], [`BrowserContext::cookies`], [`BrowserContext::clear_cookies`]
10//! - **Storage State**: Save and restore browser state (cookies, localStorage) for authentication
11//! - **Permissions**: Grant permissions like geolocation, camera, microphone
12//! - **Geolocation**: Mock browser location with [`BrowserContext::set_geolocation`]
13//! - **HTTP Credentials**: Configure basic/digest authentication
14//! - **Extra Headers**: Add headers to all requests in the context
15//! - **Offline Mode**: Simulate network offline conditions
16//! - **Event Handling**: Listen for page creation and context close events
17//! - **Init Scripts**: Run scripts before every page load
18//! - **Custom Test ID**: Configure which attribute is used for test IDs
19//! - **Network Routing**: Intercept and mock requests at the context level
20//! - **HAR Recording**: Record network traffic for debugging
21//! - **Tracing**: Record traces for debugging
22//!
23//! ## Quick Start
24//!
25//! ```no_run
26//! use viewpoint_core::{Browser, BrowserContext, Permission};
27//!
28//! # async fn example() -> Result<(), viewpoint_core::CoreError> {
29//! let browser = Browser::launch().headless(true).launch().await?;
30//!
31//! // Create a simple context
32//! let context = browser.new_context().await?;
33//!
34//! // Create a context with options
35//! let context = browser.new_context_builder()
36//!     .viewport(1920, 1080)
37//!     .geolocation(37.7749, -122.4194)
38//!     .permissions(vec![Permission::Geolocation])
39//!     .build()
40//!     .await?;
41//!
42//! // Create a page in the context
43//! let page = context.new_page().await?;
44//! page.goto("https://example.com").goto().await?;
45//! # Ok(())
46//! # }
47//! ```
48//!
49//! ## Cookie Management
50//!
51//! ```ignore
52//! use viewpoint_core::{Browser, Cookie, SameSite};
53//!
54//! # async fn example() -> Result<(), viewpoint_core::CoreError> {
55//! # let browser = Browser::launch().headless(true).launch().await?;
56//! # let context = browser.new_context().await?;
57//! // Add cookies
58//! context.add_cookies(vec![
59//!     Cookie {
60//!         name: "session".to_string(),
61//!         value: "abc123".to_string(),
62//!         domain: Some(".example.com".to_string()),
63//!         path: Some("/".to_string()),
64//!         expires: None,
65//!         http_only: Some(true),
66//!         secure: Some(true),
67//!         same_site: Some(SameSite::Lax),
68//!     }
69//! ]).await?;
70//!
71//! // Get all cookies
72//! let cookies = context.cookies(None).await?;
73//!
74//! // Get cookies for specific URLs
75//! let cookies = context.cookies(Some(&["https://example.com"])).await?;
76//!
77//! // Clear all cookies
78//! context.clear_cookies().clear().await?;
79//!
80//! // Clear cookies matching a pattern
81//! context.clear_cookies()
82//!     .domain("example.com")
83//!     .clear()
84//!     .await?;
85//! # Ok(())
86//! # }
87//! ```
88//!
89//! ## Storage State
90//!
91//! Save and restore browser state for authentication:
92//!
93//! ```ignore
94//! use viewpoint_core::{Browser, StorageStateSource};
95//!
96//! # async fn example() -> Result<(), viewpoint_core::CoreError> {
97//! # let browser = Browser::launch().headless(true).launch().await?;
98//! # let context = browser.new_context().await?;
99//! // Save storage state after login
100//! context.storage_state()
101//!     .path("auth.json")
102//!     .save()
103//!     .await?;
104//!
105//! // Create a new context with saved state
106//! let context = browser.new_context_builder()
107//!     .storage_state_path("auth.json")
108//!     .build()
109//!     .await?;
110//! # Ok(())
111//! # }
112//! ```
113//!
114//! ## Event Handling
115//!
116//! ```ignore
117//! use viewpoint_core::Browser;
118//!
119//! # async fn example() -> Result<(), viewpoint_core::CoreError> {
120//! # let browser = Browser::launch().headless(true).launch().await?;
121//! # let context = browser.new_context().await?;
122//! // Listen for new pages
123//! let handler_id = context.on_page(|page_info| async move {
124//!     println!("New page created: {}", page_info.target_id);
125//!     Ok(())
126//! }).await;
127//!
128//! // Listen for context close
129//! context.on_close(|| async {
130//!     println!("Context closed");
131//!     Ok(())
132//! }).await;
133//!
134//! // Remove handler later
135//! context.off_page(handler_id).await;
136//! # Ok(())
137//! # }
138//! ```
139//!
140//! ## Tracing
141//!
142//! ```ignore
143//! use viewpoint_core::Browser;
144//!
145//! # async fn example() -> Result<(), viewpoint_core::CoreError> {
146//! # let browser = Browser::launch().headless(true).launch().await?;
147//! # let context = browser.new_context().await?;
148//! // Start tracing
149//! context.tracing().start().await?;
150//!
151//! // ... perform actions ...
152//!
153//! // Stop and save trace
154//! context.tracing().stop("trace.zip").await?;
155//! # Ok(())
156//! # }
157//! ```
158
159mod api;
160pub mod binding;
161mod construction;
162mod cookies;
163mod emulation;
164pub mod events;
165mod har;
166mod page_events;
167mod page_factory;
168mod page_management;
169mod permissions;
170pub mod routing;
171mod routing_impl;
172mod scripts;
173pub mod storage;
174mod storage_restore;
175mod test_id;
176mod timeout;
177pub mod trace;
178mod tracing_access;
179pub mod types;
180mod weberror;
181
182pub use cookies::ClearCookiesBuilder;
183pub use emulation::SetGeolocationBuilder;
184
185// HashMap is used in emulation.rs
186use std::sync::Arc;
187use std::time::Duration;
188
189use tokio::sync::RwLock;
190use tracing::{debug, info, instrument};
191
192use viewpoint_cdp::CdpConnection;
193use viewpoint_cdp::protocol::target_domain::DisposeBrowserContextParams;
194
195use crate::error::ContextError;
196
197pub use events::{ContextEventManager, HandlerId};
198pub use storage::{StorageStateBuilder, StorageStateOptions};
199use trace::TracingState;
200pub use trace::{Tracing, TracingOptions};
201pub use types::{
202    ColorScheme, ContextOptions, ContextOptionsBuilder, Cookie, ForcedColors, Geolocation,
203    HttpCredentials, IndexedDbDatabase, IndexedDbEntry, IndexedDbIndex, IndexedDbObjectStore,
204    LocalStorageEntry, Permission, ProxyConfig, ReducedMotion, SameSite, StorageOrigin,
205    StorageState, StorageStateSource, ViewportSize,
206};
207pub use weberror::WebErrorHandler;
208// Re-export WebError for context-level usage
209pub use crate::page::page_error::WebError;
210
211/// Default test ID attribute name.
212pub const DEFAULT_TEST_ID_ATTRIBUTE: &str = "data-testid";
213
214/// An isolated browser context.
215///
216/// Browser contexts are similar to incognito windows - they have their own
217/// cookies, cache, and storage that are isolated from other contexts.
218///
219/// # Features
220///
221/// - **Cookie Management**: Add, get, and clear cookies
222/// - **Storage State**: Save and restore browser state
223/// - **Permissions**: Grant permissions like geolocation, camera, etc.
224/// - **Geolocation**: Mock browser location
225/// - **HTTP Credentials**: Basic/Digest authentication
226/// - **Extra Headers**: Add headers to all requests
227/// - **Offline Mode**: Simulate network offline conditions
228/// - **Event Handling**: Listen for page creation and context close events
229/// - **Init Scripts**: Scripts that run before every page load
230/// - **Custom Test ID**: Configure which attribute is used for test IDs
231///
232/// # Ownership
233///
234/// Contexts can be either "owned" (created by us) or "external" (discovered when
235/// connecting to an existing browser). When closing an external context, the
236/// underlying browser context is not disposed - only our connection to it is closed.
237pub struct BrowserContext {
238    /// CDP connection.
239    connection: Arc<CdpConnection>,
240    /// Browser context ID.
241    context_id: String,
242    /// Context index for element ref generation.
243    /// Each context is assigned a unique index for generating scoped element refs
244    /// in the format `c{contextIndex}p{pageIndex}e{counter}`.
245    context_index: usize,
246    /// Whether the context has been closed.
247    closed: bool,
248    /// Whether we own this context (created it) vs discovered it.
249    /// Owned contexts are disposed when closed; external contexts are not.
250    owned: bool,
251    /// Created pages (weak tracking for `pages()` method).
252    pages: Arc<RwLock<Vec<PageInfo>>>,
253    /// Counter for assigning page indices within this context.
254    page_index_counter: std::sync::atomic::AtomicUsize,
255    /// Default timeout for actions.
256    default_timeout: Duration,
257    /// Default timeout for navigation.
258    default_navigation_timeout: Duration,
259    /// Context options used to create this context.
260    options: ContextOptions,
261    /// Web error handler.
262    weberror_handler: Arc<RwLock<Option<WebErrorHandler>>>,
263    /// Event manager for context-level events.
264    event_manager: Arc<ContextEventManager>,
265    /// Context-level route registry.
266    route_registry: Arc<routing::ContextRouteRegistry>,
267    /// Context-level binding registry.
268    binding_registry: Arc<binding::ContextBindingRegistry>,
269    /// Init scripts to run on every page load.
270    init_scripts: Arc<RwLock<Vec<String>>>,
271    /// Custom test ID attribute name (defaults to "data-testid").
272    test_id_attribute: Arc<RwLock<String>>,
273    /// HAR recorder for capturing network traffic.
274    har_recorder: Arc<RwLock<Option<crate::network::HarRecorder>>>,
275    /// Shared tracing state for persistent tracing across `tracing()` calls.
276    tracing_state: Arc<RwLock<TracingState>>,
277}
278
279// Manual Debug implementation since WebErrorHandler doesn't implement Debug
280impl std::fmt::Debug for BrowserContext {
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        f.debug_struct("BrowserContext")
283            .field("context_id", &self.context_id)
284            .field("context_index", &self.context_index)
285            .field("closed", &self.closed)
286            .field("owned", &self.owned)
287            .field("default_timeout", &self.default_timeout)
288            .field(
289                "default_navigation_timeout",
290                &self.default_navigation_timeout,
291            )
292            .finish_non_exhaustive()
293    }
294}
295
296/// Information about a page in the context.
297#[derive(Debug, Clone)]
298pub struct PageInfo {
299    /// Target ID.
300    pub target_id: String,
301    /// Session ID (may be empty if not tracked).
302    pub session_id: String,
303}
304
305impl BrowserContext {
306    // Construction methods (new, with_options, from_existing, apply_options) are in construction.rs
307
308    // Page management methods (new_page, pages) are in page_management.rs
309
310    // Cookie methods are in cookies.rs
311
312    // Storage state methods are in storage.rs
313
314    // Permissions methods are in permissions.rs
315
316    // =========================================================================
317    // Geolocation
318    // =========================================================================
319
320    /// Set the geolocation.
321    ///
322    /// # Example
323    ///
324    /// ```no_run
325    /// use viewpoint_core::BrowserContext;
326    ///
327    /// # async fn example(context: &BrowserContext) -> Result<(), viewpoint_core::CoreError> {
328    /// // San Francisco
329    /// context.set_geolocation(37.7749, -122.4194).await?;
330    /// # Ok(())
331    /// # }
332    /// ```
333    ///
334    /// # Errors
335    ///
336    /// Returns an error if setting geolocation fails.
337    pub fn set_geolocation(&self, latitude: f64, longitude: f64) -> SetGeolocationBuilder<'_> {
338        SetGeolocationBuilder::new(self, latitude, longitude)
339    }
340
341    // clear_geolocation, set_extra_http_headers, set_offline are in emulation.rs
342
343    // =========================================================================
344    // Ownership and Status
345    // =========================================================================
346
347    /// Check if this context is owned (created by us) or external.
348    ///
349    /// External contexts are discovered when connecting to an already-running browser.
350    /// They are not disposed when closed.
351    pub fn is_owned(&self) -> bool {
352        self.owned
353    }
354
355    /// Check if this is the default browser context.
356    ///
357    /// The default context represents the browser's main profile and has an empty ID.
358    pub fn is_default(&self) -> bool {
359        self.context_id.is_empty()
360    }
361
362    // Timeout configuration methods are in timeout.rs
363
364    // Init script methods are in scripts.rs
365
366    // =========================================================================
367    // Context Lifecycle
368    // =========================================================================
369
370    /// Close this browser context and all its pages.
371    ///
372    /// For contexts we created (owned), this disposes the context via CDP.
373    /// For external contexts (discovered when connecting to an existing browser),
374    /// this only closes our connection without disposing the context.
375    ///
376    /// # Errors
377    ///
378    /// Returns an error if closing fails.
379    #[instrument(level = "info", skip(self), fields(context_id = %self.context_id, owned = self.owned))]
380    pub async fn close(&mut self) -> Result<(), ContextError> {
381        if self.closed {
382            debug!("Context already closed");
383            return Ok(());
384        }
385
386        info!("Closing browser context");
387
388        // Auto-save HAR if recording is active
389        if let Some(recorder) = self.har_recorder.write().await.take() {
390            if let Err(e) = recorder.save().await {
391                debug!("Failed to auto-save HAR on close: {}", e);
392            } else {
393                debug!(path = %recorder.path().display(), "Auto-saved HAR on close");
394            }
395        }
396
397        // Emit close event before cleanup
398        self.event_manager.emit_close().await;
399
400        // Only dispose the context if we own it
401        // External contexts (from connecting to existing browser) should not be disposed
402        if self.owned && !self.context_id.is_empty() {
403            debug!("Disposing owned browser context");
404            self.connection
405                .send_command::<_, serde_json::Value>(
406                    "Target.disposeBrowserContext",
407                    Some(DisposeBrowserContextParams {
408                        browser_context_id: self.context_id.clone(),
409                    }),
410                    None,
411                )
412                .await?;
413        } else {
414            debug!("Skipping dispose for external/default context");
415        }
416
417        // Clear all event handlers
418        self.event_manager.clear().await;
419
420        self.closed = true;
421        info!("Browser context closed");
422        Ok(())
423    }
424
425    /// Get the context ID.
426    pub fn id(&self) -> &str {
427        &self.context_id
428    }
429
430    /// Get the context index.
431    ///
432    /// This index is used for generating scoped element refs in the format
433    /// `c{contextIndex}p{pageIndex}e{counter}`. Each context has a unique
434    /// index to prevent ref collisions across contexts.
435    pub fn index(&self) -> usize {
436        self.context_index
437    }
438
439    /// Get the next page index for this context.
440    ///
441    /// This is called internally when creating a new page to assign
442    /// a unique index within this context.
443    pub(crate) fn next_page_index(&self) -> usize {
444        self.page_index_counter
445            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
446    }
447
448    /// Check if this context has been closed.
449    pub fn is_closed(&self) -> bool {
450        self.closed
451    }
452
453    /// Get a reference to the CDP connection.
454    pub fn connection(&self) -> &Arc<CdpConnection> {
455        &self.connection
456    }
457
458    /// Get the context ID.
459    pub fn context_id(&self) -> &str {
460        &self.context_id
461    }
462
463    // Web error event methods are in weberror.rs (on_weberror, off_weberror)
464
465    // Page and close event methods are in page_events.rs (on_page, off_page, on_close, off_close, wait_for_page)
466
467    // Context-level routing methods are in routing_impl.rs
468
469    // HAR recording methods are in har.rs
470
471    // Exposed function methods are in binding.rs (expose_function, remove_exposed_function)
472
473    // API request context methods are in api.rs (request, sync_cookies_from_api)
474
475    // Tracing method is in tracing_access.rs
476
477    // Test ID attribute methods are in test_id.rs
478}
479
480// ClearCookiesBuilder is in cookies.rs
481// SetGeolocationBuilder is in emulation.rs