eoka 0.14.3

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock};

use serde_json::{json, Value};

use super::{Action, ActionOptions, ActionReceipt, LocatorQuery, LocatorSpec};
use crate::util::LockExt;
use crate::{cdp::Session, error::classify, Error, ErrorCode, Page, Result};

/// A read-only observation of a resolved control, without its input value.
#[derive(Debug, Clone)]
pub struct ControlState {
    /// Whether the node is attached to the document.
    pub connected: bool,
    /// Whether the node is rendered and visible.
    pub visible: bool,
    /// Whether the node is not disabled.
    pub enabled: bool,
}

/// A lazy query bound to a page; it holds no cached DOM node.
#[derive(Clone)]
pub struct Locator {
    pub(crate) page: Page,
    pub(crate) spec: LocatorSpec,
}

impl Locator {
    /// Inspect the current match without dispatching input or generating a selector.
    pub async fn state(&self) -> Result<Option<ControlState>> {
        let Some(node) = resolve(&self.page, &self.spec).await? else {
            return Ok(None);
        };
        let properties = node.properties().await?;
        Ok(Some(ControlState {
            connected: properties["connected"] == true,
            visible: properties["visible"] == true,
            enabled: properties["disabled"] != true,
        }))
    }

    /// Explicitly select the first matching element.
    pub fn first(self) -> Self {
        self.nth(0)
    }
    /// Explicitly select a zero-based match.
    pub fn nth(mut self, index: usize) -> Self {
        self.spec.index = Some(index);
        self
    }
    /// Restrict resolution to a pinned frame identifier.
    pub fn in_frame(mut self, frame_id: impl Into<String>) -> Self {
        self.spec.frame_id = Some(frame_id.into());
        self
    }
    /// Return the serializable query.
    pub fn specification(&self) -> LocatorSpec {
        self.spec.clone()
    }

    /// Click once and verify the supplied completion condition.
    pub async fn click(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(Action::click(self.spec.clone(), false), options)
            .await
    }
    /// Click with paced input and verify the supplied condition.
    pub async fn human_click(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(Action::click(self.spec.clone(), true), options)
            .await
    }
    /// Replace and verify the target value.
    pub async fn fill(&self, value: &str, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::fill(self.spec.clone(), value, Default::default()),
            options,
        )
        .await
    }
    /// Set and verify selected option values.
    pub async fn select(
        &self,
        values: Vec<String>,
        options: ActionOptions,
    ) -> Result<ActionReceipt> {
        self.run(
            Action::Select {
                target: self.spec.clone(),
                values,
            },
            options,
        )
        .await
    }
    /// Double-click and verify the supplied completion condition.
    pub async fn double_click(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::Click {
                target: self.spec.clone(),
                human: false,
                double: true,
            },
            options,
        )
        .await
    }
    /// Move the pointer over the target and verify hover.
    pub async fn hover(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(Action::hover(self.spec.clone(), false), options)
            .await
    }
    /// Hover with paced pointer movement and verify hover.
    pub async fn human_hover(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(Action::hover(self.spec.clone(), true), options)
            .await
    }
    /// Focus the target and type without clearing; verify the supplied condition.
    pub async fn type_text(&self, text: &str, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::type_text(self.spec.clone(), text, Default::default()),
            options,
        )
        .await
    }
    /// Focus the target and verify focus.
    pub async fn focus(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::Focus {
                target: self.spec.clone(),
            },
            options,
        )
        .await
    }
    /// Focus the target, press Enter and verify the supplied condition.
    pub async fn submit(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::Submit {
                target: self.spec.clone(),
            },
            options,
        )
        .await
    }
    /// Scroll the target into the viewport and verify it is there.
    pub async fn scroll_into_view(&self, options: ActionOptions) -> Result<ActionReceipt> {
        self.run(
            Action::ScrollIntoView {
                target: self.spec.clone(),
            },
            options,
        )
        .await
    }
    async fn run(&self, action: Action, options: ActionOptions) -> Result<ActionReceipt> {
        self.page.act(action, options).await
    }
    /// Set and verify the uploaded files.
    pub async fn upload(
        &self,
        files: Vec<String>,
        options: ActionOptions,
    ) -> Result<ActionReceipt> {
        self.run(
            Action::Upload {
                target: self.spec.clone(),
                files,
            },
            options,
        )
        .await
    }
}

impl Page {
    /// Create a lazy CSS locator requiring a unique match.
    pub fn locator(&self, selector: &str) -> Locator {
        self.locator_spec(LocatorSpec::css(selector))
    }
    /// Create a lazy, case-insensitive text locator.
    pub fn locator_text(&self, text: &str) -> Locator {
        self.locator_spec(LocatorSpec::text(text))
    }
    /// Bind a serializable locator to this page.
    pub fn locator_spec(&self, spec: LocatorSpec) -> Locator {
        Locator {
            page: self.clone(),
            spec,
        }
    }
}

pub(super) fn call_value(result: &Value) -> Result<Value> {
    if let Some(exception) = result.get("exceptionDetails").filter(|v| !v.is_null()) {
        return Err(Error::javascript_exception(exception));
    }
    Ok(result["result"]["value"].clone())
}

