browser-commander 0.19.0

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

mod adapter;
pub mod bidi;
mod capabilities;
mod snapshot;
mod storage;
pub use snapshot::{launch_webdriver_snapshot, WebDriverSnapshotResult};

pub use capabilities::build_capabilities;
pub use fantoccini::{Client as WebDriverClient, Locator};

use crate::{
    browser::profile_directory::{
        create_temporary_user_data_dir_with_first_run, remove_user_data_dir,
    },
    downloads::{normalize_download_options, DownloadManager, DownloadSetting},
    utilities::{start_process, ManagedProcess, StartProcessOptions},
};
use anyhow::{anyhow, Context, Result};
use bidi::BidiClient;
use serde_json::{json, Value};
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::Arc,
    time::Duration,
};
use tokio::{
    net::TcpStream,
    sync::OnceCell,
    time::{sleep, timeout},
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WebDriverBrowser {
    #[default]
    Chrome,
    Firefox,
    Safari,
    SafariTechnologyPreview,
}

impl WebDriverBrowser {
    pub fn is_safari(self) -> bool {
        matches!(self, Self::Safari | Self::SafariTechnologyPreview)
    }
}

#[derive(Clone, Debug)]
pub struct WebDriverOptions {
    pub browser: WebDriverBrowser,
    /// Matching chromedriver/geckodriver; otherwise resolved through PATH.
    pub driver_executable: Option<PathBuf>,
    pub browser_executable: Option<PathBuf>,
    /// An existing dedicated profile is retained on close. Never use a profile
    /// that is already open in another browser.
    pub user_data_dir: Option<PathBuf>,
    pub headless: bool,
    pub sandbox: bool,
    pub args: Vec<String>,
    pub preferences: Value,
    pub local_state: Value,
    pub default_browser_check: Option<bool>,
    pub first_run: bool,
    pub automation_parity: bool,
    pub capabilities: serde_json::Map<String, Value>,
    /// Added to the driver and inherited by its browser; parent stays unchanged.
    pub env: Option<HashMap<String, String>>,
    pub downloads: DownloadSetting,
    pub launch_timeout: Duration,
    /// Request webSocketUrl and connect when the driver supplies it.
    pub bidi: bool,
}

impl Default for WebDriverOptions {
    fn default() -> Self {
        Self {
            browser: WebDriverBrowser::Chrome,
            driver_executable: None,
            browser_executable: None,
            user_data_dir: None,
            headless: false,
            sandbox: true,
            args: Vec::new(),
            preferences: json!({}),
            local_state: json!({}),
            default_browser_check: None,
            first_run: false,
            automation_parity: true,
            capabilities: Default::default(),
            env: None,
            downloads: DownloadSetting::Off,
            launch_timeout: Duration::from_secs(30),
            bidi: true,
        }
    }
}

struct OwnedDriver {
    child: Option<Arc<ManagedProcess>>,
    profile: PathBuf,
    temporary: bool,
}

impl OwnedDriver {
    async fn stop(&mut self) -> Result<()> {
        if let Some(child) = self.child.take() {
            child.kill();
            child.wait_timeout(Duration::from_secs(6)).await;
        }
        if self.temporary {
            remove_user_data_dir(&self.profile).await?;
        }
        Ok(())
    }
}

impl Drop for OwnedDriver {
    fn drop(&mut self) {
        let profile = self.profile.clone();
        let temporary = self.temporary;
        if let Some(child) = self.child.take() {
            child.kill();
            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
                runtime.spawn(async move {
                    child.wait_timeout(Duration::from_secs(6)).await;
                    if temporary {
                        let _ = remove_user_data_dir(&profile).await;
                    }
                });
                return;
            }
        }
        if temporary {
            let _ = std::fs::remove_dir_all(profile);
        }
    }
}

/// Owns driver, browser session, BiDi and the optional download watcher.
/// All typed Fantoccini APIs are available through [`Self::client`]. Close
/// waits for downloads before quitting; Drop stops the owned driver as well.
pub struct ManagedWebDriver {
    browser: WebDriverBrowser,
    client: WebDriverClient,
    bidi: Option<Arc<BidiClient>>,
    downloads: Option<Arc<DownloadManager>>,
    profile: PathBuf,
    driver: tokio::sync::Mutex<OwnedDriver>,
    closed: OnceCell<()>,
}

