eoka 0.17.1

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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
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, Element, 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
    }
    /// 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), 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()), 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), 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)
}

/// Calls `body` on the element `spec` pins, in the isolated world, and
/// returns its result by value. A node removed from the document can still be
/// read. The node's object group is released on drop.
pub(crate) async fn call_on(
    page: &Page,
    spec: &LocatorSpec,
    body: &str,
    args: Vec<Value>,
) -> Result<Value> {
    let params = pinned(spec).ok_or_else(|| Error::cdp_msg("element reads need a pinned node"))?;
    resolve_pinned(page, spec, params, false)
        .await?
        .call(body, args)
        .await
}

/// `spec` with an explicit first index, so several matches are not ambiguous.
fn first(mut spec: LocatorSpec) -> LocatorSpec {
    spec.index = Some(0);
    spec
}

/// The first element `spec` matches, without the strict-uniqueness check.
pub(crate) async fn first_element(page: &Page, spec: LocatorSpec) -> Result<Option<Element>> {
    let spec = &first(spec);
    in_one_document(page, |document| async move {
        match resolve(page, spec).await? {
            Some(node) => Ok(Some(node.element(page, document).await?)),
            None => Ok(None),
        }
    })
    .await
}

/// Runs `find` with the page's document count until the count is the same
/// after it, so a handle is never pinned to a count from before a navigation
/// that committed while it was being found. After three tries the last result
/// stands: its handles fail with `target_stale` rather than guess.
async fn in_one_document<T, F, Fut>(page: &Page, find: F) -> Result<T>
where
    F: Fn(u64) -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let mut tries = 0;
    loop {
        let document = page.document();
        let found = find(document).await?;
        tries += 1;
        if tries == 3 || page.document() == document {
            return Ok(found);
        }
    }
}

/// The first match's visibility, by the rule `properties.js` gives actions.
pub(crate) enum Visibility {
    /// Nothing matches.
    Missing,
    /// The first match is not visible.
    Hidden,
    /// The first match is visible; a handle to it when one was asked for.
    Visible(Option<Element>),
}

/// The visibility of the first element `spec` matches, read from the same
/// resolved node. With `element`, a visible match comes with its handle.
pub(crate) async fn first_visibility(
    page: &Page,
    spec: LocatorSpec,
    element: bool,
) -> Result<Visibility> {
    let spec = &first(spec);
    in_one_document(page, |document| async move {
        let Some(node) = resolve(page, spec).await? else {
            return Ok(Visibility::Missing);
        };
        if node.properties().await?["visible"] != true {
            return Ok(Visibility::Hidden);
        }
        Ok(Visibility::Visible(if element {
            Some(node.element(page, document).await?)
        } else {
            None
        }))
    })
    .await
}

/// Every element `spec` matches, in document (or text-priority) order.
pub(crate) async fn all_elements(page: &Page, spec: &LocatorSpec) -> Result<Vec<Element>> {
    in_one_document(page, |document| all_elements_in(page, spec, document)).await
}

async fn all_elements_in(page: &Page, spec: &LocatorSpec, document: u64) -> Result<Vec<Element>> {
    let Some(node) = query(page, spec, Pick::All).await? else {
        return Err(Error::cdp_msg("Locator did not return an array"));
    };
    // Indexed properties of the isolated-world array, in its object group so
    // dropping `node` releases them too. An empty array has none.
    let properties: Value = node
        .session
        .send(
            "Runtime.getProperties",
            &json!({"objectId":node.object,"ownProperties":true}),
        )
        .await?;
    let mut indexed: Vec<(usize, &str)> = properties["result"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|property| {
            let index = property["name"].as_str()?.parse().ok()?;
            Some((index, property["value"]["objectId"].as_str()?))
        })
        .collect();
    indexed.sort_unstable_by_key(|(index, _)| *index);
    // `node` stays alive, keeping the objects, until every id is described.
    let elements =
        futures_util::future::try_join_all(indexed.into_iter().map(|(_, object)| async {
            Ok::<_, Error>(Element {
                page: page.clone(),
                backend_node_id: describe(&node.session, object).await?,
                document,
            })
        }))
        .await?;
    drop(node);
    Ok(elements)
}