pub(super) struct Node {
    pub session: Session,
    pub object: String,
    pub frame_id: Option<String>,
    group: String,
    attached: bool,
    hover_observer: Option<String>,
}

impl Node {
    pub(super) fn call_params(&self, body: &str, args: Vec<Value>) -> Value {
        json!({
            "objectId":self.object, "functionDeclaration":body,
            "arguments":args.into_iter().map(|value| json!({"value":value})).collect::<Vec<_>>(),
            "returnByValue":true, "awaitPromise":true,
        })
    }

    pub(super) async fn call(&self, body: &str, args: Vec<Value>) -> Result<Value> {
        let result: Value = self
            .session
            .send("Runtime.callFunctionOn", &self.call_params(body, args))
            .await?;
        call_value(&result)
    }

    pub(super) fn property(properties: &Value, field: &str) -> Value {
        let mut actual = properties[field].clone();
        if field == "selected" {
            if let Some(values) = actual.as_array_mut() {
                values.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
            }
        }
        actual
    }

    pub(super) async fn properties(&self) -> Result<Value> {
        let mut properties = self.call(include_str!("properties.js"), vec![]).await?;
        if let Some(observer) = &self.hover_observer {
            let result: Value = self.session.send("Runtime.callFunctionOn", &json!({"objectId":observer,"functionDeclaration":"function(){return this.seen}","returnByValue":true})).await?;
            properties["hovered"] = result["result"]["value"].clone();
        }
        Ok(properties)
    }

    pub(super) async fn arm_hover(&mut self) -> Result<()> {
        let result: Value = self.session.send("Runtime.callFunctionOn", &json!({"objectId":self.object,"objectGroup":self.group,"returnByValue":false,
            "functionDeclaration":"function(){const target=this;const state={seen:false};const doc=this.ownerDocument;const handler=e=>{if(e.isTrusted && (e.target===target || target.contains(e.target))){state.seen=true;state.dispose()}};const timer=setTimeout(()=>state.dispose(),30000);state.dispose=()=>{clearTimeout(timer);doc.removeEventListener('mousemove',handler,true);doc.removeEventListener('mouseover',handler,true)};doc.addEventListener('mousemove',handler,true);doc.addEventListener('mouseover',handler,true);return state}"})).await?;
        self.hover_observer = Some(
            result["result"]["objectId"]
                .as_str()
                .ok_or_else(|| Error::cdp_msg("Could not arm hover observation"))?
                .into(),
        );
        Ok(())
    }
}

impl Drop for Node {
    fn drop(&mut self) {
        let session = self.session.clone();
        let group = std::mem::take(&mut self.group);
        let attached = self.attached;
        let observer = self.hover_observer.take();
        crate::util::spawn_detached(async move {
            let _ = tokio::time::timeout(std::time::Duration::from_secs(2), async {
                if let Some(observer)=observer {
                    let _=session.send::<_,Value>("Runtime.callFunctionOn",&json!({"objectId":observer,"functionDeclaration":"function(){this.dispose()}"})).await;
                }
                let _ = session
                    .send::<_, Value>(
                        "Runtime.releaseObjectGroup",
                        &json!({"objectGroup":group}),
                    )
                    .await;
                if attached {
                    let _ = session.detach().await;
                }
            })
            .await;
        });
    }
}

pub(crate) async fn is_visible(page: &Page, spec: &LocatorSpec) -> Result<bool> {
    let Some(node) = resolve(page, spec).await? else {
        return Ok(false);
    };
    Ok(node.properties().await?["visible"] == true)
}