impl ManagedWebDriver {
    pub fn client(&self) -> &WebDriverClient {
        &self.client
    }
    pub fn bidi(&self) -> Option<&Arc<BidiClient>> {
        self.bidi.as_ref()
    }
    pub fn downloads(&self) -> Option<&Arc<DownloadManager>> {
        self.downloads.as_ref()
    }
    pub fn user_data_dir(&self) -> &Path {
        &self.profile
    }
    pub fn driver_pid(&self) -> Option<u32> {
        self.driver
            .try_lock()
            .ok()
            .and_then(|driver| driver.child.as_ref().and_then(|child| child.pid()))
    }
    pub(crate) fn process_handle(&self) -> crate::browser::browser_process::BrowserProcess {
        let child = self
            .driver
            .try_lock()
            .expect("new driver is unlocked")
            .child
            .as_ref()
            .unwrap()
            .clone();
        crate::browser::browser_process::BrowserProcess::from_control(child)
    }
    /// Reject unsupported Safari features before starting an operation.
    pub fn require_feature(&self, feature: &str) -> Result<(), crate::core::engine::EngineError> {
        if self.browser.is_safari() {
            Err(crate::browser::safari::unsupported(feature))
        } else {
            Ok(())
        }
    }
    pub async fn close(&self) -> Result<()> {
        self.closed
            .get_or_try_init(|| async {
                if let Some(manager) = &self.downloads {
                    manager.dispose().await;
                }
                if let Some(bidi) = &self.bidi {
                    bidi.close().await;
                }
                // Even a dead session must release its driver and copied profile.
                let result = timeout(Duration::from_secs(6), self.client.clone().close()).await;
                self.driver.lock().await.stop().await?;
                if let Ok(Err(error)) = result {
                    tracing::debug!(%error, "WebDriver session was already closed");
                }
                Ok::<(), anyhow::Error>(())
            })
            .await
            .map(|_| ())
    }
}

impl Drop for ManagedWebDriver {
    fn drop(&mut self) {
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            let manager = self.downloads.take();
            let bidi = self.bidi.take();
            runtime.spawn(async move {
                if let Some(manager) = manager {
                    manager.dispose().await;
                }
                if let Some(bidi) = bidi {
                    bidi.close().await;
                }
            });
        }
    }
}

/// Start a locally installed driver. No npm package or Node process is used.
pub async fn launch_webdriver(options: WebDriverOptions) -> Result<ManagedWebDriver> {
    launch_owned(options, false).await
}

