stygian-browser 0.9.2

Anti-detection browser automation library for Rust with CDP stealth features
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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
//!
//! ## Resource blocking
//!
//! ## Wait strategies
//!
//! [`PageHandle`] exposes three wait strategies via [`WaitUntil`]:
//! - `DomContentLoaded` — fires when the HTML is parsed
//!
//! # Example
//!
//! ```no_run
//! use stygian_browser::{BrowserPool, BrowserConfig};
//! use stygian_browser::page::{ResourceFilter, WaitUntil};
//! use std::time::Duration;
//!
//! # async fn run() -> stygian_browser::error::Result<()> {
//! let pool = BrowserPool::new(BrowserConfig::default()).await?;
//! let handle = pool.acquire().await?;
//!
//! let mut page = handle.browser().expect("valid browser").new_page().await?;
//! page.set_resource_filter(ResourceFilter::block_media()).await?;
//! page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
//! let title = page.title().await?;
//! println!("title: {title}");
//! handle.release().await;
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;
use std::sync::{
    Arc,
    atomic::{AtomicU16, Ordering},
};
use std::time::Duration;

use chromiumoxide::Page;
use tokio::time::timeout;
use tracing::{debug, warn};

use crate::error::{BrowserError, Result};

// ─── ResourceType ─────────────────────────────────────────────────────────────

/// CDP resource types that can be intercepted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceType {
    /// `<img>`, `<picture>`, background images
    Image,
    /// Web fonts loaded via CSS `@font-face`
    Font,
    /// External CSS stylesheets
    Stylesheet,
    /// Media files (audio/video)
    Media,
}

impl ResourceType {
    pub const fn as_cdp_str(&self) -> &'static str {
        match self {
            Self::Image => "Image",
            Self::Font => "Font",
            Self::Stylesheet => "Stylesheet",
            Self::Media => "Media",
        }
    }
}

// ─── ResourceFilter ───────────────────────────────────────────────────────────

///
/// # Example
///
/// ```
/// use stygian_browser::page::ResourceFilter;
/// let filter = ResourceFilter::block_media();
/// assert!(filter.should_block("Image"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct ResourceFilter {
    blocked: Vec<ResourceType>,
}

impl ResourceFilter {
    /// Block all media resources (images, fonts, CSS, audio/video).
    pub fn block_media() -> Self {
        Self {
            blocked: vec![
                ResourceType::Image,
                ResourceType::Font,
                ResourceType::Stylesheet,
                ResourceType::Media,
            ],
        }
    }

    pub fn block_images_and_fonts() -> Self {
        Self {
            blocked: vec![ResourceType::Image, ResourceType::Font],
        }
    }

    #[must_use]
    pub fn block(mut self, resource: ResourceType) -> Self {
        if !self.blocked.contains(&resource) {
            self.blocked.push(resource);
        }
        self
    }

    pub fn should_block(&self, cdp_type: &str) -> bool {
        self.blocked
            .iter()
            .any(|r| r.as_cdp_str().eq_ignore_ascii_case(cdp_type))
    }

    pub const fn is_empty(&self) -> bool {
        self.blocked.is_empty()
    }
}

// ─── WaitUntil ────────────────────────────────────────────────────────────────

///
/// # Example
///
/// ```
/// use stygian_browser::page::WaitUntil;
/// ```
/// Specifies what condition to wait for after a page navigation.
#[derive(Debug, Clone)]
pub enum WaitUntil {
    /// Fires when the initial HTML is fully parsed, without waiting for
    /// subresources such as images and stylesheets to finish loading.
    DomContentLoaded,
    NetworkIdle,
    Selector(String),
}

// ─── NodeHandle ───────────────────────────────────────────────────────────────

///
/// more CDP `Runtime.callFunctionOn` calls against the held V8 remote object
/// reference — no HTML serialisation occurs.
///
/// A handle becomes **stale** after page navigation or if the underlying DOM
/// node is removed.  Stale calls return [`BrowserError::StaleNode`] so callers
/// can distinguish them from other CDP failures.
///
/// # Example
///
/// ```no_run
/// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
/// use std::time::Duration;
///
/// # async fn run() -> stygian_browser::error::Result<()> {
/// let pool = BrowserPool::new(BrowserConfig::default()).await?;
/// let handle = pool.acquire().await?;
/// let mut page = handle.browser().expect("valid browser").new_page().await?;
/// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
/// # let nodes = page.query_selector_all("a").await?;
/// # for node in &nodes {
///     let href = node.attr("href").await?;
///     let text = node.text_content().await?;
///     println!("{text}: {href:?}");
/// # }
/// # Ok(())
/// # }
/// ```
pub struct NodeHandle {
    element: chromiumoxide::element::Element,
    /// Shared via `Arc<str>` so all handles from a single query reuse the
    /// same allocation rather than cloning a `String` per node.
    selector: Arc<str>,
    cdp_timeout: Duration,
    /// during DOM traversal (parent / sibling navigation).
    page: chromiumoxide::Page,
}

impl NodeHandle {
    /// Return a single attribute value, or `None` if the attribute is absent.
    ///
    /// Issues one `Runtime.callFunctionOn` CDP call (`el.getAttribute(name)`).
    ///
    /// # Errors
    ///
    /// invalidated, or [`BrowserError::Timeout`] / [`BrowserError::CdpError`]
    /// on transport-level failures.
    pub async fn attr(&self, name: &str) -> Result<Option<String>> {
        timeout(self.cdp_timeout, self.element.attribute(name))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::attr".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "attr"))
    }

    /// Return all attributes as a `HashMap<name, value>` in a **single**
    /// CDP round-trip.
    ///
    /// Uses `DOM.getAttributes` (via the chromiumoxide `attributes()` API)
    /// which returns a flat `[name, value, name, value, …]` list from the node
    /// description — no per-attribute calls are needed.
    ///
    /// # Errors
    ///
    /// invalidated.
    pub async fn attr_map(&self) -> Result<HashMap<String, String>> {
        let flat = timeout(self.cdp_timeout, self.element.attributes())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::attr_map".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "attr_map"))?;

        let mut map = HashMap::with_capacity(flat.len() / 2);
        for pair in flat.chunks_exact(2) {
            if let [name, value] = pair {
                map.insert(name.clone(), value.clone());
            }
        }
        Ok(map)
    }