/// The backend node id of a remote object.
async fn describe(session: &Session, object: &str) -> Result<i64> {
    let described: Value = session
        .send("DOM.describeNode", &json!({ "objectId": object }))
        .await?;
    described["node"]["backendNodeId"]
        .as_i64()
        .ok_or_else(|| Error::cdp("DOM.describeNode", -1, "No backendNodeId returned"))
}

impl Node {
    /// A handle pinned to this node's backend id, in the page document
    /// `document` counted before the node was found. Top frame only.
    async fn element(&self, page: &Page, document: u64) -> Result<Element> {
        Ok(Element {
            page: page.clone(),
            backend_node_id: describe(&self.session, &self.object).await?,
            document,
        })
    }
}

/// A fresh node with its own object group, on the session that owns
/// `spec`'s frame, and that frame's id.
async fn start(page: &Page, spec: &LocatorSpec) -> Result<(Node, String)> {
    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(),
    };
    Ok((node, frame_id))
}

/// Whether a CDP reply carries eoka's stale-world exception.
fn world_mismatch(reply: &Value) -> bool {
    reply["exceptionDetails"]["exception"]["description"]
        .as_str()
        .is_some_and(|text| text.contains(WORLD_MISMATCH))
}

/// What an attempt in a stale world returns: Chrome's lost-context error, or
/// a mismatched world token.
enum Attempt<T> {
    Done(T),
    Stale(Option<Error>),
}

/// Runs `attempt` in the frame's cached isolated world. A cached world that
/// turns out stale is replaced once; a world created for this attempt is
/// never retried, so a failing read creates at most one world. When the
/// world stays stale the last real CDP error is returned, so navigation-race
/// checks still recognise it.
async fn in_world<T, F, Fut>(node: &Node, frame_id: &str, attempt: F) -> Result<T>
where
    F: Fn(World) -> Fut,
    Fut: std::future::Future<Output = Result<Attempt<T>>>,
{
    let mut last = None;
    loop {
        let world = isolated_world(&node.session, frame_id).await?;
        match attempt(world).await? {
            Attempt::Done(value) => return Ok(value),
            Attempt::Stale(error) => {
                forget_isolated_world(&node.session, frame_id);
                last = error.or(last);
                if world.fresh {
                    return Err(last.unwrap_or_else(classify::world_replaced));
                }
            }
        }
    }
}

/// Whether an error says the world's context itself is gone. Lost objects
/// and nodes from another document are not: the world may be fine.
fn stale_context(error: &Error) -> bool {
    classify::is_stale_world(error)
}

/// The `DOM.resolveNode` parameters for a pinned query, or `None`.
fn pinned(spec: &LocatorSpec) -> Option<Value> {
    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,
    }
}

pub(super) async fn resolve(page: &Page, spec: &LocatorSpec) -> Result<Option<Node>> {
    if let Some(params) = pinned(spec) {
        return resolve_pinned(page, spec, params, true).await.map(Some);
    }
    query(page, spec, spec.index.map_or(Pick::Strict, Pick::Index)).await
}

pub(crate) fn stale() -> Error {
    Error::coded(
        ErrorCode::TargetStale,
        "pinned element no longer refers to a live node",
    )
}

/// Resolves a pinned node into the isolated world of the frame whose
/// document holds it. With `connected`, a node that is no longer in the
/// document is stale, never retargeted.
///
/// Without a `frame_id` the top frame is tried first. A node of a
/// same-origin child frame resolves there too, but its reads and input
/// coordinates belong to its own frame, so it moves to that frame's world;
/// a cross-origin child frame's node does not resolve in the top world at
/// all, so the page's other frames are searched for it.
async fn resolve_pinned(
    page: &Page,
    spec: &LocatorSpec,
    params: Value,
    connected: bool,
) -> Result<Node> {
    let (mut node, frame_id) = start(page, spec).await?;
    let found = match pinned_object(&node, &frame_id, &params, connected).await? {
        Pinned::Here(object) => Some((object, None)),
        Pinned::Frame(frame) => match pinned_object(&node, &frame, &params, connected).await? {
            Pinned::Here(object) => Some((object, Some(frame))),
            Pinned::Frame(_) | Pinned::Elsewhere => None,
        },
        Pinned::Elsewhere if spec.frame_id.is_none() => {
            child_frame_object(&node, &params, connected).await?
        }
        Pinned::Elsewhere => None,
    };
    let (object, frame) = found.ok_or_else(stale)?;
    node.object = object;
    if frame.is_some() {
        node.frame_id = frame;
    }
    Ok(node)
}