async fn launch_owned(
    mut options: WebDriverOptions,
    own_profile: bool,
) -> Result<ManagedWebDriver> {
    if options.launch_timeout.is_zero() {
        return Err(anyhow!("launch_timeout must be positive"));
    }
    // Validate before creating profiles or starting a process.
    build_capabilities(&options, Path::new("validation-profile"), None)?;
    let safari = options.browser.is_safari();
    if safari && !cfg!(target_os = "macos") && options.driver_executable.is_none() {
        return Err(crate::browser::safari::unsupported("Safari launch outside macOS").into());
    }
    let temporary = !safari && (own_profile || options.user_data_dir.is_none());
    let profile = if safari {
        PathBuf::new()
    } else {
        match &options.user_data_dir {
            Some(path) => {
                std::fs::create_dir_all(path)?;
                std::fs::canonicalize(path)?
            }
            None => create_temporary_user_data_dir_with_first_run(None, options.first_run)?,
        }
    };
    let mut owner = OwnedDriver {
        child: None,
        profile: profile.clone(),
        temporary,
    };
    if options.browser == WebDriverBrowser::Chrome {
        use crate::browser::profile_directory::{
            configure_user_data_dir_for_profile, prepare_user_data_dir_with_first_run,
        };
        prepare_user_data_dir_with_first_run(&profile, options.first_run)?;
        let selected = options
            .args
            .iter()
            .find_map(|arg| arg.strip_prefix("--profile-directory="))
            .unwrap_or("Default");
        configure_user_data_dir_for_profile(
            &profile,
            selected,
            options.default_browser_check,
            &options.preferences,
            &options.local_state,
        )?;
        if options.automation_parity
            && !options
                .args
                .iter()
                .any(|arg| arg.starts_with("--remote-debugging-port"))
        {
            options.args.push(format!(
                "--remote-debugging-port={}",
                crate::browser::debugging_port::reserve_loopback_port()?
            ));
        }
    }
    let manager = normalize_download_options(options.downloads.clone())
        .map(DownloadManager::create)
        .transpose()?;
    let staging = manager
        .as_ref()
        .map(|manager| crate::downloads::sources::prepare_staging_directory(&manager.directory))
        .transpose()?;
    let capabilities = build_capabilities(&options, &profile, staging.as_deref())?;
    let port = crate::browser::debugging_port::reserve_loopback_port()?;
    let executable = options.driver_executable.clone().unwrap_or_else(|| {
        PathBuf::from(match options.browser {
            WebDriverBrowser::Chrome => "chromedriver",
            WebDriverBrowser::Firefox => "geckodriver",
            WebDriverBrowser::Safari => "/usr/bin/safaridriver",
            WebDriverBrowser::SafariTechnologyPreview => {
                "/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver"
            }
        })
    });
    let args = match options.browser {
        WebDriverBrowser::Chrome => {
            vec![format!("--port={port}"), "--allowed-ips=127.0.0.1".into()]
        }
        WebDriverBrowser::Firefox => vec![
            "--host".into(),
            "127.0.0.1".into(),
            "--port".into(),
            port.to_string(),
            // geckodriver otherwise shares port 9222 across sessions, even
            // when its WebDriver HTTP port is allocated dynamically.
            "--websocket-port".into(),
            "0".into(),
        ],
        WebDriverBrowser::Safari | WebDriverBrowser::SafariTechnologyPreview => {
            vec!["--port".into(), port.to_string()]
        }
    };
    let output = Arc::new(std::sync::Mutex::new(Vec::new()));
    let tail = output.clone();
    let listener: crate::utilities::OutputListener = Arc::new(move |chunk| {
        tracing::debug!(output = %String::from_utf8_lossy(chunk), "WebDriver output");
        let mut tail = tail.lock().unwrap();
        tail.extend_from_slice(chunk);
        if tail.len() > 8192 {
            let excess = tail.len() - 8192;
            tail.drain(..excess);
        }
    });
    owner.child = Some(Arc::new(
        start_process(
            executable.to_string_lossy().as_ref(),
            &args,
            StartProcessOptions {
                env: {
                    let mut env = options.env.clone().unwrap_or_default();
                    if options.browser == WebDriverBrowser::Firefox && !options.sandbox {
                        env.insert("MOZ_DISABLE_CONTENT_SANDBOX".into(), "1".into());
                    }
                    (!env.is_empty()).then_some(env)
                },
                on_stdout: vec![listener.clone()],
                on_stderr: vec![listener],
                ..Default::default()
            },
        )
        .await
        .with_context(|| format!("start WebDriver {}", executable.display()))?,
    ));
    let endpoint = format!("http://127.0.0.1:{port}");
    let launched = timeout(options.launch_timeout, async {
        loop {
            if let Some(code) = owner.child.as_ref().and_then(|child| child.exit_code()) {
                return Err(anyhow!(
                    "WebDriver exited with {code}: {}",
                    String::from_utf8_lossy(&output.lock().unwrap())
                ));
            }
            if TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
                break;
            }
            sleep(Duration::from_millis(25)).await;
        }
        let client = fantoccini::ClientBuilder::rustls()?
            .capabilities(capabilities)
            .connect(&endpoint)
            .await?;
        // Safari reports an empty URL until its first navigation.
        if safari {
            client.goto("about:blank").await?;
        }
        Ok::<_, anyhow::Error>(client)
    })
    .await;
    let client = match launched {
        Ok(Ok(client)) => client,
        result => {
            owner.stop().await?;
            return match result {
                Ok(Err(error)) => Err(if safari {
                    crate::browser::safari::launch_error(error, options.browser)
                } else {
                    error
                }),
                _ => Err(anyhow!(
                    "WebDriver launch timed out: {}",
                    String::from_utf8_lossy(&output.lock().unwrap())
                )),
            };
        }
    };
    let mut browser = ManagedWebDriver {
        browser: options.browser,
        client,
        bidi: None,
        downloads: manager,
        profile,
        driver: tokio::sync::Mutex::new(owner),
        closed: OnceCell::new(),
    };
    let setup = async {
        if options.bidi {
            if let Some(url) = browser
                .client
                .capabilities()
                .and_then(|caps| caps.get("webSocketUrl"))
                .and_then(Value::as_str)
            {
                browser.bidi = Some(Arc::new(BidiClient::connect(url).await?));
            }
        }
        if let Some(manager) = &browser.downloads {
            manager.attach_filesystem().await?;
        }
        Ok::<(), anyhow::Error>(())
    }
    .await;
    if let Err(error) = setup {
        browser.close().await?;
        return Err(error);
    }
    Ok(browser)
}