    /// Return the element's `textContent` (all text inside, no markup).
    ///
    /// Reads the DOM `textContent` property via a single JS eval — this is the
    /// raw text concatenation of all descendant text nodes, independent of
    /// layout or visibility (unlike `innerText`).
    ///
    ///
    /// # Errors
    ///
    /// invalidated.
    pub async fn text_content(&self) -> Result<String> {
        let returns = timeout(
            self.cdp_timeout,
            self.element
                .call_js_fn(r"function() { return this.textContent ?? ''; }", true),
        )
        .await
        .map_err(|_| BrowserError::Timeout {
            operation: "NodeHandle::text_content".to_string(),
            duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
        })?
        .map_err(|e| self.cdp_err_or_stale(&e, "text_content"))?;

        Ok(returns
            .result
            .value
            .as_ref()
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string())
    }

    /// Return the element's `innerHTML`.
    ///
    ///
    /// # Errors
    ///
    /// invalidated.
    pub async fn inner_html(&self) -> Result<String> {
        timeout(self.cdp_timeout, self.element.inner_html())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::inner_html".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "inner_html"))
            .map(Option::unwrap_or_default)
    }

    /// Return the element's `outerHTML`.
    ///
    ///
    /// # Errors
    ///
    /// invalidated.
    pub async fn outer_html(&self) -> Result<String> {
        timeout(self.cdp_timeout, self.element.outer_html())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::outer_html".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "outer_html"))
            .map(Option::unwrap_or_default)
    }

    ///
    /// Executes a single `Runtime.callFunctionOn` JavaScript function that
    /// walks `parentElement` and collects tag names — no repeated CDP calls.
    ///
    /// ```text
    /// ["p", "article", "body", "html"]
    /// ```
    ///
    /// # Errors
    ///
    /// invalidated, or [`BrowserError::ScriptExecutionFailed`] when CDP
    pub async fn ancestors(&self) -> Result<Vec<String>> {
        let returns = timeout(
            self.cdp_timeout,
            self.element.call_js_fn(
                r"function() {
                    const a = [];
                    let n = this.parentElement;
                    while (n) { a.push(n.tagName.toLowerCase()); n = n.parentElement; }
                    return a;
                }",
                true,
            ),
        )
        .await
        .map_err(|_| BrowserError::Timeout {
            operation: "NodeHandle::ancestors".to_string(),
            duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
        })?
        .map_err(|e| self.cdp_err_or_stale(&e, "ancestors"))?;

        // With returnByValue=true and an array return, CDP delivers the value
        // as a JSON array directly — no JSON.stringify/re-parse needed.
        // A missing or wrong-type value indicates an unexpected CDP failure.
        let arr = returns
            .result
            .value
            .as_ref()
            .and_then(|v| v.as_array())
            .ok_or_else(|| BrowserError::ScriptExecutionFailed {
                script: "NodeHandle::ancestors".to_string(),
                reason: "CDP returned no value or a non-array value for ancestors()".to_string(),
            })?;