pub(super) async fn resolve(page: &Page, spec: &LocatorSpec) -> Result<Option<Node>> {
    static NEXT: AtomicU64 = AtomicU64::new(1);
    let mut node = Node {
        session: page.session().clone(),
        object: String::new(),
        frame_id: spec.frame_id.clone(),
        group: format!("eoka-action-{}", NEXT.fetch_add(1, Ordering::Relaxed)),
        attached: false,
        hover_observer: None,
    };
    // Locators always run in an isolated world, so page scripts can neither
    // observe them nor patch the DOM APIs they use. A page target's main
    // frame id is its target id.
    let frame_id = match &spec.frame_id {
        Some(frame_id) => {
            let target = page.frame_target_id(frame_id).await?;
            if target != page.target_id() {
                node.session = page.session().attach_frame_target(&target).await?;
                node.attached = true;
            }
            frame_id.clone()
        }
        None => page.target_id().to_owned(),
    };
    let pinned = match spec.query {
        LocatorQuery::BackendNode { id } => Some(json!({"backendNodeId": id})),
        LocatorQuery::Node { id } => Some(json!({"nodeId": id})),
        LocatorQuery::Css { .. }
        | LocatorQuery::Text { .. }
        | LocatorQuery::Placeholder { .. }
        | LocatorQuery::Role { .. } => None,
    };
    if let Some(mut params) = pinned {
        let stale = || {
            Error::coded(
                ErrorCode::TargetStale,
                "pinned element no longer refers to a live node",
            )
        };
        params["objectGroup"] = json!(node.group);
        let result: Value = node.session.send("DOM.resolveNode", &params).await?;
        node.object = result["object"]["objectId"]
            .as_str()
            .ok_or_else(stale)?
            .into();
        if !node
            .call("function(){return this.isConnected === true}", vec![])
            .await?
            .as_bool()
            .unwrap_or(false)
        {
            return Err(stale());
        }
        return Ok(Some(node));
    }
    let query = serde_json::to_string(&spec.query)?;
    let expression = format!(
        "({})({query})",
        include_str!("resolve.js").replace(
            "TEXT_CANDIDATES",
            include_str!("../page/text_candidates.js")
        )
    );
    let mut attempt = 0;
    let result: Value = loop {
        attempt += 1;
        let world = isolated_world(&node.session, &frame_id).await?;
        let guarded = format!(
            "(()=>{{if(globalThis.__eoka_world!=={}){{throw new Error('{WORLD_MISMATCH}')}}return {expression}}})()",
            world.token
        );
        let params = json!({"expression":guarded,"objectGroup":node.group,"returnByValue":false,"contextId":world.context});
        let result = node
            .session
            .send::<_, Value>("Runtime.evaluate", &params)
            .await;
        let stale = match &result {
            Err(error) => classify::is(error, classify::CdpFailure::ContextLost),
            Ok(value) => value["exceptionDetails"]["exception"]["description"]
                .as_str()
                .is_some_and(|text| text.contains(WORLD_MISMATCH)),
        };
        if stale && attempt < 3 {
            forget_isolated_world(&node.session, &frame_id);
            continue;
        }
        break result?;
    };
    if let Some(exception) = result.get("exceptionDetails") {
        let stale = exception["exception"]["description"]
            .as_str()
            .is_some_and(|text| text.contains(WORLD_MISMATCH));
        // A world that stayed stale after three attempts is a page-state
        // race; any other exception means the query itself is invalid.
        return Err(if stale {
            Error::cdp_msg("Invalid locator query")
        } else {
            Error::invalid_argument("invalid locator query")
        });
    }
    node.object = result["result"]["objectId"]
        .as_str()
        .ok_or_else(|| Error::cdp_msg("Locator did not return an array"))?
        .into();
    #[allow(
        clippy::cast_possible_truncation,
        reason = "a JavaScript array length is at most 2^32 - 1, which fits usize on 32- and 64-bit targets"
    )]
    let count = node
        .call("function(){return this.length}", vec![])
        .await?
        .as_u64()
        .ok_or_else(|| Error::cdp_msg("Invalid locator count"))? as usize;
    let index = spec.index.unwrap_or(0);
    if count == 0 || index >= count {
        return Ok(None);
    }
    if count > 1 && spec.index.is_none() {
        return Err(Error::coded(
            ErrorCode::AmbiguousTarget,
            "locator matched multiple elements; select first/nth explicitly",
        ));
    }
    let result: Value = node
        .session
        .send(
            "Runtime.callFunctionOn",
            &json!({
                "objectId":node.object,"functionDeclaration":"function(i){return this[i]}",
                "arguments":[{"value":index}],"returnByValue":false,"objectGroup":node.group,
            }),
        )
        .await?;
    node.object = result["result"]["objectId"]
        .as_str()
        .ok_or_else(|| Error::cdp_msg("Locator element disappeared"))?
        .into();
    Ok(Some(node))
}

const WORLD_MISMATCH: &str = "eoka: stale isolated world";

#[derive(Clone, Copy)]
struct World {
    context: i64,
    token: u64,
}

/// Cached worlds keyed by (session id, frame id).
fn worlds() -> MutexGuard<'static, HashMap<(String, String), World>> {
    static WORLDS: OnceLock<Mutex<HashMap<(String, String), World>>> = OnceLock::new();
    WORLDS.get_or_init(Default::default).lock_unpoisoned()
}

/// The cached eoka isolated world for a frame, created on first use.
///
/// Creating a world per poll grew Chrome's world list on every 25ms retry.
/// A navigation destroys the world; callers detect that through the token
/// check or a lost-context error and call [`forget_isolated_world`]. The
/// token, set inside the world, also catches a reused context id.
async fn isolated_world(session: &Session, frame_id: &str) -> Result<World> {
    let key = (session.session_id().to_owned(), frame_id.to_owned());
    if let Some(world) = worlds().get(&key).copied() {
        return Ok(world);
    }
    let context = session.create_isolated_world(frame_id).await?;
    let token = fastrand::u64(1..u64::MAX >> 11);
    session
        .send::<_, Value>(
            "Runtime.evaluate",
            &json!({"expression":format!("globalThis.__eoka_world={token}"),"contextId":context}),
        )
        .await?;
    let world = World { context, token };
    let mut cache = worlds();
    if cache.len() >= 512 {
        cache.clear();
    }
    cache.insert(key, world);
    Ok(world)
}

fn forget_isolated_world(session: &Session, frame_id: &str) {
    worlds().remove(&(session.session_id().to_owned(), frame_id.to_owned()));
}