/// Where a pinned node resolved from one frame's isolated world.
enum Pinned {
    /// In this frame: the node's object.
    Here(String),
    /// In a child frame's document, reached through this one (same origin).
    Frame(String),
    /// Not reachable from this frame: another frame's or a replaced document.
    Elsewhere,
}

/// Searches the session's child frames, in tree order, for the one whose
/// isolated world resolves the pinned node; returns its object and frame.
async fn child_frame_object(
    node: &Node,
    params: &Value,
    connected: bool,
) -> Result<Option<(String, Option<String>)>> {
    fn collect(tree: &crate::cdp::FrameTree, frames: &mut Vec<String>) {
        for child in &tree.child_frames {
            frames.push(child.frame.id.clone());
            collect(child, frames);
        }
    }
    let mut frames = Vec::new();
    collect(&node.session.get_frame_tree().await?, &mut frames);
    for frame in frames {
        match pinned_object(node, &frame, params, connected).await {
            Ok(Pinned::Here(object)) => return Ok(Some((object, Some(frame)))),
            Ok(Pinned::Frame(_) | Pinned::Elsewhere) => {}
            // A frame this session cannot reach, such as one that just went
            // away or lives in another process.
            Err(error) if error.cdp_context().is_some() => {
                tracing::debug!("pinned node search skipped frame {frame}: {error}");
            }
            Err(error) => return Err(error),
        }
    }
    Ok(None)
}

/// Resolves a pinned node in one frame's isolated world.
async fn pinned_object(
    node: &Node,
    frame_id: &str,
    params: &Value,
    connected: bool,
) -> Result<Pinned> {
    in_world(node, frame_id, |world| {
        let mut params = params.clone();
        params["objectGroup"] = json!(node.group);
        params["executionContextId"] = json!(world.context);
        let session = node.session.clone();
        let group = node.group.clone();
        async move {
            let resolved = match session.send::<_, Value>("DOM.resolveNode", &params).await {
                Err(error) if stale_context(&error) => return Ok(Attempt::Stale(Some(error))),
                // Chrome gives this both for a node this world cannot reach
                // and for a context that no longer exists. A world created
                // for this attempt, or one whose token still answers, is
                // live: the node is elsewhere.
                Err(error) if classify::node_left_document(&error) => {
                    return if world.fresh || world_answers(&session, world).await {
                        Ok(Attempt::Done(Pinned::Elsewhere))
                    } else {
                        Ok(Attempt::Stale(Some(error)))
                    };
                }
                // A pinned node is never retargeted, so one that is gone is
                // stale now, not "not yet" for a wait.
                Err(error) if classify::is(&error, classify::CdpFailure::NodeGone) => {
                    return Err(stale());
                }
                result => result?,
            };
            // A null object: the node's document is not this world's to
            // reach (a cross-origin frame's, or a replaced one).
            let Some(object) = resolved["object"]["objectId"].as_str() else {
                return Ok(Attempt::Done(Pinned::Elsewhere));
            };
            let object = object.to_owned();
            // The token proves the context is still eoka's world, not a
            // reused id that now belongs to the page.
            let checked = session
                .send::<_, Value>(
                    "Runtime.callFunctionOn",
                    &json!({
                        "objectId":object,"returnByValue":true,
                        "functionDeclaration":"function(token,stale){if(globalThis.__eoka_world!==token){throw new Error(stale)}const view=this.ownerDocument.defaultView;return {connected:this.isConnected===true,own:this.ownerDocument===document,framed:view!==null&&view!==window}}",
                        "arguments":[{"value":world.token},{"value":WORLD_MISMATCH}],
                    }),
                )
                .await;
            let state = match checked {
                // The object was just created in this world, so losing it
                // means the world went too.
                Err(error) if classify::is(&error, classify::CdpFailure::ContextLost) => {
                    return Ok(Attempt::Stale(Some(error)));
                }
                Ok(reply) if world_mismatch(&reply) => return Ok(Attempt::Stale(None)),
                reply => call_value(&reply?)?,
            };
            if state["own"] != true {
                if let Some(frame) = owner_frame(&session, &object, &group).await? {
                    return Ok(Attempt::Done(Pinned::Frame(frame)));
                }
                // Another frame's document whose owner this world cannot
                // see (it sits in a cross-origin document): that frame's own
                // world has to resolve it. A template's or a detached
                // document has no window and stays here.
                if state["framed"] == true {
                    return Ok(Attempt::Done(Pinned::Elsewhere));
                }
            }
            if connected && state["connected"] != true {
                return Err(stale());
            }
            Ok(Attempt::Done(Pinned::Here(object)))
        }
    })
    .await
}