        arr.iter()
            .map(|v| {
                v.as_str().map(ToString::to_string).ok_or_else(|| {
                    BrowserError::ScriptExecutionFailed {
                        script: "NodeHandle::ancestors".to_string(),
                        reason: format!("ancestor entry is not a string: {v}"),
                    }
                })
            })
            .collect()
    }

    ///
    ///
    ///
    /// # Errors
    ///
    /// invalidated, or [`BrowserError::CdpError`] on transport failure.
    pub async fn children_matching(&self, selector: &str) -> Result<Vec<Self>> {
        let elements = timeout(self.cdp_timeout, self.element.find_elements(selector))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::children_matching".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "children_matching"))?;

        let selector_arc: Arc<str> = Arc::from(selector);
        Ok(elements
            .into_iter()
            .map(|el| Self {
                element: el,
                selector: selector_arc.clone(),
                cdp_timeout: self.cdp_timeout,
                page: self.page.clone(),
            })
            .collect())
    }

    /// Return the immediate parent element, or `None` if this element has no
    /// parent (i.e. it is the document root).
    ///
    /// Issues a single `Runtime.callFunctionOn` CDP call that temporarily tags
    /// the parent element with a unique attribute, then resolves it via a
    /// CSS attribute selector.
    ///
    /// # Errors
    ///
    /// Returns an error if the CDP call fails or the page handle is invalidated.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// # let nodes = page.query_selector_all("a").await?;
    /// if let Some(parent) = nodes[0].parent().await? {
    ///     let html = parent.outer_html().await?;
    ///     println!("parent: {}", &html[..html.len().min(80)]);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn parent(&self) -> Result<Option<Self>> {
        let attr = format!(
            "data-stygian-t-{}",
            ulid::Ulid::new().to_string().to_lowercase()
        );
        let js = format!(
            "function() {{ \
                var t = this.parentElement; \
                if (!t) {{ return false; }} \
                t.setAttribute('{attr}', '1'); \
                return true; \
            }}"
        );
        self.call_traversal(&js, &attr, "parent").await
    }

    /// Return the next element sibling, or `None` if this element is the last
    /// child of its parent.
    ///
    /// Uses `nextElementSibling` (skips text/comment nodes).
    ///
    /// # Errors
    ///
    /// invalidated.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// # let nodes = page.query_selector_all("a").await?;
    /// if let Some(next) = nodes[0].next_sibling().await? {
    ///     println!("next sibling: {}", next.text_content().await?);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn next_sibling(&self) -> Result<Option<Self>> {
        let attr = format!(
            "data-stygian-t-{}",
            ulid::Ulid::new().to_string().to_lowercase()
        );
        let js = format!(
            "function() {{ \
                var t = this.nextElementSibling; \
                if (!t) {{ return false; }} \
                t.setAttribute('{attr}', '1'); \
                return true; \
            }}"
        );
        self.call_traversal(&js, &attr, "next").await
    }

    /// Return the previous element sibling, or `None` if this element is the
    /// first child of its parent.
    ///
    /// Uses `previousElementSibling` (skips text/comment nodes).
    ///
    /// # Errors
    ///
    /// invalidated.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// # let nodes = page.query_selector_all("a").await?;
    /// if let Some(prev) = nodes[1].previous_sibling().await? {
    ///     println!("prev sibling: {}", prev.text_content().await?);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn previous_sibling(&self) -> Result<Option<Self>> {
        let attr = format!(
            "data-stygian-t-{}",
            ulid::Ulid::new().to_string().to_lowercase()
        );
        let js = format!(
            "function() {{ \
                var t = this.previousElementSibling; \
                if (!t) {{ return false; }} \
                t.setAttribute('{attr}', '1'); \
                return true; \
            }}"
        );
        self.call_traversal(&js, &attr, "prev").await
    }

    /// Shared traversal implementation used by [`parent`], [`next_sibling`],
    /// and [`previous_sibling`].
    ///
    /// The caller provides a JS function that:
    /// 1. Computes the traversal target (for example, the parent, next
    ///    sibling, or previous sibling) and stores it in a local variable.
    /// 2. If the target is non-null, sets a unique attribute (`attr_name`)
    ///    on it and returns `true`.
    /// 3. Returns `false` when the target is null (no such neighbour).
    ///
    /// This helper then resolves the tagged element from the document root,
    /// removes the temporary attribute, and wraps the result in a
    /// `NodeHandle`.
    ///
    /// [`parent`]: Self::parent
    /// [`next_sibling`]: Self::next_sibling
    /// [`previous_sibling`]: Self::previous_sibling
    async fn call_traversal(
        &self,
        js_fn: &str,
        attr_name: &str,
        selector_suffix: &str,
    ) -> Result<Option<Self>> {
        // Step 1: Run the JS that tags the target element and reports null/non-null.
        let op_tag = format!("NodeHandle::{selector_suffix}::tag");
        let returns = timeout(self.cdp_timeout, self.element.call_js_fn(js_fn, false))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: op_tag.clone(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, selector_suffix))?;

        // JS returns false → no such neighbour.
        let has_target = returns
            .result
            .value
            .as_ref()
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        if !has_target {
            return Ok(None);
        }

        let css = format!("[{attr_name}]");
        let op_resolve = format!("NodeHandle::{selector_suffix}::resolve");
        let element = timeout(self.cdp_timeout, self.page.find_element(css))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: op_resolve.clone(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: op_resolve,
                message: e.to_string(),
            })?;

        // is non-fatal — it leaves a harmless stale attribute in the DOM).
        let cleanup = format!("function() {{ this.removeAttribute('{attr_name}'); }}");
        let _ = element.call_js_fn(cleanup, false).await;

        let new_selector: Arc<str> =
            Arc::from(format!("{}::{selector_suffix}", self.selector).as_str());
        Ok(Some(Self {
            element,
            selector: new_selector,
            cdp_timeout: self.cdp_timeout,
            page: self.page.clone(),
        }))
    }

    /// (when the remote object reference has been invalidated) or
    fn cdp_err_or_stale(
        &self,
        err: &chromiumoxide::error::CdpError,
        operation: &str,
    ) -> BrowserError {
        let msg = err.to_string();
        if msg.contains("Cannot find object with id")
            || msg.contains("context with specified id")
            || msg.contains("Cannot find context")
        {
            BrowserError::StaleNode {
                selector: self.selector.to_string(),
            }
        } else {
            BrowserError::CdpError {
                operation: operation.to_string(),
                message: msg,
            }
        }
    }
}

// ─── PageHandle ───────────────────────────────────────────────────────────────

///
///
/// # Example
///
/// ```no_run
/// use stygian_browser::{BrowserPool, BrowserConfig};
/// use stygian_browser::page::WaitUntil;
/// use std::time::Duration;
///
/// # async fn run() -> stygian_browser::error::Result<()> {
/// let pool = BrowserPool::new(BrowserConfig::default()).await?;
/// let handle = pool.acquire().await?;
/// let mut page = handle.browser().expect("valid browser").new_page().await?;
/// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
/// let html = page.content().await?;
/// drop(page); // closes the tab
/// handle.release().await;
/// # Ok(())
/// # }
/// ```
pub struct PageHandle {
    page: Page,
    cdp_timeout: Duration,
    /// HTTP status code of the most recent main-frame navigation, or `0` if not
    last_status_code: Arc<AtomicU16>,
    /// Background task processing `Fetch.requestPaused` events. Aborted and
    /// replaced each time `set_resource_filter` is called.
    resource_filter_task: Option<tokio::task::JoinHandle<()>>,
}

impl PageHandle {
    /// Wrap a raw chromiumoxide [`Page`] in a handle.
    pub(crate) fn new(page: Page, cdp_timeout: Duration) -> Self {
        Self {
            page,
            cdp_timeout,
            last_status_code: Arc::new(AtomicU16::new(0)),
            resource_filter_task: None,
        }
    }

    ///
    /// # Errors
    ///
    /// the CDP call fails.
    pub async fn navigate(
        &mut self,
        url: &str,
        condition: WaitUntil,
        nav_timeout: Duration,
    ) -> Result<()> {
        self.setup_status_capture().await;
        timeout(
            nav_timeout,
            self.navigate_inner(url, condition, nav_timeout),
        )
        .await
        .map_err(|_| BrowserError::NavigationFailed {
            url: url.to_string(),
            reason: format!("navigation timed out after {nav_timeout:?}"),
        })?
    }