/// The id of the frame whose document holds `object`, when that document
/// belongs to a frame (not a template's or a detached one).
async fn owner_frame(session: &Session, object: &str, group: &str) -> Result<Option<String>> {
    let owner: Value = session
        .send(
            "Runtime.callFunctionOn",
            &json!({
                "objectId":object,"objectGroup":group,"returnByValue":false,
                "functionDeclaration":"function(){return this.ownerDocument.defaultView?.frameElement ?? null}",
            }),
        )
        .await?;
    let Some(owner) = owner["result"]["objectId"].as_str() else {
        return Ok(None);
    };
    let described: Value = session
        .send("DOM.describeNode", &json!({ "objectId": owner }))
        .await?;
    Ok(described["node"]["frameId"].as_str().map(str::to_owned))
}

/// What a non-pinned query returns.
#[derive(Clone, Copy)]
pub(super) enum Pick {
    /// The array of every match, in order.
    All,
    /// The only match; several matches are ambiguous.
    Strict,
    /// The match at a zero-based index.
    Index(usize),
}

/// Runs a non-pinned query in the frame's isolated world in one
/// `Runtime.evaluate`. Returns the node holding the picked element, or the
/// array of every match for [`Pick::All`]; `None` when nothing is picked.
pub(super) async fn query(page: &Page, spec: &LocatorSpec, pick: Pick) -> Result<Option<Node>> {
    let (mut node, frame_id) = start(page, spec).await?;
    let query = serde_json::to_string(&spec.query)?;
    let pick = match pick {
        Pick::All => Value::Null,
        Pick::Strict => json!({ "index": null }),
        Pick::Index(index) => json!({ "index": index }),
    };
    let expression = format!(
        "({})({query},{pick})",
        include_str!("resolve.js")
            .replace(
                "TEXT_CANDIDATES",
                include_str!("../page/text_candidates.js")
            )
            .replace("AMBIGUOUS", &format!("'{AMBIGUOUS}'"))
    );
    let result: Value = in_world(&node, &frame_id, |world| {
        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 session = node.session.clone();
        async move {
            match session.send::<_, Value>("Runtime.evaluate", &params).await {
                Err(error) if stale_context(&error) => Ok(Attempt::Stale(Some(error))),
                Ok(reply) if world_mismatch(&reply) => Ok(Attempt::Stale(None)),
                result => result.map(Attempt::Done),
            }
        }
    })
    .await?;
    if let Some(exception) = result.get("exceptionDetails") {
        if exception["exception"]["description"]
            .as_str()
            .is_some_and(|text| text.contains(AMBIGUOUS))
        {
            return Err(Error::coded(
                ErrorCode::AmbiguousTarget,
                "locator matched multiple elements; select first/nth explicitly",
            ));
        }
        // Any other exception means the query itself is invalid, such as a
        // CSS selector that does not parse.
        return Err(Error::invalid_argument("invalid locator query"));
    }
    // A miss is `null`, which has no object id.
    let Some(object) = result["result"]["objectId"].as_str() else {
        return Ok(None);
    };
    node.object = object.into();
    Ok(Some(node))
}

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