    /// Reset the last status code and wire up the `Network.responseReceived`
    /// so that a missing network domain never blocks navigation.
    async fn setup_status_capture(&self) {
        use chromiumoxide::cdp::browser_protocol::network::{
            EventResponseReceived, ResourceType as NetworkResourceType,
        };
        use futures::StreamExt;

        // Reset so a stale code is not returned if the new navigation fails
        self.last_status_code.store(0, Ordering::Release);

        let page_for_listener = self.page.clone();
        let status_capture = Arc::clone(&self.last_status_code);
        match page_for_listener
            .event_listener::<EventResponseReceived>()
            .await
        {
            Ok(mut stream) => {
                tokio::spawn(async move {
                    while let Some(event) = stream.next().await {
                        if event.r#type == NetworkResourceType::Document {
                            let code = u16::try_from(event.response.status).unwrap_or(0);
                            if code > 0 {
                                status_capture.store(code, Ordering::Release);
                            }
                            break;
                        }
                    }
                });
            }
            Err(e) => warn!("status-code capture unavailable: {e}"),
        }
    }

    /// described in issue #7.
    async fn navigate_inner(
        &self,
        url: &str,
        condition: WaitUntil,
        nav_timeout: Duration,
    ) -> Result<()> {
        use chromiumoxide::cdp::browser_protocol::page::{
            EventDomContentEventFired, EventLoadEventFired,
        };
        use futures::StreamExt;

        let url_owned = url.to_string();

        let mut dom_events = match &condition {
            WaitUntil::DomContentLoaded => Some(
                self.page
                    .event_listener::<EventDomContentEventFired>()
                    .await
                    .map_err(|e| BrowserError::NavigationFailed {
                        url: url_owned.clone(),
                        reason: e.to_string(),
                    })?,
            ),
            _ => None,
        };

        let mut load_events = match &condition {
            WaitUntil::NetworkIdle => Some(
                self.page
                    .event_listener::<EventLoadEventFired>()
                    .await
                    .map_err(|e| BrowserError::NavigationFailed {
                        url: url_owned.clone(),
                        reason: e.to_string(),
                    })?,
            ),
            _ => None,
        };

        let inflight = if matches!(condition, WaitUntil::NetworkIdle) {
            Some(self.subscribe_inflight_counter().await)
        } else {
            None
        };

        self.page
            .goto(url)
            .await
            .map_err(|e| BrowserError::NavigationFailed {
                url: url_owned.clone(),
                reason: e.to_string(),
            })?;

        match &condition {
            WaitUntil::DomContentLoaded => {
                if let Some(ref mut events) = dom_events {
                    let _ = events.next().await;
                }
            }
            WaitUntil::NetworkIdle => {
                if let Some(ref mut events) = load_events {
                    let _ = events.next().await;
                }
                if let Some(ref counter) = inflight {
                    Self::wait_network_idle(counter).await;
                }
            }
            WaitUntil::Selector(css) => {
                self.wait_for_selector(css, nav_timeout).await?;
            }
        }
        Ok(())
    }

    /// Spawn three detached tasks that maintain a signed in-flight request
    /// counter via `Network.requestWillBeSent` (+1) and
    /// `Network.loadingFinished`/`Network.loadingFailed` (−1 each).
    async fn subscribe_inflight_counter(&self) -> Arc<std::sync::atomic::AtomicI32> {
        use std::sync::atomic::AtomicI32;

        use chromiumoxide::cdp::browser_protocol::network::{
            EventLoadingFailed, EventLoadingFinished, EventRequestWillBeSent,
        };
        use futures::StreamExt;

        let counter: Arc<AtomicI32> = Arc::new(AtomicI32::new(0));
        let pairs: [(Arc<AtomicI32>, i32); 3] = [
            (Arc::clone(&counter), 1),
            (Arc::clone(&counter), -1),
            (Arc::clone(&counter), -1),
        ];
        let [p1, p2, p3] = [self.page.clone(), self.page.clone(), self.page.clone()];

        macro_rules! spawn_tracker {
            ($page:expr, $event:ty, $c:expr, $delta:expr) => {
                match $page.event_listener::<$event>().await {
                    Ok(mut s) => {
                        let c = $c;
                        let d = $delta;
                        tokio::spawn(async move {
                            while s.next().await.is_some() {
                                c.fetch_add(d, Ordering::Relaxed);
                            }
                        });
                    }
                    Err(e) => warn!("network-idle tracker unavailable: {e}"),
                }
            };
        }

        let [(c1, d1), (c2, d2), (c3, d3)] = pairs;
        spawn_tracker!(p1, EventRequestWillBeSent, c1, d1);
        spawn_tracker!(p2, EventLoadingFinished, c2, d2);
        spawn_tracker!(p3, EventLoadingFailed, c3, d3);

        counter
    }

    async fn wait_network_idle(counter: &Arc<std::sync::atomic::AtomicI32>) {
        const IDLE_THRESHOLD: i32 = 2;
        const SETTLE: Duration = Duration::from_millis(500);
        loop {
            if counter.load(Ordering::Relaxed) <= IDLE_THRESHOLD {
                tokio::time::sleep(SETTLE).await;
                if counter.load(Ordering::Relaxed) <= IDLE_THRESHOLD {
                    break;
                }
            } else {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        }
    }

    ///
    /// # Errors
    ///
    /// within the given timeout.
    pub async fn wait_for_selector(&self, selector: &str, wait_timeout: Duration) -> Result<()> {
        let selector_owned = selector.to_string();
        let poll = async {
            loop {
                if self.page.find_element(selector_owned.clone()).await.is_ok() {
                    return Ok(());
                }
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
        };

        timeout(wait_timeout, poll)
            .await
            .map_err(|_| BrowserError::NavigationFailed {
                url: String::new(),
                reason: format!("selector '{selector_owned}' not found within {wait_timeout:?}"),
            })?
    }

    ///
    /// Enables `Fetch` interception and spawns a background task that continues
    /// allowed requests and fails blocked ones with `BlockedByClient`. Any
    /// previously set filter task is cancelled first.
    ///
    /// # Errors
    ///
    pub async fn set_resource_filter(&mut self, filter: ResourceFilter) -> Result<()> {
        use chromiumoxide::cdp::browser_protocol::fetch::{
            ContinueRequestParams, EnableParams, EventRequestPaused, FailRequestParams,
            RequestPattern,
        };
        use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
        use futures::StreamExt as _;

        if filter.is_empty() {
            return Ok(());
        }

        // Cancel any previously running filter task.
        if let Some(task) = self.resource_filter_task.take() {
            task.abort();
        }

        let pattern = RequestPattern::builder().url_pattern("*").build();
        let params = EnableParams::builder()
            .patterns(vec![pattern])
            .handle_auth_requests(false)
            .build();

        timeout(self.cdp_timeout, self.page.execute::<EnableParams>(params))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "Fetch.enable".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: "Fetch.enable".to_string(),
                message: e.to_string(),
            })?;

        // is never blocked. Without this handler Chrome holds every intercepted
        // request indefinitely and the page hangs.
        let mut events = self
            .page
            .event_listener::<EventRequestPaused>()
            .await
            .map_err(|e| BrowserError::CdpError {
                operation: "Fetch.requestPaused subscribe".to_string(),
                message: e.to_string(),
            })?;

        let page = self.page.clone();
        debug!("Resource filter active: {:?}", filter);
        let task = tokio::spawn(async move {
            while let Some(event) = events.next().await {
                let request_id = event.request_id.clone();
                if filter.should_block(event.resource_type.as_ref()) {
                    let params = FailRequestParams::new(request_id, ErrorReason::BlockedByClient);
                    let _ = page.execute(params).await;
                } else {
                    let _ = page.execute(ContinueRequestParams::new(request_id)).await;
                }
            }
        });

        self.resource_filter_task = Some(task);
        Ok(())
    }

    /// Return the current page URL (post-navigation, post-redirect).
    ///
    /// internally by [`save_cookies`](Self::save_cookies); no extra network
    /// request is made.  Returns an empty string if the URL is not yet set
    ///
    /// # Errors
    ///
    /// [`BrowserError::Timeout`] if it exceeds `cdp_timeout`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig};
    /// use stygian_browser::page::WaitUntil;
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// let url = page.url().await?;
    /// println!("Final URL after redirects: {url}");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn url(&self) -> Result<String> {
        timeout(self.cdp_timeout, self.page.url())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "page.url".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: "page.url".to_string(),
                message: e.to_string(),
            })
            .map(Option::unwrap_or_default)
    }

    /// Return the HTTP status code of the most recent main-frame navigation.
    ///
    /// The status is captured from the `Network.responseReceived` CDP event
    /// wired up inside [`navigate`](Self::navigate), so it reflects the
    /// *final* response after any server-side redirects.
    ///
    /// navigations, when [`navigate`](Self::navigate) has not yet been called,
    /// or if the network event subscription failed.
    ///
    /// # Errors
    ///
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig};
    /// use stygian_browser::page::WaitUntil;
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// if let Some(code) = page.status_code()? {
    ///     println!("HTTP {code}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn status_code(&self) -> Result<Option<u16>> {
        let code = self.last_status_code.load(Ordering::Acquire);
        Ok(if code == 0 { None } else { Some(code) })
    }

    /// Return the page's `<title>` text.
    ///
    /// # Errors
    ///
    pub async fn title(&self) -> Result<String> {
        timeout(self.cdp_timeout, self.page.get_title())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "get_title".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::ScriptExecutionFailed {
                script: "document.title".to_string(),
                reason: e.to_string(),
            })
            .map(Option::unwrap_or_default)
    }

    /// Return the page's full outer HTML.
    ///
    /// # Errors
    ///
    pub async fn content(&self) -> Result<String> {
        timeout(self.cdp_timeout, self.page.content())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "page.content".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::ScriptExecutionFailed {
                script: "document.documentElement.outerHTML".to_string(),
                reason: e.to_string(),
            })
    }

    /// lightweight [`NodeHandle`]s backed by CDP `RemoteObjectId`s.
    ///
    /// No HTML serialisation occurs — the browser's in-memory DOM is queried
    /// directly over the CDP connection, eliminating the `page.content()` +
    /// `scraper::Html::parse_document` round-trip.
    ///
    ///
    /// # Errors
    ///
    /// [`BrowserError::Timeout`] if it exceeds `cdp_timeout`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    /// # let nodes = page.query_selector_all("div[data-ux]").await?;
    /// # for node in &nodes {
    ///     let ux_type = node.attr("data-ux").await?;
    ///     let text    = node.text_content().await?;
    ///     println!("{ux_type:?}: {text}");
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn query_selector_all(&self, selector: &str) -> Result<Vec<NodeHandle>> {
        let elements = timeout(self.cdp_timeout, self.page.find_elements(selector))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "PageHandle::query_selector_all".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: "PageHandle::query_selector_all".to_string(),
                message: e.to_string(),
            })?;

        let selector_arc: Arc<str> = Arc::from(selector);
        Ok(elements
            .into_iter()
            .map(|el| NodeHandle {
                element: el,
                selector: selector_arc.clone(),
                cdp_timeout: self.cdp_timeout,
                page: self.page.clone(),
            })
            .collect())
    }

    /// Evaluate arbitrary JavaScript and return the result as `T`.
    ///
    /// # Errors
    ///
    /// deserialization error.
    pub async fn eval<T: serde::de::DeserializeOwned>(&self, script: &str) -> Result<T> {
        let script_owned = script.to_string();
        timeout(self.cdp_timeout, self.page.evaluate(script))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "page.evaluate".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::ScriptExecutionFailed {
                script: script_owned.clone(),
                reason: e.to_string(),
            })?
            .into_value::<T>()
            .map_err(|e| BrowserError::ScriptExecutionFailed {
                script: script_owned,
                reason: e.to_string(),
            })
    }

    ///
    /// # Errors
    ///
    pub async fn save_cookies(
        &self,
    ) -> Result<Vec<chromiumoxide::cdp::browser_protocol::network::Cookie>> {
        use chromiumoxide::cdp::browser_protocol::network::GetCookiesParams;

        let url = self
            .page
            .url()
            .await
            .map_err(|e| BrowserError::CdpError {
                operation: "page.url".to_string(),
                message: e.to_string(),
            })?
            .unwrap_or_default();

        timeout(
            self.cdp_timeout,
            self.page
                .execute(GetCookiesParams::builder().urls(vec![url]).build()),
        )
        .await
        .map_err(|_| BrowserError::Timeout {
            operation: "Network.getCookies".to_string(),
            duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
        })?
        .map_err(|e| BrowserError::CdpError {
            operation: "Network.getCookies".to_string(),
            message: e.to_string(),
        })
        .map(|r| r.cookies.clone())
    }

    ///
    /// [`SessionSnapshot`][crate::session::SessionSnapshot] and without
    /// requiring a direct `chromiumoxide` dependency in calling code.
    ///
    /// Individual cookie failures are logged as warnings and do not abort the
    /// remaining cookies.
    ///
    /// # Errors
    ///
    /// call exceeds `cdp_timeout`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig};
    /// use stygian_browser::session::SessionCookie;
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let page = handle.browser().expect("valid browser").new_page().await?;
    /// let cookies = vec![SessionCookie {
    ///     name: "session".to_string(),
    ///     value: "abc123".to_string(),
    ///     domain: ".example.com".to_string(),
    ///     path: "/".to_string(),
    ///     expires: -1.0,
    ///     http_only: true,
    ///     secure: true,
    ///     same_site: "Lax".to_string(),
    /// }];
    /// page.inject_cookies(&cookies).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn inject_cookies(&self, cookies: &[crate::session::SessionCookie]) -> Result<()> {
        use chromiumoxide::cdp::browser_protocol::network::SetCookieParams;

        for cookie in cookies {
            let params = match SetCookieParams::builder()
                .name(cookie.name.clone())
                .value(cookie.value.clone())
                .domain(cookie.domain.clone())
                .path(cookie.path.clone())
                .http_only(cookie.http_only)
                .secure(cookie.secure)
                .build()
            {
                Ok(p) => p,
                Err(e) => {
                    warn!(cookie = %cookie.name, error = %e, "Failed to build cookie params");
                    continue;
                }
            };

            match timeout(self.cdp_timeout, self.page.execute(params)).await {
                Err(_) => {
                    warn!(
                        cookie = %cookie.name,
                        timeout_ms = self.cdp_timeout.as_millis(),
                        "Timed out injecting cookie"
                    );
                }
                Ok(Err(e)) => {
                    warn!(cookie = %cookie.name, error = %e, "Failed to inject cookie");
                }
                Ok(Ok(_)) => {}
            }
        }

        debug!(count = cookies.len(), "Cookies injected");
        Ok(())
    }

    /// Capture a screenshot of the current page as PNG bytes.
    ///
    /// them in-memory.
    ///
    /// # Errors
    ///
    /// command fails, or [`BrowserError::Timeout`] if it exceeds
    /// `cdp_timeout`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::{time::Duration, fs};
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// let png = page.screenshot().await?;
    /// fs::write("screenshot.png", &png).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    pub async fn screenshot(&self) -> Result<Vec<u8>> {
        use chromiumoxide::page::ScreenshotParams;

        let params = ScreenshotParams::builder().full_page(true).build();

        timeout(self.cdp_timeout, self.page.screenshot(params))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "Page.captureScreenshot".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: "Page.captureScreenshot".to_string(),
                message: e.to_string(),
            })
    }

    /// Borrow the underlying chromiumoxide [`Page`].
    pub const fn inner(&self) -> &Page {
        &self.page
    }

    /// Close this page (tab).
    ///
    pub async fn close(self) -> Result<()> {
        timeout(Duration::from_secs(5), self.page.clone().close())
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "page.close".to_string(),
                duration_ms: 5000,
            })?
            .map_err(|e| BrowserError::CdpError {
                operation: "page.close".to_string(),
                message: e.to_string(),
            })
    }
}

// ─── Stealth diagnostics ──────────────────────────────────────────────────────

#[cfg(feature = "stealth")]
impl PageHandle {
    /// Run all built-in stealth detection checks against the current page.
    ///
    /// Iterates [`crate::diagnostic::all_checks`], evaluates each check's
    /// JavaScript via CDP `Runtime.evaluate`, and returns an aggregate
    /// [`crate::diagnostic::DiagnosticReport`].
    ///
    /// recorded as failing checks and do **not** abort the whole run.
    ///
    /// # Errors
    ///
    /// Individual check failures are captured in the report.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// use stygian_browser::{BrowserPool, BrowserConfig};
    /// use stygian_browser::page::WaitUntil;
    /// use std::time::Duration;
    ///
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let browser = handle.browser().expect("valid browser");
    /// let mut page = browser.new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(10)).await?;
    ///
    /// let report = page.verify_stealth().await?;
    /// println!("Stealth: {}/{} checks passed", report.passed_count, report.checks.len());
    /// # for failure in report.failures() {
    ///     eprintln!("  FAIL  {}: {}", failure.description, failure.details);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn verify_stealth(&self) -> Result<crate::diagnostic::DiagnosticReport> {
        use crate::diagnostic::{CheckResult, DiagnosticReport, all_checks};