#[derive(Clone, Copy)]
struct World {
    context: i64,
    token: u64,
    /// Created by this lookup rather than taken from the cache.
    fresh: bool,
}

/// Whether `world` still exists and is eoka's: its token answers.
async fn world_answers(session: &Session, world: World) -> bool {
    session
        .send::<_, Value>(
            "Runtime.evaluate",
            &json!({"expression":"globalThis.__eoka_world","contextId":world.context,"returnByValue":true}),
        )
        .await
        .is_ok_and(|reply| reply["result"]["value"].as_u64() == Some(world.token))
}

/// 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,
        fresh: false,
    };
    let mut cache = worlds();
    if cache.len() >= 512 {
        cache.clear();
    }
    cache.insert(key, world);
    Ok(World {
        fresh: true,
        ..world
    })
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    /// A local HTTP server answering every GET with `page(path)` as HTML.
    async fn serve(page: fn(&str) -> String) -> String {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        tokio::spawn(async move {
            while let Ok((mut stream, _)) = listener.accept().await {
                tokio::spawn(async move {
                    let mut request = vec![0u8; 4096];
                    let read = stream.read(&mut request).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(&request[..read]);
                    let path = request.split_whitespace().nth(1).unwrap_or("/");
                    let body = page(path);
                    let _ = stream
                        .write_all(
                            format!(
                                "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                                body.len()
                            )
                            .as_bytes(),
                        )
                        .await;
                });
            }
        });
        base
    }

    async fn launch() -> crate::Browser {
        crate::Browser::launch_with(|config| {
            config.chrome_path = std::env::var("EOKA_TEST_CHROME_PATH").ok();
            config.cdp_timeout = Duration::from_secs(5);
        })
        .await
        .unwrap()
    }

    /// The context id of the page's cached top-frame world, if any.
    fn cached_world(page: &Page) -> Option<i64> {
        let key = (
            page.session().session_id().to_owned(),
            page.target_id().to_owned(),
        );
        worlds().get(&key).map(|world| world.context)
    }

    #[tokio::test]
    #[ignore = "requires Chrome"]
    async fn chrome_an_element_from_a_previous_document_is_stale_at_once() {
        let base = serve(|path| format!("<p id=p>{}</p>", &path[1..])).await;
        let browser = launch().await;
        let page = browser.new_page(&format!("{base}/old")).await.unwrap();
        let old = page.find("p").await.unwrap();
        assert_eq!(old.text().await.unwrap(), "old");
        let dead = cached_world(&page).expect("the first find caches a world");
        page.goto(&format!("{base}/new")).await.unwrap();

        // A live node of the new document, pinned before any locator ran
        // there: the cached world died with the old document, so the read
        // replaces it once and succeeds.
        let new = Element {
            page: page.clone(),
            backend_node_id: backend_id_in_frames(&page, "p").await,
            document: page.document(),
        };
        assert_eq!(new.text().await.unwrap(), "new");
        let world = cached_world(&page).expect("the replacement world is cached");
        assert_ne!(world, dead);

        // The old node is stale at once.
        let start = std::time::Instant::now();
        let error = old.text().await.unwrap_err();
        assert_eq!(error.code(), ErrorCode::TargetStale, "{error}");
        assert_eq!(cached_world(&page), Some(world));
        // Later reads keep that world: no new world per read, no waiting.
        for _ in 0..3 {
            assert_eq!(old.text().await.unwrap_err().code(), ErrorCode::TargetStale);
            assert_eq!(
                old.is_visible().await.unwrap_err().code(),
                ErrorCode::TargetStale
            );
        }
        assert_eq!(cached_world(&page), Some(world));
        assert!(
            start.elapsed() < Duration::from_secs(2),
            "{:?}",
            start.elapsed()
        );
        // A wait on the pinned node fails at once instead of polling.
        let pinned = LocatorSpec {
            query: LocatorQuery::BackendNode {
                id: old.backend_node_id,
            },
            frame_id: None,
            index: None,
        };
        let start = std::time::Instant::now();
        let error = page
            .wait_for_expectation(
                &crate::Expectation::Visible { target: pinned },
                Duration::from_secs(10),
            )
            .await
            .unwrap_err();
        assert_eq!(error.code(), ErrorCode::TargetStale, "{error}");
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "{:?}",
            start.elapsed()
        );
        // The new document resolves in the same world.
        assert_eq!(page.find("p").await.unwrap().text().await.unwrap(), "new");
        assert_eq!(cached_world(&page), Some(world));
        browser.close().await.unwrap();
    }

    /// The backend node id of the element with `id` anywhere in the page,
    /// child frames included, once it exists.
    async fn backend_id_in_frames(page: &Page, id: &str) -> i64 {
        fn find(node: &Value, id: &str) -> Option<i64> {
            let attributes = node["attributes"].as_array();
            if attributes.is_some_and(|a| a.chunks(2).any(|pair| pair[0] == "id" && pair[1] == id))
            {
                return node["backendNodeId"].as_i64();
            }
            let children = node["children"].as_array().into_iter().flatten();
            children
                .chain(node.get("contentDocument"))
                .find_map(|child| find(child, id))
        }
        for _ in 0..100 {
            let document: Value = page
                .session()
                .send("DOM.getDocument", &json!({"depth":-1,"pierce":true}))
                .await
                .unwrap();
            if let Some(found) = find(&document["root"], id) {
                return found;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        panic!("no element #{id} in any frame");
    }

    /// An Element pinned by backend id with no frame, as eoka-tools builds
    /// from accessibility refs, works inside a child frame: reads run in that
    /// frame's isolated world and a click lands on the element, not at its
    /// frame-local coordinates.
    async fn pinned_frame_element_works(page: &Page) {
        let button = Element {
            page: page.clone(),
            backend_node_id: backend_id_in_frames(page, "go").await,
            document: page.document(),
        };
        let field = Element {
            page: page.clone(),
            backend_node_id: backend_id_in_frames(page, "field").await,
            document: page.document(),
        };
        assert!(button.is_visible().await.unwrap());
        assert_eq!(button.text().await.unwrap(), "go");
        assert_eq!(
            button.get_attribute("id").await.unwrap().as_deref(),
            Some("go")
        );
        assert_eq!(field.value().await.unwrap(), "inner");
        let receipt = button
            .click()
            .expecting(crate::Expectation::Text {
                target: LocatorSpec {
                    query: LocatorQuery::BackendNode {
                        id: button.backend_node_id,
                    },
                    frame_id: None,
                    index: None,
                },
                value: "clicked".into(),
                contains: false,
            })
            .timeout(Duration::from_secs(5))
            .await
            .unwrap();
        assert_eq!(receipt.outcome, crate::ActionOutcome::VerifiedComplete);
        assert_eq!(button.text().await.unwrap(), "clicked");
        // The top frame's own clicks were not hit.
        assert_eq!(page.eval::<u32>("window.topClicks").await.unwrap(), 0);
    }

    fn framed_page(inner: &str) -> String {
        format!(
            "<body onclick='window.topClicks++'><script>window.topClicks=0</script>\
             <div style='margin:200px 0 0 300px'><iframe src='{inner}' style='width:300px;height:150px'></iframe></div></body>"
        )
    }

    /// Pages for nested-frame layouts; the query carries the next URL, so
    /// one router serves every origin.
    fn frames_router(path: &str) -> String {
        if let Some(next) = path.strip_prefix("/top?") {
            framed_page(next)
        } else if let Some(next) = path.strip_prefix("/mid?") {
            format!("<iframe src='{next}' style='margin:10px;width:260px;height:120px'></iframe>")
        } else if let Some(other) = path.strip_prefix("/two?") {
            format!(
                "<body onclick='window.topClicks++'><script>window.topClicks=0</script>\
                 <iframe src='{other}/blank'></iframe>\
                 <div style='margin:100px 0 0 300px'><iframe src='{other}/inner' style='width:300px;height:150px'></iframe></div></body>"
            )
        } else if path == "/blank" {
            "<p>blank</p>".into()
        } else {
            inner_page()
        }
    }

    #[tokio::test]
    #[ignore = "requires Chrome"]
    async fn chrome_a_pinned_node_resolves_in_its_own_frame_among_nested_and_sibling_frames() {
        let a = serve(frames_router).await;
        let b = serve(frames_router).await;
        let browser = launch().await;
        // Top a, child b, grandchild a: the top world can wrap the node but
        // cannot see its frame owner, which sits in b's document.
        let page = browser
            .new_page(&format!("{a}/top?{b}/mid?{a}/inner"))
            .await
            .unwrap();
        pinned_frame_element_works(&page).await;
        // Two b siblings under a: the first sibling's world can wrap the
        // second's node, but the node belongs to the second.
        page.goto(&format!("{a}/two?{b}")).await.unwrap();
        pinned_frame_element_works(&page).await;
        browser.close().await.unwrap();
    }

    fn inner_page() -> String {
        "<button id=go style='margin:40px' onclick=\"this.textContent='clicked'\">go</button><input id=field value=inner>".into()
    }

    #[tokio::test]
    #[ignore = "requires Chrome"]
    async fn chrome_a_pinned_node_in_a_same_origin_frame_resolves_in_its_frame() {
        let base = serve(|path| {
            if path == "/inner" {
                inner_page()
            } else {
                framed_page("/inner")
            }
        })
        .await;
        let browser = launch().await;
        let page = browser.new_page(&format!("{base}/")).await.unwrap();
        pinned_frame_element_works(&page).await;
        browser.close().await.unwrap();
    }

    #[tokio::test]
    #[ignore = "requires Chrome"]
    async fn chrome_a_pinned_node_in_a_cross_origin_frame_resolves_in_its_frame() {
        // Another port on the same host is cross-origin but same-site, so
        // the frame stays in the page's process and session.
        let inner = serve(|_| inner_page()).await;
        let base = serve(|path| framed_page(path.strip_prefix("/?").unwrap_or_default())).await;
        let browser = launch().await;
        let page = browser
            .new_page(&format!("{base}/?{inner}/"))
            .await
            .unwrap();
        pinned_frame_element_works(&page).await;
        browser.close().await.unwrap();
    }

    #[tokio::test]
    #[ignore = "requires Chrome"]
    async fn chrome_dropping_a_match_list_releases_it_and_its_elements() {
        let browser = crate::Browser::launch_with(|config| {
            config.chrome_path = std::env::var("EOKA_TEST_CHROME_PATH").ok();
            config.cdp_timeout = Duration::from_secs(5);
        })
        .await
        .unwrap();
        let page = browser
            .new_page("data:text/html,<p>a</p><p>b</p>")
            .await
            .unwrap();
        let node = query(&page, &LocatorSpec::css("p"), Pick::All)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            all_elements(&page, &LocatorSpec::css("p"))
                .await
                .unwrap()
                .len(),
            2
        );
        let session = node.session.clone();
        let array = node.object.clone();
        // An element object derived from the array, as all_elements gets them.
        let properties: Value = session
            .send(
                "Runtime.getProperties",
                &json!({"objectId":array,"ownProperties":true}),
            )
            .await
            .unwrap();
        let element = properties["result"]
            .as_array()
            .unwrap()
            .iter()
            .find(|property| property["name"] == "0")
            .and_then(|property| property["value"]["objectId"].as_str())
            .unwrap()
            .to_owned();
        let call = |object: String| {
            let session = session.clone();
            async move {
                session
                    .send::<_, Value>(
                        "Runtime.callFunctionOn",
                        &json!({"objectId":object,"functionDeclaration":"function(){return 1}","returnByValue":true}),
                    )
                    .await
            }
        };
        call(element.clone()).await.unwrap();
        drop(node);
        tokio::time::timeout(Duration::from_secs(2), async {
            while call(element.clone()).await.is_ok() || call(array.clone()).await.is_ok() {
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await
        .expect("dropping the node must release the array and its element objects");
        browser.close().await.unwrap();
    }
}