        let mut results: Vec<CheckResult> = Vec::new();

        for check in all_checks() {
            let result = match self.eval::<String>(check.script).await {
                Ok(json) => check.parse_output(&json),
                Err(e) => {
                    tracing::warn!(
                        check = ?check.id,
                        error = %e,
                        "stealth check script failed during evaluation"
                    );
                    CheckResult {
                        id: check.id,
                        description: check.description.to_string(),
                        passed: false,
                        details: format!("script error: {e}"),
                    }
                }
            };
            tracing::debug!(
                check = ?result.id,
                passed = result.passed,
                details = %result.details,
                "stealth check result"
            );
            results.push(result);
        }

        Ok(DiagnosticReport::new(results))
    }

    /// Run stealth checks and attach transport diagnostics (JA3/JA4/HTTP3).
    ///
    pub async fn verify_stealth_with_transport(
        &self,
        observed: Option<crate::diagnostic::TransportObservations>,
    ) -> Result<crate::diagnostic::DiagnosticReport> {
        let report = self.verify_stealth().await?;

        let user_agent = match self.eval::<String>("navigator.userAgent").await {
            Ok(ua) => ua,
            Err(e) => {
                tracing::warn!(error = %e, "failed to read navigator.userAgent for transport diagnostics");
                String::new()
            }
        };

        let transport = crate::diagnostic::TransportDiagnostic::from_user_agent_and_observations(
            &user_agent,
            observed.as_ref(),
        );

        Ok(report.with_transport(transport))
    }
}

// ─── extract feature ─────────────────────────────────────────────────────────

#[cfg(feature = "extract")]
impl PageHandle {
    ///
    ///
    /// All per-node extractions are driven concurrently via
    /// [`futures::future::try_join_all`].
    ///
    /// # Errors
    ///
    /// fails, or [`BrowserError::ExtractionFailed`] if any field extraction
    /// fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use stygian_browser::extract::Extract;
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use std::time::Duration;
    ///
    /// #[derive(Extract)]
    /// struct Link {
    ///     href: Option<String>,
    /// }
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate(
    ///     "https://example.com",
    ///     WaitUntil::DomContentLoaded,
    ///     Duration::from_secs(30),
    /// ).await?;
    /// let links: Vec<Link> = page.extract_all::<Link>("nav li").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn extract_all<T>(&self, selector: &str) -> Result<Vec<T>>
    where
        T: crate::extract::Extractable,
    {
        use futures::future::try_join_all;

        let nodes = self.query_selector_all(selector).await?;
        try_join_all(nodes.iter().map(|n| T::extract_from(n)))
            .await
            .map_err(BrowserError::ExtractionFailed)
    }
}

// ─── similarity feature ──────────────────────────────────────────────────────

#[cfg(feature = "similarity")]
impl NodeHandle {
    /// node.
    ///
    /// Issues a single `Runtime.callFunctionOn` JS eval that extracts the tag,
    /// class list, attribute names, and body-depth in one round-trip.
    ///
    /// # Errors
    ///
    /// invalidated, or [`BrowserError::ScriptExecutionFailed`] if the script
    /// produces unexpected output.
    pub async fn fingerprint(&self) -> Result<crate::similarity::ElementFingerprint> {
        const JS: &str = r"function() {
    var el = this;
    var tag = el.tagName.toLowerCase();
    var classes = Array.prototype.slice.call(el.classList).sort();
    var attrNames = Array.prototype.slice.call(el.attributes)
        .map(function(a) { return a.name; })
        .filter(function(n) { return n !== 'class' && n !== 'id'; })
        .sort();
    var depth = 0;
    var n = el.parentElement;
    while (n && n.tagName.toLowerCase() !== 'body') { depth++; n = n.parentElement; }
    return JSON.stringify({ tag: tag, classes: classes, attrNames: attrNames, depth: depth });
}";

        let returns = tokio::time::timeout(self.cdp_timeout, self.element.call_js_fn(JS, true))
            .await
            .map_err(|_| BrowserError::Timeout {
                operation: "NodeHandle::fingerprint".to_string(),
                duration_ms: u64::try_from(self.cdp_timeout.as_millis()).unwrap_or(u64::MAX),
            })?
            .map_err(|e| self.cdp_err_or_stale(&e, "fingerprint"))?;

        let json_str = returns
            .result
            .value
            .as_ref()
            .and_then(|v| v.as_str())
            .ok_or_else(|| BrowserError::ScriptExecutionFailed {
                script: "NodeHandle::fingerprint".to_string(),
                reason: "CDP returned no string value from fingerprint script".to_string(),
            })?;

        serde_json::from_str::<crate::similarity::ElementFingerprint>(json_str).map_err(|e| {
            BrowserError::ScriptExecutionFailed {
                script: "NodeHandle::fingerprint".to_string(),
                reason: format!("failed to deserialise fingerprint JSON: {e}"),
            }
        })
    }
}

#[cfg(feature = "similarity")]
impl PageHandle {
    /// `reference`, scored by [`crate::similarity::SimilarityConfig`].
    ///
    /// [`NodeHandle::fingerprint`]), then fingerprints every candidate returned
    /// [`crate::similarity::jaccard_weighted`] score exceeds
    /// `config.threshold`.  Results are ordered by score descending.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{BrowserPool, BrowserConfig, WaitUntil};
    /// use stygian_browser::similarity::SimilarityConfig;
    /// use std::time::Duration;
    ///
    /// # async fn run() -> stygian_browser::error::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let handle = pool.acquire().await?;
    /// let mut page = handle.browser().expect("valid browser").new_page().await?;
    /// page.navigate("https://example.com", WaitUntil::DomContentLoaded, Duration::from_secs(30)).await?;
    ///
    /// # let nodes = page.query_selector_all("h1").await?;
    /// # let reference = nodes.into_iter().next().ok_or(stygian_browser::error::BrowserError::StaleNode { selector: "h1".to_string() })?;
    ///     let similar = page.find_similar(&reference, SimilarityConfig::default()).await?;
    /// # for m in &similar {
    ///         println!("score={:.2}", m.score);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`BrowserError::ScriptExecutionFailed`] if a scoring script fails.
    pub async fn find_similar(
        &self,
        reference: &NodeHandle,
        config: crate::similarity::SimilarityConfig,
    ) -> Result<Vec<crate::similarity::SimilarMatch>> {
        use crate::similarity::{SimilarMatch, jaccard_weighted};

        let ref_fp = reference.fingerprint().await?;
        let candidates = self.query_selector_all("*").await?;

        let mut matches: Vec<SimilarMatch> = Vec::new();
        for node in candidates {
            if let Ok(cand_fp) = node.fingerprint().await {
                let score = jaccard_weighted(&ref_fp, &cand_fp);
                if score >= config.threshold {
                    matches.push(SimilarMatch { node, score });
                }
            }
            // Stale / detached nodes are silently skipped.
        }

        matches.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        if config.max_results > 0 {
            matches.truncate(config.max_results);
        }

        Ok(matches)
    }
}

impl Drop for PageHandle {
    fn drop(&mut self) {
        warn!("PageHandle dropped without explicit close(); spawning cleanup task");
        // chromiumoxide Page does not implement close on Drop, so we spawn
        // swap it out. We clone the Page handle (it's Arc-backed internally).
        let page = self.page.clone();
        tokio::spawn(async move {
            let _ = page.close().await;
        });
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    #[test]
    fn resource_filter_block_media_blocks_image() {
        let filter = ResourceFilter::block_media();
        assert!(filter.should_block("Image"));
        assert!(filter.should_block("Font"));
        assert!(filter.should_block("Stylesheet"));
        assert!(filter.should_block("Media"));
        assert!(!filter.should_block("Script"));
        assert!(!filter.should_block("XHR"));
    }

    #[test]
    fn resource_filter_case_insensitive() {
        let filter = ResourceFilter::block_images_and_fonts();
        assert!(filter.should_block("image")); // lowercase
        assert!(filter.should_block("IMAGE")); // uppercase
        assert!(!filter.should_block("Stylesheet"));
    }

    #[test]
    fn resource_filter_builder_chain() {
        let filter = ResourceFilter::default()
            .block(ResourceType::Image)
            .block(ResourceType::Font);
        assert!(filter.should_block("Image"));
        assert!(filter.should_block("Font"));
        assert!(!filter.should_block("Stylesheet"));
    }

    #[test]
    fn resource_filter_dedup_block() {
        let filter = ResourceFilter::default()
            .block(ResourceType::Image)
            .block(ResourceType::Image); // duplicate
        assert_eq!(filter.blocked.len(), 1);
    }

    #[test]
    fn resource_filter_is_empty_when_default() {
        assert!(ResourceFilter::default().is_empty());
        assert!(!ResourceFilter::block_media().is_empty());
    }

    #[test]
    fn wait_until_selector_stores_string() {
        let w = WaitUntil::Selector("#foo".to_string());
        assert!(matches!(w, WaitUntil::Selector(ref s) if s == "#foo"));
    }

    #[test]
    fn resource_type_cdp_str() {
        assert_eq!(ResourceType::Image.as_cdp_str(), "Image");
        assert_eq!(ResourceType::Font.as_cdp_str(), "Font");
        assert_eq!(ResourceType::Stylesheet.as_cdp_str(), "Stylesheet");
        assert_eq!(ResourceType::Media.as_cdp_str(), "Media");
    }

    #[test]
    fn page_handle_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        assert_send::<PageHandle>();
        assert_sync::<PageHandle>();
    }

    /// `Option<u16>` are pure-logic invariants testable without a live browser.
    #[test]
    fn status_code_sentinel_zero_maps_to_none() {
        use std::sync::atomic::{AtomicU16, Ordering};
        let atom = AtomicU16::new(0);
        let code = atom.load(Ordering::Acquire);
        assert_eq!(if code == 0 { None } else { Some(code) }, None::<u16>);
    }

    #[test]
    fn status_code_non_zero_maps_to_some() {
        use std::sync::atomic::{AtomicU16, Ordering};
        for &expected in &[200u16, 301, 404, 503] {
            let atom = AtomicU16::new(expected);
            let code = atom.load(Ordering::Acquire);
            assert_eq!(if code == 0 { None } else { Some(code) }, Some(expected));
        }
    }

    // ── NodeHandle pure-logic tests ───────────────────────────────────────────

    /// `attr_map` relies on `chunks_exact(2)` — verify the pairing logic is
    /// correct without a live browser by exercising it directly.
    #[test]
    fn attr_map_chunking_pairs_correctly() {
        let flat = [
            "id".to_string(),
            "main".to_string(),
            "data-ux".to_string(),
            "Section".to_string(),
            "class".to_string(),
            "container".to_string(),
        ];
        let mut map = std::collections::HashMap::with_capacity(flat.len() / 2);
        for pair in flat.chunks_exact(2) {
            if let [name, value] = pair {
                map.insert(name.clone(), value.clone());
            }
        }
        assert_eq!(map.get("id").map(String::as_str), Some("main"));
        assert_eq!(map.get("data-ux").map(String::as_str), Some("Section"));
        assert_eq!(map.get("class").map(String::as_str), Some("container"));
        assert_eq!(map.len(), 3);
    }

    /// gracefully — the trailing element is silently ignored.
    #[test]
    fn attr_map_chunking_ignores_odd_trailing() {
        let flat = ["orphan".to_string()]; // no value
        let mut map = std::collections::HashMap::new();
        for pair in flat.chunks_exact(2) {
            if let [name, value] = pair {
                map.insert(name.clone(), value.clone());
            }
        }
        assert!(map.is_empty());
    }

    /// Empty flat list → empty map.
    #[test]
    fn attr_map_chunking_empty_input() {
        let flat: Vec<String> = vec![];
        let map: std::collections::HashMap<String, String> = flat
            .chunks_exact(2)
            .filter_map(|pair| {
                if let [name, value] = pair {
                    Some((name.clone(), value.clone()))
                } else {
                    None
                }
            })
            .collect();
        assert!(map.is_empty());
    }

    #[test]
    fn ancestors_json_parse_round_trip() -> std::result::Result<(), serde_json::Error> {
        let json = r#"["p","article","body","html"]"#;
        let result: Vec<String> = serde_json::from_str(json)?;
        assert_eq!(result, ["p", "article", "body", "html"]);
        Ok(())
    }

    #[test]
    fn ancestors_json_parse_empty() -> std::result::Result<(), serde_json::Error> {
        let json = "[]";
        let result: Vec<String> = serde_json::from_str(json)?;
        assert!(result.is_empty());
        Ok(())
    }

    /// `"div::parent"`) must surface that suffix in its `Display` output so
    /// callers can locate the failed traversal in logs.
    #[test]
    fn traversal_selector_suffix_in_stale_error() {
        let e = crate::error::BrowserError::StaleNode {
            selector: "div::parent".to_string(),
        };
        let msg = e.to_string();
        assert!(
            msg.contains("div::parent"),
            "StaleNode display must include the full selector; got: {msg}"
        );
    }

    #[test]
    fn traversal_next_suffix_in_stale_error() {
        let e = crate::error::BrowserError::StaleNode {
            selector: "li.price::next".to_string(),
        };
        assert!(e.to_string().contains("li.price::next"));
    }

    #[test]
    fn traversal_prev_suffix_in_stale_error() {
        let e = crate::error::BrowserError::StaleNode {
            selector: "td.label::prev".to_string(),
        };
        assert!(e.to_string().contains("td.label::prev"));
    }
}