Skip to content

Backends

AbstractBackend

AbstractBackend

Bases: NavigationBackend, ScreenshotBackend, DOMBackend, InputBackend, NetworkBackend, EmulationBackend, PerformanceBackend, DebugBackend, CSSBackend, StorageBackend, EventsBackend, AccessibilityBackend, DialogBackend, ServiceWorkerBackend, AnimationBackend, ExperimentalBackend

Unified abstract interface for browser automation backends.

Composed from domain-specific mixins:

  • :class:NavigationBackend - launch, navigate, tabs, contexts, eval, raw
  • :class:ScreenshotBackend - screenshot, PDF, screencast
  • :class:DOMBackend - DOM query, mutation, locators, snapshot
  • :class:InputBackend - click, type, fill, iframe, shadow DOM
  • :class:NetworkBackend - cookies, headers, HAR, interception
  • :class:EmulationBackend - device, viewport, geolocation, sensors
  • :class:PerformanceBackend - metrics, traces, coverage
  • :class:DebugBackend - breakpoints, stepping, pause/resume
  • :class:CSSBackend - styles, stylesheets, overlay highlights
  • :class:StorageBackend - DOM storage, Cache Storage, IndexedDB
  • :class:EventsBackend - event subscription, console, logs
  • :class:AccessibilityBackend - a11y tree, axe audit
  • :class:DialogBackend - dialogs, security, downloads
  • :class:ServiceWorkerBackend - SW list, unregister, update
  • :class:AnimationBackend - animation list, pause, play, seek
  • :class:ExperimentalBackend - WebAuthn, WebAudio, Media, Cast, BT, extensions

Implementations include CDPBackend (via cdpwave) and BiDiBackend (via bidiwave).

Source code in wavexis/backend/base.py
class AbstractBackend(
    NavigationBackend,
    ScreenshotBackend,
    DOMBackend,
    InputBackend,
    NetworkBackend,
    EmulationBackend,
    PerformanceBackend,
    DebugBackend,
    CSSBackend,
    StorageBackend,
    EventsBackend,
    AccessibilityBackend,
    DialogBackend,
    ServiceWorkerBackend,
    AnimationBackend,
    ExperimentalBackend,
):
    """Unified abstract interface for browser automation backends.

    Composed from domain-specific mixins:

    - :class:`NavigationBackend` - launch, navigate, tabs, contexts, eval, raw
    - :class:`ScreenshotBackend` - screenshot, PDF, screencast
    - :class:`DOMBackend` - DOM query, mutation, locators, snapshot
    - :class:`InputBackend` - click, type, fill, iframe, shadow DOM
    - :class:`NetworkBackend` - cookies, headers, HAR, interception
    - :class:`EmulationBackend` - device, viewport, geolocation, sensors
    - :class:`PerformanceBackend` - metrics, traces, coverage
    - :class:`DebugBackend` - breakpoints, stepping, pause/resume
    - :class:`CSSBackend` - styles, stylesheets, overlay highlights
    - :class:`StorageBackend` - DOM storage, Cache Storage, IndexedDB
    - :class:`EventsBackend` - event subscription, console, logs
    - :class:`AccessibilityBackend` - a11y tree, axe audit
    - :class:`DialogBackend` - dialogs, security, downloads
    - :class:`ServiceWorkerBackend` - SW list, unregister, update
    - :class:`AnimationBackend` - animation list, pause, play, seek
    - :class:`ExperimentalBackend` - WebAuthn, WebAudio, Media, Cast, BT, extensions

    Implementations include CDPBackend (via cdpwave) and BiDiBackend (via bidiwave).
    """

CDPBackend

CDPBackend

Bases: AbstractBackend

Chrome DevTools Protocol backend via cdpwave.

Source code in wavexis/backend/cdp.py
  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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
class CDPBackend(AbstractBackend):
    """Chrome DevTools Protocol backend via cdpwave."""

    def __init__(self) -> None:
        """Initialize the CDP backend.

        Raises:
            ImportError: If cdpwave is not installed.
        """
        if CDPClient is None:
            raise ImportError(
                "cdpwave is not installed. Run: pip install wavexis[cdp]"
            )
        self._client: CDPClient | None = None
        self._session: CDPSession | None = None
        self._console_entries: list[dict[str, Any]] = []
        self._log_entries: list[dict[str, Any]] = []
        self._current_url: str = ""

    async def new_tab_handle(self, url: str = "about:blank") -> TabHandle:
        """Create a new tab with its own session, sharing the browser process.

        Args:
            url: Initial URL for the new tab.

        Returns:
            A TabHandle that can be used like a CDPBackend for concurrent operations.

        Raises:
            SessionNotInitializedError: If launch() has not been called.
        """
        if self._client is None:
            raise SessionNotInitializedError(
                "Backend not launched. Call launch() first."
            )
        session = await self._client.new_page(url)
        return TabHandle(self._client, session)

    def _require_session(self) -> CDPSession:
        """Return the current session or raise if not initialized.

        Returns:
            The active CDPSession instance.

        Raises:
            SessionNotInitializedError: If launch() has not been called.
        """
        if self._session is None:
            raise SessionNotInitializedError(
                "Session not initialized. Call launch() first."
            )
        return self._session

    async def launch(self, options: BrowserOptions) -> None:
        """Launch Chrome and create a new page session.

        Args:
            options: Browser launch options (headless, width, height, proxy, etc.).
        """
        extra_args: list[str] = []
        if options.width and options.height:
            extra_args.append(f"--window-size={options.width},{options.height}")
        if options.proxy:
            extra_args.append(f"--proxy-server={options.proxy}")

        if options.browser_url:
            from urllib.parse import urlparse

            parsed = urlparse(options.browser_url)
            host = parsed.hostname or "localhost"
            port = parsed.port or 9222
            self._client = await CDPClient.connect(host=host, port=port)
        elif options.remote_url:
            self._client = await CDPClient.connect(
                ws_url=options.remote_url
            )
        else:
            self._client = await CDPClient.launch(
                headless=options.headless,
                user_data_dir=options.user_data_dir,  # type: ignore[call-arg]
                extra_args=extra_args if extra_args else None,
            )
        self._session = await self._client.new_page()

        if options.user_agent:
            await self._session.emulation.set_user_agent_override(
                user_agent=options.user_agent
            )

        if options.extra_headers:
            await self._session.network.set_extra_http_headers(
                options.extra_headers
            )

        if options.stealth:
            from wavexis.actions.stealth import get_stealth_js

            await self._session.runtime.evaluate(
                get_stealth_js(), await_promise=False
            )

    async def close(self) -> None:
        """Close the browser client and release resources."""
        if self._session is not None:
            await self._session.close()
            self._session = None
        if self._client is not None:
            await self._client.close()
            self._client = None

    async def navigate(self, url: str, wait: WaitStrategy | None = None) -> None:
        """Navigate to a URL and optionally wait for a condition.

        Args:
            url: The URL to navigate to.
            wait: Wait strategy to apply after navigation.

        Raises:
            SessionNotInitializedError: If launch() has not been called.
            WaitTimeoutError: If the wait strategy times out.
        """
        session = self._require_session()

        await session.page.enable()
        await session.page.navigate(url)
        self._current_url = url

        if wait is None or wait.strategy == "load":
            timeout_sec = (wait.timeout if wait else 30000) / 1000
            try:
                await session.wait_for_event(
                    "Page.loadEventFired", timeout=timeout_sec
                )
            except TimeoutError:
                raise WaitTimeoutError("load", wait.timeout if wait else 30000) from None
        elif wait.strategy == "selector":
            await self.wait_for(wait)
        elif wait.strategy == "domcontentloaded":
            timeout_sec = wait.timeout / 1000
            try:
                await session.wait_for_event(
                    "Page.domContentEventFired", timeout=timeout_sec
                )
            except TimeoutError:
                raise WaitTimeoutError("domcontentloaded", wait.timeout) from None
        elif wait.strategy == "networkidle":
            raise ValueError(
                "networkidle wait strategy is not implemented in CDP backend. "
                "Use 'load', 'domcontentloaded', or 'selector' instead."
            )

    async def screenshot(self, params: ScreenshotParams) -> bytes:
        """Take a screenshot of the current page.

        Args:
            params: Screenshot parameters (format, quality, full_page, etc.).

        Returns:
            Screenshot image bytes (PNG or JPEG).

        Raises:
            SessionNotInitializedError: If launch() has not been called.
        """
        session = self._require_session()

        if params.device and params.device in DEVICE_PRESETS:
            preset = DEVICE_PRESETS[params.device]
            await session.emulation.set_device_metrics_override(
                width=preset["width"],
                height=preset["height"],
                device_scale_factor=preset["device_scale_factor"],
                mobile=preset["mobile"],
                user_agent=preset["user_agent"],
            )
            if preset.get("touch"):
                await session.emulation.set_touch_emulation_enabled(True)

        result = await session.page.capture_screenshot(
            format=params.format,
            quality=params.quality,
            capture_beyond_viewport=params.full_page,
        )
        data_b64 = result.get("data", "")
        return base64.b64decode(data_b64)

    async def screenshot_selector(
        self, selector: str, format: str = "png", quality: int = 80
    ) -> bytes:
        """Take a screenshot of an element matching a CSS selector.

        Uses CDP to get the element's bounding box and clips the screenshot.

        Args:
            selector: CSS selector for the target element.
            format: Image format ("png" or "jpeg").
            quality: JPEG quality (0-100).

        Returns:
            Screenshot image bytes.
        """
        session = self._require_session()

        doc = await session.dom.get_document()
        root_node_id = doc.get("root", {}).get("nodeId", 0)
        node = await session.dom.query_selector(root_node_id, selector)
        node_id = node.get("nodeId", 0)
        box = await session.dom.get_box_model(node_id)
        model = box.get("model", {})
        borders = model.get("border", [])
        if len(borders) >= 8:
            x = min(borders[0], borders[2], borders[4], borders[6])
            y = min(borders[1], borders[3], borders[5], borders[7])
            width = max(borders[0], borders[2], borders[4], borders[6]) - x
            height = max(borders[1], borders[3], borders[5], borders[7]) - y
        else:
            raise NavigationError(selector, "Could not determine element bounds.")

        clip = {
            "x": x,
            "y": y,
            "width": width,
            "height": height,
            "scale": 1,
        }
        result = await session.page.capture_screenshot(
            format=format,
            quality=quality,
            clip=clip,
        )
        data_b64 = result.get("data", "")
        return base64.b64decode(data_b64)

    @staticmethod
    def _annotate_js(selectors: list[str]) -> str:
        """Build JS that overlays numbered labels on elements."""
        selectors_json = json.dumps(selectors)
        return (
            f"(function(){{"
            f"var sels={selectors_json};"
            f"var container=document.createElement('div');"
            f"container.id='__wavexis_annotate';"
            f"container.style.cssText="
            f"'position:fixed;top:0;left:0;width:100%;height:100%;"
            f"pointer-events:none;z-index:999999;';"
            f"var labelMap={{}};"
            f"for(var i=0;i<sels.length;i++){{"
            f"var el=document.querySelector(sels[i]);"
            f"if(!el)continue;"
            f"var rect=el.getBoundingClientRect();"
            f"var label=document.createElement('div');"
            f"var num=i+1;"
            f"label.textContent='@e'+num;"
            f"label.style.cssText="
            f"'position:fixed;left:'+(rect.left+4)+'px;'"
            f"+'top:'+(rect.top+4)+'px;'"
            f"+'background:#ff4444;color:#fff;'"
            f"+'padding:2px 6px;border-radius:3px;'"
            f"+'font:bold 12px monospace;'"
            f"+'pointer-events:none;z-index:999999;';"
            f"var outline=document.createElement('div');"
            f"outline.style.cssText="
            f"'position:fixed;left:'+rect.left+'px;'"
            f"+'top:'+rect.top+'px;'"
            f"+'width:'+rect.width+'px;'"
            f"+'height:'+rect.height+'px;'"
            f"+'border:2px solid #ff4444;'"
            f"+'pointer-events:none;z-index:999998;';"
            f"container.appendChild(outline);"
            f"container.appendChild(label);"
            f"labelMap['e'+num]=sels[i];"
            f"}}"
            f"document.body.appendChild(container);"
            f"return JSON.stringify(labelMap);"
            f"}})()"
        )

    @staticmethod
    def _remove_annotate_js() -> str:
        """Build JS that removes annotation overlays."""
        return (
            "(function(){var e=document.getElementById"
            "('__wavexis_annotate');if(e)e.remove();})()"
        )

    async def annotated_screenshot(
        self,
        selectors: list[str],
        format: str = "png",
    ) -> tuple[bytes, dict[str, str]]:
        """Take a screenshot with numbered labels overlaid on elements.

        Args:
            selectors: List of CSS selectors to annotate.
            format: Image format: "png" or "jpeg".

        Returns:
            Tuple of (image_bytes, label_map).
        """
        session = self._require_session()
        js = self._annotate_js(selectors)
        result = await session.runtime.evaluate(js)
        raw = result.get("result", {}).get("value")
        label_map: dict[str, str] = (
            json.loads(raw) if isinstance(raw, str) else {}
        )
        screenshot = await session.page.capture_screenshot(format=format)
        await session.runtime.evaluate(self._remove_annotate_js())
        data_b64 = screenshot.get("data", "")
        return base64.b64decode(data_b64), label_map

    async def eval(self, expression: str, await_promise: bool = False) -> Any:
        """Evaluate a JavaScript expression.

        Args:
            expression: JavaScript expression to evaluate.
            await_promise: Whether to await a returned Promise.

        Returns:
            The evaluation result value.
        """
        session = self._require_session()

        await session.runtime.enable()
        result = await session.runtime.evaluate(
            expression,
            await_promise=await_promise,
        )
        return result.get("result", {}).get("value")

    async def raw(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
        """Send a raw CDP command.

        Args:
            method: CDP method name (e.g. "Page.navigate").
            params: Optional command parameters.

        Returns:
            The CDP response result dict.
        """
        session = self._require_session()
        result: dict[str, Any] = await session.send(method, params)
        return result

    async def go_back(self) -> None:
        """Navigate back in browser history."""
        session = self._require_session()
        history = await session.page.get_navigation_history()
        current_idx = history.get("currentIndex", 0)
        entries = history.get("entries", [])
        if current_idx > 0 and entries:
            prev_entry = entries[current_idx - 1]
            await session.page.navigate_to_history_entry(
                prev_entry.get("id", 0)
            )

    async def go_forward(self) -> None:
        """Navigate forward in browser history."""
        session = self._require_session()
        history = await session.page.get_navigation_history()
        current_idx = history.get("currentIndex", 0)
        entries = history.get("entries", [])
        if current_idx < len(entries) - 1:
            next_entry = entries[current_idx + 1]
            await session.page.navigate_to_history_entry(
                next_entry.get("id", 0)
            )

    async def reload(self, ignore_cache: bool = False) -> None:
        """Reload the current page.

        Args:
            ignore_cache: If True, bypass the browser cache.
        """
        session = self._require_session()
        await session.page.reload(ignore_cache=ignore_cache)

    async def stop_loading(self) -> None:
        """Stop all pending navigations and resource loads."""
        session = self._require_session()
        await session.page.stop()

    async def wait_for(self, strategy: WaitStrategy) -> None:
        """Wait for a specific condition.

        Args:
            strategy: Wait strategy (selector, load, url).

        Raises:
            WaitTimeoutError: If the condition is not met within the timeout.
        """
        session = self._require_session()

        timeout_sec = strategy.timeout / 1000
        deadline = time.monotonic() + timeout_sec

        if strategy.strategy == "selector" and strategy.selector:
            escaped = json.dumps(strategy.selector)
            js = f"document.querySelector('{escaped}') !== null"
            while time.monotonic() < deadline:
                result = await session.runtime.evaluate(js)
                if result.get("result", {}).get("value") is True:
                    return
                await asyncio.sleep(0.1)
            raise WaitTimeoutError("selector", strategy.timeout)

        if strategy.strategy == "load":
            try:
                await session.wait_for_event(
                    "Page.loadEventFired", timeout=timeout_sec
                )
            except TimeoutError:
                raise WaitTimeoutError("load", strategy.timeout) from None
            return

        if strategy.strategy == "url" and strategy.url_pattern:
            while time.monotonic() < deadline:
                result = await session.runtime.evaluate("window.location.href")
                href = result.get("result", {}).get("value", "")
                if strategy.url_pattern in href:
                    return
                await asyncio.sleep(0.1)
            raise WaitTimeoutError("url", strategy.timeout)

        if strategy.strategy == "domcontentloaded":
            try:
                await session.wait_for_event(
                    "Page.domContentEventFired", timeout=timeout_sec
                )
            except TimeoutError:
                raise WaitTimeoutError("domcontentloaded", strategy.timeout) from None
            return

        if strategy.strategy == "networkidle":
            # Poll for network idle: no more than 2 active requests for 500ms
            js = """
            (function() {
                return window.performance.getEntries()
                    .filter(e => e.entryType === 'resource')
                    .filter(e => !e.duration || e.duration < 0)
                    .length <= 2;
            })()
            """
            deadline = time.monotonic() + timeout_sec
            idle_start = None
            while time.monotonic() < deadline:
                result = await session.runtime.evaluate(js)
                is_idle = result.get("result", {}).get("value", False)
                if is_idle:
                    if idle_start is None:
                        idle_start = time.monotonic()
                    elif time.monotonic() - idle_start >= 0.5:
                        return
                else:
                    idle_start = None
                await asyncio.sleep(0.1)
            raise WaitTimeoutError("networkidle", strategy.timeout)

        # If we get here, the strategy is not supported
        raise ValueError(f"Unsupported wait strategy: {strategy.strategy}")

    async def pdf(self, params: PDFParams) -> bytes:
        """Generate a PDF of the current page.

        Args:
            params: PDF generation parameters.

        Returns:
            PDF bytes.
        """
        session = self._require_session()

        await session.emulation.set_emulated_media(media=params.media)

        paper_dims = PAPER_SIZES.get(params.paper, PAPER_SIZES["letter"])
        margin_val = float(params.margin.replace("in", "").replace("cm", ""))

        result = await session.page.print_to_pdf(
            landscape=params.landscape,
            display_header_footer=not params.no_header_footer,
            print_background=True,
            paper_width=paper_dims["width"],
            paper_height=paper_dims["height"],
            margin_top=margin_val,
            margin_bottom=margin_val,
            margin_left=margin_val,
            margin_right=margin_val,
        )
        data_b64 = result.get("data", "")
        return base64.b64decode(data_b64)

    async def screencast(self, params: ScreencastParams) -> list[bytes]:
        """Capture a screencast and return a list of frame bytes.

        Args:
            params: Screencast parameters.

        Returns:
            List of frame image bytes.
        """
        session = self._require_session()

        frames: list[bytes] = []

        def on_frame(event_params: dict[str, Any]) -> None:
            """Handle a screencast frame event and decode the image data.

            Args:
                event_params: CDP event parameters containing base64-encoded frame data.
            """
            data = event_params.get("data")
            if data:
                frames.append(base64.b64decode(data))

        session.on("Page.screencastFrame", on_frame)

        await session.send("Page.startScreencast", {
            "format": params.format,
            "quality": params.quality,
            "maxWidth": params.max_width,
            "maxHeight": params.max_height,
        })

        await asyncio.sleep(params.duration)

        await session.send("Page.stopScreencast")

        return frames

    async def list_tabs(self) -> list[dict[str, Any]]:
        """List all open browser tabs/targets.

        Returns:
            List of target info dicts.
        """
        session = self._require_session()
        result = await session.target.get_targets()
        targets = result.get("targetInfos", [])
        return [t for t in targets if t.get("type") == "page"]

    async def new_tab(self, url: str = "about:blank") -> str:
        """Create a new tab and return its target ID.

        Args:
            url: Initial URL for the new tab.

        Returns:
            The target ID of the new tab.
        """
        session = self._require_session()
        result = await session.target.create_target(url)
        return str(result.get("targetId", ""))

    async def close_tab(self, tab_id: str) -> None:
        """Close a tab by its target ID.

        Args:
            tab_id: The target ID of the tab to close.
        """
        session = self._require_session()
        await session.target.close_target(tab_id)

    async def activate_tab(self, tab_id: str) -> None:
        """Activate (focus) a tab by its target ID.

        Args:
            tab_id: The target ID of the tab to activate.
        """
        session = self._require_session()
        await session.target.activate_target(tab_id)

    async def capture_console(self, level: str = "all") -> list[dict[str, Any]]:
        """Capture console messages at or above the given level.

        Args:
            level: Minimum log level ("all", "error", "warning", "info", "log").

        Returns:
            List of console entry dicts with type, args, and timestamp.
        """
        session = self._require_session()

        entries: list[dict[str, Any]] = []

        def on_console_api(event_params: dict[str, Any]) -> None:
            """Handle a Runtime.consoleAPICalled event and append matching entries.

            Args:
                event_params: CDP event parameters with console API call data.
            """
            entry_type = event_params.get("type", "log")
            if level == "all" or entry_type == level:
                entries.append({
                    "type": entry_type,
                    "args": event_params.get("args", []),
                    "executionContextId": event_params.get("executionContextId"),
                    "timestamp": event_params.get("timestamp"),
                })

        session.on("Runtime.consoleAPICalled", on_console_api)

        await session.runtime.enable()
        await asyncio.sleep(0.5)

        return entries

    async def capture_logs(self) -> list[dict[str, Any]]:
        """Capture browser log entries.

        Returns:
            List of log entry dicts with level, text, and timestamp.
        """
        session = self._require_session()

        entries: list[dict[str, Any]] = []

        def on_log_entry(event_params: dict[str, Any]) -> None:
            """Handle a Log.entryAdded event and append the log entry.

            Args:
                event_params: CDP event parameters containing the log entry.
            """
            entry = event_params.get("entry", {})
            entries.append({
                "level": entry.get("level", "info"),
                "text": entry.get("text", ""),
                "timestamp": entry.get("timestamp"),
                "url": entry.get("url"),
                "lineNumber": entry.get("lineNumber"),
                "stackTrace": entry.get("stackTrace", []),
            })

        session.on("Log.entryAdded", on_log_entry)

        await session.log.enable()
        await asyncio.sleep(0.5)

        return entries

    # ── DOM ────────────────────────────────────────────────

    async def _find_node(self, selector: str) -> int:
        """Find a node by CSS selector and return its nodeId."""
        session = self._require_session()
        await session.dom.enable()
        doc = await session.dom.get_document()
        root_node_id = doc.get("root", {}).get("nodeId", 0)
        result = await session.dom.query_selector(root_node_id, selector)
        node_id = result.get("nodeId", 0)
        if node_id == 0:
            raise ElementNotFoundError(selector)
        return int(node_id)

    async def dom_get(self, selector: str, outer: bool = True) -> str:
        """Get the HTML of an element matching a CSS selector.

        Args:
            selector: CSS selector for the target element.
            outer: If True, return outerHTML; otherwise innerHTML.

        Returns:
            The HTML string of the element.
        """
        session = self._require_session()
        node_id = await self._find_node(selector)
        if outer:
            result = await session.dom.get_outer_html(node_id)
            return str(result.get("outerHTML", ""))
        result = await session.dom.get_outer_html(node_id)
        outer_html = str(result.get("outerHTML", ""))
        inner = re.sub(r"^<[^>]+>", "", outer_html, count=1)
        inner = re.sub(r"<[^>]+>$", "", inner, count=1)
        return inner

    async def dom_query(
        self, selector: str, all: bool = False
    ) -> list[dict[str, Any]] | dict[str, Any]:
        """Query elements by CSS selector.

        Args:
            selector: CSS selector string.
            all: If True, return all matches as a list; otherwise first match.

        Returns:
            List of node dicts when all=True, single dict when all=False.
        """
        session = self._require_session()
        await session.dom.enable()
        doc = await session.dom.get_document()
        root_node_id = doc.get("root", {}).get("nodeId", 0)

        if all:
            result = await session.dom.query_selector_all(root_node_id, selector)
            node_ids = result.get("nodeIds", [])
            nodes: list[dict[str, Any]] = []
            for nid in node_ids:
                desc = await session.dom.describe_node(node_id=nid)
                nodes.append(desc.get("node", {}))
            return nodes

        result = await session.dom.query_selector(root_node_id, selector)
        node_id = result.get("nodeId", 0)
        if node_id == 0:
            raise ElementNotFoundError(selector)
        desc = await session.dom.describe_node(node_id=node_id)
        return dict(desc.get("node", {}))

    async def dom_set_attr(self, selector: str, name: str, value: str) -> None:
        """Set an attribute on an element matching a CSS selector."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.dom.set_attribute_value(node_id, name, value)

    async def dom_get_attr(self, selector: str, name: str) -> str:
        """Get an attribute value from an element matching a CSS selector."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        result = await session.dom.get_attribute(node_id, name)
        attrs = result.get("attributes", [])
        for i in range(0, len(attrs) - 1, 2):
            if attrs[i] == name:
                return str(attrs[i + 1])
        return ""

    async def dom_remove_attr(self, selector: str, name: str) -> None:
        """Remove an attribute from an element matching a CSS selector."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.dom.remove_attribute(node_id, name)

    async def dom_remove(self, selector: str) -> None:
        """Remove an element matching a CSS selector from the DOM."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.dom.remove_node(node_id)

    async def dom_focus(self, selector: str) -> None:
        """Focus an element matching a CSS selector."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.dom.focus(node_id)

    async def dom_scroll(
        self, selector: str | None = None, x: int = 0, y: int = 0
    ) -> None:
        """Scroll to an element or by offset.

        Args:
            selector: CSS selector to scroll to. If None, scroll by offset.
            x: Horizontal scroll offset.
            y: Vertical scroll offset.
        """
        session = self._require_session()
        if selector:
            escaped = json.dumps(selector)
            js = f"document.querySelector('{escaped}').scrollIntoView()"
        else:
            js = f"window.scrollBy({x}, {y})"
        await session.runtime.evaluate(js)

    async def suggest_locator(
        self, selector: str, all: bool = False
    ) -> list[str] | str:
        """Suggest the best CSS selector for an element.

        Args:
            selector: CSS selector for the target element.
            all: If True, return multiple suggestions; otherwise just the best one.

        Returns:
            List of selector strings when all=True, single best selector when all=False.
        """
        session = self._require_session()
        escaped = json.dumps(selector)
        js = self._suggest_locator_js(escaped)
        result = await session.runtime.evaluate(js)
        raw = result.get("result", {}).get("value")
        if not raw:
            raise ElementNotFoundError(selector)
        suggestions: list[str] = json.loads(raw)
        if all:
            return suggestions
        return suggestions[0] if suggestions else selector

    @staticmethod
    def _suggest_locator_js(escaped: str) -> str:
        """Build JS that generates CSS selector suggestions for an element."""
        return (
            f"(function(){{"
            f"var el=document.querySelector('{escaped}');"
            f"if(!el)return null;"
            f"var s=[];var t=el.tagName.toLowerCase();"
            f"var id=el.id;"
            f"var tid=el.getAttribute('data-testid')"
            f"||el.getAttribute('data-test-id')"
            f"||el.getAttribute('data-cy');"
            f"var aria=el.getAttribute('aria-label');"
            f"var role=el.getAttribute('role');"
            f"var txt=(el.textContent||'').trim().substring(0,50);"
            f"var cls=Array.from(el.classList);"
            f"if(id)s.push('#'+CSS.escape(id));"
            f"if(tid)s.push('[data-testid=\"'+tid+'\"]');"
            f"if(aria)s.push(t+'[aria-label=\"'+aria+'\"]');"
            f"if(role)s.push(t+'[role=\"'+role+'\"]');"
            f"if(txt&&txt.length<30)s.push(t+':has-text(\"'+txt+'\"]');"
            f"if(cls.length>0)s.push(t+'.'+cls.join('.'));"
            f"var p=el.parentElement;"
            f"if(p&&p.id)s.push('#'+CSS.escape(p.id)+' > '+t);"
            f"var sib=p?Array.from(p.children)"
            f".filter(function(c){{return c.tagName===el.tagName}}):[];"
            f"if(sib.length>1){{"
            f"var i=sib.indexOf(el)+1;"
            f"s.push(t+':nth-of-type('+i+')');}}"
            f"s.push(t);"
            f"return JSON.stringify(s);"
            f"}})()"
        )

    @staticmethod
    def _find_by_text_js(query: str) -> str:
        """Build JS that finds elements by natural language text query."""
        escaped = json.dumps(query)
        return (
            f"(function(){{"
            f"var q='{escaped}'.toLowerCase().trim();"
            f"var words=q.split(/\\s+/);"
            f"var els=Array.from(document.querySelectorAll('*'));"
            f"var results=[];"
            f"for(var i=0;i<els.length;i++){{"
            f"var el=els[i];"
            f"var rect=el.getBoundingClientRect();"
            f"if(rect.width===0||rect.height===0)continue;"
            f"var texts=["
            f"(el.textContent||'').trim(),"
            f"el.getAttribute('aria-label')||'',"
            f"el.getAttribute('placeholder')||'',"
            f"el.getAttribute('title')||'',"
            f"el.getAttribute('alt')||'',"
            f"el.getAttribute('value')||''"
            f"].map(function(t){{return t.toLowerCase()}});"
            f"var bestScore=0;"
            f"for(var j=0;j<texts.length;j++){{"
            f"var t=texts[j];if(!t)continue;"
            f"if(t===q){{bestScore=100;break;}}"
            f"if(t.indexOf(q)>=0){{bestScore=Math.max(bestScore,80);}}"
            f"if(q.indexOf(t)>=0&&t.length>3){{bestScore=Math.max(bestScore,60);}}"
            f"var matched=0;"
            f"for(var k=0;k<words.length;k++){{"
            f"if(t.indexOf(words[k])>=0)matched++;"
            f"}}"
            f"if(matched>0)bestScore=Math.max(bestScore,"
            f"Math.round(matched/words.length*50));"
            f"}}"
            f"if(bestScore>0){{"
            f"var tag=el.tagName.toLowerCase();"
            f"var sel=tag;"
            f"if(el.id)sel='#'+CSS.escape(el.id);"
            f"else if(el.getAttribute('data-testid'))"
            f"sel='[data-testid=\"'+el.getAttribute('data-testid')+'\"]';"
            f"else if(el.getAttribute('aria-label'))"
            f"sel=tag+'[aria-label=\"'+el.getAttribute('aria-label')+'\"]';"
            f"else if(el.classList.length>0)"
            f"sel=tag+'.'+Array.from(el.classList).join('.');"
            f"results.push({{score:bestScore,sel:sel}});"
            f"}}"
            f"}}"
            f"results.sort(function(a,b){{return b.score-a.score}});"
            f"return JSON.stringify(results.map(function(r){{return r.sel}}));"
            f"}})()"
        )

    async def find_by_text(
        self, query: str, all: bool = False
    ) -> list[str] | str:
        """Find elements by natural language text query.

        Args:
            query: Natural language query (e.g. "the login button").
            all: If True, return all matches; otherwise just the best one.

        Returns:
            List of CSS selector strings when all=True, single best when all=False.

        Raises:
            ElementNotFoundError: If no element matches the query.
        """
        session = self._require_session()
        js = self._find_by_text_js(query)
        result = await session.runtime.evaluate(js)
        raw = result.get("result", {}).get("value")
        if not raw:
            raise ElementNotFoundError(query)
        selectors: list[str] = json.loads(raw)
        if not selectors:
            raise ElementNotFoundError(query)
        if all:
            return selectors
        return selectors[0]

    async def nl_click(
        self, query: str, auto_wait: bool = True
    ) -> None:
        """Click an element found by natural language text query.

        Args:
            query: Natural language query (e.g. "login button").
            auto_wait: If True, wait for element to be visible before clicking.
        """
        selector = await self.find_by_text(query)
        assert isinstance(selector, str)
        await self.click(selector, auto_wait=auto_wait)

    async def nl_fill(
        self, query: str, value: str, auto_wait: bool = True
    ) -> None:
        """Fill an input element found by natural language text query.

        Args:
            query: Natural language query (e.g. "email field").
            value: Value to set in the input field.
            auto_wait: If True, wait for element to be visible before filling.
        """
        selector = await self.find_by_text(query)
        assert isinstance(selector, str)
        await self.fill(selector, value, auto_wait=auto_wait)

    # ── Network ────────────────────────────────────────────

    async def capture_har(self, params: HarParams) -> dict[str, Any]:
        """Navigate to a URL and capture network traffic as HAR 1.2 dict.

        Args:
            params: HAR capture parameters.

        Returns:
            HAR 1.2 compliant dict with log.entries.
        """
        session = self._require_session()

        requests: dict[str, dict[str, Any]] = {}
        responses: dict[str, dict[str, Any]] = {}
        finished: dict[str, dict[str, Any]] = {}

        def on_request(event_params: dict[str, Any]) -> None:
            """Handle Network.requestWillBeSent and record the request.

            Args:
                event_params: CDP event parameters with request data.
            """
            req_id = event_params.get("requestId", "")
            request = event_params.get("request", {})
            requests[req_id] = {
                "method": request.get("method", "GET"),
                "url": request.get("url", ""),
                "headers": [
                    {"name": k, "value": v}
                    for k, v in request.get("headers", {}).items()
                ],
                "queryString": [
                    {"name": k, "value": v}
                    for k, v in request.get("queryString", {}).items()
                ],
                "headersSize": -1,
                "bodySize": -1,
                "timestamp": event_params.get("timestamp", 0),
                "wallTime": event_params.get("wallTime", 0),
                "type": event_params.get("type", ""),
            }

        def on_response(event_params: dict[str, Any]) -> None:
            """Handle Network.responseReceived and record the response.

            Args:
                event_params: CDP event parameters with response data.
            """
            req_id = event_params.get("requestId", "")
            response = event_params.get("response", {})
            responses[req_id] = {
                "status": response.get("status", 0),
                "statusText": response.get("statusText", ""),
                "headers": [
                    {"name": k, "value": v}
                    for k, v in response.get("headers", {}).items()
                ],
                "mimeType": response.get("mimeType", ""),
                "redirectURL": response.get("redirectUrl", ""),
                "headersSize": response.get("headersSize", -1),
                "bodySize": response.get("encodedDataLength", -1),
                "content": {
                    "size": response.get("content", {}).get("size", 0),
                    "mimeType": response.get("content", {}).get("mimeType", ""),
                },
            }

        def on_loading_finished(event_params: dict[str, Any]) -> None:
            """Handle Network.loadingFinished and mark a request as complete.

            Args:
                event_params: CDP event parameters with loading finish data.
            """
            req_id = event_params.get("requestId", "")
            finished[req_id] = {
                "timestamp": event_params.get("timestamp", 0),
                "encodedDataLength": event_params.get("encodedDataLength", 0),
            }

        session.on("Network.requestWillBeSent", on_request)
        session.on("Network.responseReceived", on_response)
        session.on("Network.loadingFinished", on_loading_finished)

        await session.network.enable()
        await self.navigate(params.url, WaitStrategy(strategy="load"))
        await asyncio.sleep(params.wait / 1000)

        entries: list[dict[str, Any]] = []
        for req_id, req_data in requests.items():
            url = req_data.get("url", "")
            if params.filter and params.filter not in url:
                continue
            resp = responses.get(req_id, {})
            fin = finished.get(req_id, {})
            wall_time = req_data.get("wallTime", 0)
            started_dt = (
                f"{time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(wall_time))}"
                if wall_time
                else ""
            )
            send_time = 0
            wait_time = max(
                float(fin.get("timestamp", 0)) - float(req_data.get("timestamp", 0)),
                0.0,
            )
            receive_time = 0
            entries.append({
                "request": {
                    "method": req_data.get("method", "GET"),
                    "url": url,
                    "headers": req_data.get("headers", []),
                    "queryString": req_data.get("queryString", []),
                    "headersSize": req_data.get("headersSize", -1),
                    "bodySize": req_data.get("bodySize", -1),
                },
                "response": {
                    "status": resp.get("status", 0),
                    "statusText": resp.get("statusText", ""),
                    "headers": resp.get("headers", []),
                    "content": resp.get("content", {"size": 0, "mimeType": ""}),
                    "redirectURL": resp.get("redirectURL", ""),
                    "headersSize": resp.get("headersSize", -1),
                    "bodySize": resp.get("bodySize", -1),
                },
                "timings": {
                    "send": send_time,
                    "wait": round(wait_time * 1000, 2),
                    "receive": receive_time,
                },
                "time": round((wait_time + send_time + receive_time) * 1000, 2),
                "startedDateTime": started_dt,
            })

        return {
            "log": {
                "version": "1.2",
                "creator": {"name": "wavexis", "version": "0.3.0"},
                "entries": entries,
            }
        }

    async def get_cookies(self) -> list[dict[str, Any]]:
        """Get all cookies for the current page.

        Returns:
            List of cookie dicts.
        """
        session = self._require_session()
        result = await session.network.get_cookies()
        return list(result.get("cookies", []))

    async def set_cookie(self, params: CookieParams) -> None:
        """Set a cookie in the browser.

        Args:
            params: Cookie parameters.
        """
        session = self._require_session()
        await session.network.set_cookie(
            name=params.name,
            value=params.value,
            domain=params.domain or None,
            path=params.path,
            secure=params.secure,
            http_only=params.http_only,
            same_site=params.same_site,
        )

    async def delete_cookie(self, name: str, domain: str) -> None:
        """Delete cookies matching name and domain.

        Args:
            name: Cookie name to delete.
            domain: Cookie domain to scope deletion.
        """
        session = self._require_session()
        await session.network.delete_cookies(name=name, domain=domain)

    async def clear_cookies(self) -> None:
        """Clear all browser cookies."""
        session = self._require_session()
        await session.network.clear_browser_cookies()

    async def set_headers(self, headers: dict[str, str]) -> None:
        """Set extra HTTP headers for all requests.

        Args:
            headers: Dict of header name to value.
        """
        session = self._require_session()
        await session.network.enable()
        await session.network.set_extra_request_headers(headers)

    async def set_user_agent(self, user_agent: str) -> None:
        """Override the browser's User-Agent string.

        Args:
            user_agent: The User-Agent string to use.
        """
        session = self._require_session()
        await session.network.set_user_agent_override(user_agent=user_agent)

    # ── Browser management ─────────────────────────────────

    async def new_context(self) -> str:
        """Create a new browser context and return its ID.

        Returns:
            The browser context ID string.
        """
        self._require_session()
        if self._client is None:
            raise NavigationError("", "Client not initialized.")
        result = await self._client.send("Target.createBrowserContext", {})
        return str(result.get("browserContextId", ""))

    async def list_contexts(self) -> list[dict[str, Any]]:
        """List all browser contexts.

        Returns:
            List of context info dicts.
        """
        session = self._require_session()
        result = await session.send("Target.getBrowserContexts")
        contexts = result.get("browserContextIds", [])
        return [{"contextId": ctx} for ctx in contexts]

    async def close_context(self, context_id: str) -> None:
        """Close a browser context by ID.

        Args:
            context_id: The browser context ID to close.
        """
        session = self._require_session()
        await session.target.dispose_browser_context(context_id)

    async def get_window_bounds(self) -> dict[str, Any]:
        """Get the current window bounds.

        Returns:
            Dict with width, height, left, top.
        """
        session = self._require_session()
        if self._client is None:
            raise NavigationError("", "Client not initialized.")
        result = await self._client.browser.get_window_for_target(
            target_id=session.target_id
        )
        bounds = result.get("bounds", {})
        return {
            "width": bounds.get("width", 0),
            "height": bounds.get("height", 0),
            "x": bounds.get("left", 0),
            "y": bounds.get("top", 0),
        }

    async def set_window_bounds(
        self, width: int, height: int, x: int = 0, y: int = 0
    ) -> None:
        """Set the window bounds.

        Args:
            width: Window width in pixels.
            height: Window height in pixels.
            x: Window X position.
            y: Window Y position.
        """
        session = self._require_session()
        if self._client is None:
            raise NavigationError("", "Client not initialized.")
        result = await self._client.browser.get_window_for_target(
            target_id=session.target_id
        )
        window_id = result.get("windowId", 0)
        bounds = {
            "left": x,
            "top": y,
            "width": width,
            "height": height,
            "windowState": "normal",
        }
        await self._client.browser.set_window_bounds(window_id, bounds)

    async def browser_version(self) -> str:
        """Get the browser version string.

        Returns:
            The browser product/version string.
        """
        if self._client is None:
            raise NavigationError("", "Client not initialized.")
        result = await self._client.browser.get_version()
        return str(result.get("product", ""))

    # ── Emulation ─────────────────────────────────────────

    async def emulate_device(self, device: str) -> None:
        """Emulate a device by preset name.

        Args:
            device: Device preset name (e.g. 'iphone-15').

        Raises:
            ValueError: If the device name is not in DEVICE_PRESETS.
        """
        session = self._require_session()
        preset = DEVICE_PRESETS.get(device)
        if preset is None:
            raise ValueError(f"Unknown device preset: {device}")
        await session.emulation.set_device_metrics_override(
            width=int(preset["width"]),
            height=int(preset["height"]),
            device_scale_factor=float(preset["device_scale_factor"]),
            mobile=bool(preset["mobile"]),
            user_agent=str(preset["user_agent"]),
        )
        if preset.get("touch"):
            await session.emulation.set_touch_emulation_enabled(True)

    async def set_viewport(
        self, width: int, height: int, device_scale_factor: float = 1.0
    ) -> None:
        """Set a custom viewport with given dimensions and scale factor.

        Args:
            width: Viewport width in CSS pixels.
            height: Viewport height in CSS pixels.
            device_scale_factor: Device pixel scale factor.
        """
        session = self._require_session()
        await session.emulation.set_device_metrics_override(
            width=width,
            height=height,
            device_scale_factor=device_scale_factor,
            mobile=False,
        )

    async def set_geolocation(
        self, latitude: float, longitude: float, accuracy: float = 100.0
    ) -> None:
        """Override the geolocation position.

        Args:
            latitude: Latitude in degrees.
            longitude: Longitude in degrees.
            accuracy: Accuracy in meters.
        """
        session = self._require_session()
        await session.emulation.set_geolocation_override(
            latitude=latitude,
            longitude=longitude,
            accuracy=accuracy,
        )

    async def set_timezone(self, timezone: str) -> None:
        """Override the system timezone.

        Args:
            timezone: IANA timezone ID (e.g. 'America/New_York').
        """
        session = self._require_session()
        await session.emulation.set_timezone_override(timezone)

    async def set_dark_mode(self, enabled: bool) -> None:
        """Enable or disable dark mode emulation.

        Args:
            enabled: True to enable dark mode, False to disable.
        """
        session = self._require_session()
        features = [{"name": "prefers-color-scheme", "value": "dark" if enabled else "light"}]
        await session.emulation.set_emulated_media(features=features)

    # ── Input ──────────────────────────────────────────────

    async def _get_box_center(self, selector: str) -> tuple[float, float]:
        """Find an element by selector and return the center of its bounding box."""
        session = self._require_session()
        node_id = await self._find_node(selector)
        box = await session.dom.get_box_model(node_id)
        model = box.get("model", {})
        borders = model.get("border", [])
        if len(borders) < 8:
            raise ElementNotFoundError(selector)
        xs = [borders[0], borders[2], borders[4], borders[6]]
        ys = [borders[1], borders[3], borders[5], borders[7]]
        cx = (min(xs) + max(xs)) / 2
        cy = (min(ys) + max(ys)) / 2
        return cx, cy

    async def _wait_for_element(self, selector: str, timeout_ms: int = 30000) -> None:
        """Wait for an element to exist and be visible in the DOM.

        Polls until the element matches, is attached, and has non-zero size.

        Args:
            selector: CSS selector for the target element.
            timeout_ms: Maximum wait time in milliseconds.

        Raises:
            WaitTimeoutError: If the element is not found within the timeout.
        """
        session = self._require_session()
        escaped = json.dumps(selector)
        js = (
            f"(function(){{var el=document.querySelector('{escaped}');"
            f"if(!el)return false;"
            f"var rect=el.getBoundingClientRect();"
            f"return rect.width>0&&rect.height>0;}})()"
        )
        deadline = time.monotonic() + timeout_ms / 1000
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate(js)
            if result.get("result", {}).get("value") is True:
                return
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("selector", timeout_ms)

    async def _scroll_into_view_if_needed(self, selector: str) -> None:
        """Scroll element into view if it's not visible in the viewport.

        Args:
            selector: CSS selector for the target element.
        """
        session = self._require_session()
        escaped = json.dumps(selector)
        js = (
            f"(function(){{var el=document.querySelector('{escaped}');"
            f"if(!el)return;var rect=el.getBoundingClientRect();"
            f"if(rect.top<0||rect.bottom>window.innerHeight||"
            f"rect.left<0||rect.right>window.innerWidth)"
            f"el.scrollIntoView({{block:'center',behavior:'instant'}});}})()"
        )
        await session.runtime.evaluate(js)

    async def click(
        self,
        selector: str,
        button: str = "left",
        click_count: int = 1,
        auto_wait: bool = True,
    ) -> None:
        """Click an element matching a CSS selector.

        Args:
            selector: CSS selector for the target element.
            button: Mouse button — "left", "right", or "middle".
            click_count: Number of clicks to dispatch.
            auto_wait: If True, wait for element to be visible before clicking.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element(selector)
        await self._scroll_into_view_if_needed(selector)
        x, y = await self._get_box_center(selector)
        btn_map = {"left": "left", "right": "right", "middle": "middle"}
        btn = btn_map.get(button, "left")
        for _ in range(click_count):
            await session.input.dispatch_mouse_event(
                **{"type": "mousePressed"}, x=x, y=y, button=btn, click_count=1
            )
            await session.input.dispatch_mouse_event(
                **{"type": "mouseReleased"}, x=x, y=y, button=btn, click_count=1
            )

    async def type_text(self, selector: str, text: str, delay: int = 0) -> None:
        """Type text into an element, optionally with delay between keystrokes.

        Args:
            selector: CSS selector for the target element.
            text: Text to type character by character.
            delay: Delay between keystrokes in milliseconds.
        """
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.dom.focus(node_id)
        for char in text:
            await session.input.dispatch_key_event(
                **{"type": "char"}, text=char
            )
            if delay > 0:
                await asyncio.sleep(delay / 1000)

    async def fill(
        self, selector: str, value: str, auto_wait: bool = True
    ) -> None:
        """Fill an input element with a value (replaces existing content).

        Args:
            selector: CSS selector for the target element.
            value: Value to set in the input field.
            auto_wait: If True, wait for element to be visible before filling.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element(selector)
        await self._scroll_into_view_if_needed(selector)
        escaped = json.dumps(selector)
        js = (
            f"(function(){{var el=document.querySelector('{escaped}');"
            f"if(!el)return false;el.focus();el.value='{value}';"
            f"el.dispatchEvent(new Event('input',{{bubbles:true}}));"
            f"el.dispatchEvent(new Event('change',{{bubbles:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(selector)

    async def select_option(self, selector: str, value: str) -> None:
        """Select an option in a <select> element by value.

        Args:
            selector: CSS selector for the <select> element.
            value: Option value to select.
        """
        session = self._require_session()
        escaped = json.dumps(selector)
        escaped_val = json.dumps(value)
        js = (
            f"(function(){{var el=document.querySelector('{escaped}');"
            f"if(!el)return false;el.value='{escaped_val}';"
            f"el.dispatchEvent(new Event('change',{{bubbles:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(selector)

    async def hover(self, selector: str, auto_wait: bool = True) -> None:
        """Hover over an element matching a CSS selector.

        Args:
            selector: CSS selector for the target element.
            auto_wait: If True, wait for element to be visible before hovering.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element(selector)
        await self._scroll_into_view_if_needed(selector)
        x, y = await self._get_box_center(selector)
        await session.input.dispatch_mouse_event(
            **{"type": "mouseMoved"}, x=x, y=y
        )

    async def key_press(self, key: str) -> None:
        """Press a keyboard key.

        Args:
            key: Key name (e.g. 'Enter', 'Tab', 'Escape').
        """
        session = self._require_session()
        key_map = {
            "Enter": {"key": "Enter", "code": "Enter", "windows_virtual_key_code": 13},
            "Tab": {"key": "Tab", "code": "Tab", "windows_virtual_key_code": 9},
            "Escape": {"key": "Escape", "code": "Escape", "windows_virtual_key_code": 27},
            "Space": {"key": " ", "code": "Space", "windows_virtual_key_code": 32},
            "Backspace": {"key": "Backspace", "code": "Backspace", "windows_virtual_key_code": 8},
        }
        key_info = key_map.get(key, {"key": key, "code": key})
        await session.input.dispatch_key_event(
            **{"type": "keyDown"}, **key_info
        )
        await session.input.dispatch_key_event(
            **{"type": "keyUp"}, **key_info
        )

    async def drag(self, source: str, target: str) -> None:
        """Drag an element from source selector to target selector.

        Args:
            source: CSS selector for the element to drag.
            target: CSS selector for the drop target.
        """
        session = self._require_session()
        sx, sy = await self._get_box_center(source)
        tx, ty = await self._get_box_center(target)
        await session.input.dispatch_mouse_event(
            **{"type": "mousePressed"}, x=sx, y=sy, button="left", click_count=1
        )
        await session.input.dispatch_mouse_event(
            **{"type": "mouseMoved"}, x=tx, y=ty
        )
        await session.input.dispatch_mouse_event(
            **{"type": "mouseReleased"}, x=tx, y=ty, button="left", click_count=1
        )

    async def tap(self, selector: str) -> None:
        """Tap an element (touch emulation click).

        Args:
            selector: CSS selector for the target element.
        """
        session = self._require_session()
        x, y = await self._get_box_center(selector)
        await session.input.dispatch_touch_event(
            **{"type": "touchStart"}, touch_points=[{"x": x, "y": y}]
        )
        await session.input.dispatch_touch_event(
            **{"type": "touchEnd"}, touch_points=[]
        )

    async def set_files(self, selector: str, files: list[str]) -> None:
        """Set files on a file input element.

        Args:
            selector: CSS selector for the <input type="file"> element.
            files: List of absolute file paths to upload.
        """
        session = self._require_session()
        node_id = await self._find_node(selector)
        await session.send(
            "DOM.setFileInputFiles",
            {"files": files, "nodeId": node_id},
        )

    # ── iframe ─────────────────────────────────────────────

    async def iframe_eval(
        self, iframe_selector: str, expression: str, await_promise: bool = False
    ) -> Any:
        """Evaluate a JavaScript expression inside an iframe.

        Args:
            iframe_selector: CSS selector for the <iframe> element.
            expression: JavaScript expression to evaluate in the iframe context.
            await_promise: Whether to await a returned Promise.

        Returns:
            The evaluation result value.
        """
        session = self._require_session()
        escaped_iframe = json.dumps(iframe_selector)
        escaped_expr = json.dumps(expression)
        js = (
            f"(function(){{var f=document.querySelector('{escaped_iframe}');"
            f"if(!f||!f.contentDocument)return null;"
            f"return (function(){{{escaped_expr}}}).call(f.contentDocument);}})()"
        )
        result = await session.runtime.evaluate(js, await_promise=await_promise)
        return result.get("result", {}).get("value")

    async def _wait_for_element_in_iframe(
        self, iframe_selector: str, selector: str, timeout_ms: int = 30000
    ) -> None:
        """Wait for an element inside an iframe to exist and be visible.

        Args:
            iframe_selector: CSS selector for the <iframe> element.
            selector: CSS selector inside the iframe.
            timeout_ms: Maximum wait time in milliseconds.

        Raises:
            WaitTimeoutError: If the element is not found within the timeout.
        """
        session = self._require_session()
        escaped_iframe = json.dumps(iframe_selector)
        escaped_sel = json.dumps(selector)
        js = (
            f"(function(){{var f=document.querySelector('{escaped_iframe}');"
            f"if(!f||!f.contentDocument)return false;"
            f"var el=f.contentDocument.querySelector('{escaped_sel}');"
            f"if(!el)return false;"
            f"var rect=el.getBoundingClientRect();"
            f"return rect.width>0&&rect.height>0;}})()"
        )
        deadline = time.monotonic() + timeout_ms / 1000
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate(js)
            if result.get("result", {}).get("value") is True:
                return
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("selector", timeout_ms)

    async def iframe_click(
        self, iframe_selector: str, selector: str, auto_wait: bool = True
    ) -> None:
        """Click an element inside an iframe.

        Args:
            iframe_selector: CSS selector for the <iframe> element.
            selector: CSS selector inside the iframe for the target element.
            auto_wait: If True, wait for element to be visible before clicking.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element_in_iframe(iframe_selector, selector)
        escaped_iframe = json.dumps(iframe_selector)
        escaped_sel = json.dumps(selector)
        js = (
            f"(function(){{var f=document.querySelector('{escaped_iframe}');"
            f"if(!f||!f.contentDocument)return false;"
            f"var el=f.contentDocument.querySelector('{escaped_sel}');"
            f"if(!el)return false;"
            f"el.scrollIntoView({{block:'center',behavior:'instant'}});"
            f"el.dispatchEvent(new MouseEvent('click',{{bubbles:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(selector)

    async def iframe_fill(
        self, iframe_selector: str, selector: str, value: str, auto_wait: bool = True
    ) -> None:
        """Fill an input element inside an iframe.

        Args:
            iframe_selector: CSS selector for the <iframe> element.
            selector: CSS selector inside the iframe for the target element.
            value: Value to set in the input field.
            auto_wait: If True, wait for element to be visible before filling.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element_in_iframe(iframe_selector, selector)
        escaped_iframe = json.dumps(iframe_selector)
        escaped_sel = json.dumps(selector)
        escaped_val = json.dumps(value)
        js = (
            f"(function(){{var f=document.querySelector('{escaped_iframe}');"
            f"if(!f||!f.contentDocument)return false;"
            f"var el=f.contentDocument.querySelector('{escaped_sel}');"
            f"if(!el)return false;"
            f"el.focus();el.value='{escaped_val}';"
            f"el.dispatchEvent(new Event('input',{{bubbles:true}}));"
            f"el.dispatchEvent(new Event('change',{{bubbles:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(selector)

    # ── Shadow DOM ──────────────────────────────────────────

    @staticmethod
    def _build_shadow_pierce_js(selectors: list[str]) -> str:
        """Build JS that pierces shadow boundaries via a selector chain.

        Args:
            selectors: List of CSS selectors. selectors[0] in document,
                each subsequent selector in the previous element's shadowRoot.

        Returns:
            JavaScript IIFE that returns the final element or null.
        """
        escaped = [json.dumps(s) for s in selectors]
        parts = [f"var el=document.querySelector('{escaped[0]}')"]
        for sel in escaped[1:]:
            parts.append(
                f"if(!el||!el.shadowRoot)return null;"
                f"el=el.shadowRoot.querySelector('{sel}')"
            )
        parts.append("return el")
        body = ";".join(parts)
        return f"(function(){{{body};}})()"

    async def shadow_eval(
        self, selectors: list[str], expression: str, await_promise: bool = False
    ) -> Any:
        """Evaluate a JavaScript expression inside a shadow DOM tree.

        Args:
            selectors: List of CSS selectors piercing shadow boundaries.
            expression: JavaScript expression to evaluate in the shadow context.
            await_promise: Whether to await a returned Promise.

        Returns:
            The evaluation result value.
        """
        session = self._require_session()
        pierce_js = self._build_shadow_pierce_js(selectors)
        escaped_expr = json.dumps(expression)
        js = (
            f"(function(){{var el=({pierce_js});"
            f"if(!el)return null;"
            f"return (function(){{{escaped_expr}}}).call(el);}})()"
        )
        result = await session.runtime.evaluate(js, await_promise=await_promise)
        return result.get("result", {}).get("value")

    async def _wait_for_element_in_shadow(
        self, selectors: list[str], timeout_ms: int = 30000
    ) -> None:
        """Wait for an element inside a shadow DOM tree to exist and be visible.

        Args:
            selectors: List of CSS selectors piercing shadow boundaries.
            timeout_ms: Maximum wait time in milliseconds.

        Raises:
            WaitTimeoutError: If the element is not found within the timeout.
        """
        session = self._require_session()
        pierce_js = self._build_shadow_pierce_js(selectors)
        js = (
            f"(function(){{var el=({pierce_js});"
            f"if(!el)return false;"
            f"var rect=el.getBoundingClientRect();"
            f"return rect.width>0&&rect.height>0;}})()"
        )
        deadline = time.monotonic() + timeout_ms / 1000
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate(js)
            if result.get("result", {}).get("value") is True:
                return
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("selector", timeout_ms)

    async def shadow_click(
        self, selectors: list[str], auto_wait: bool = True
    ) -> None:
        """Click an element inside a shadow DOM tree.

        Args:
            selectors: List of CSS selectors piercing shadow boundaries.
            auto_wait: If True, wait for element to be visible before clicking.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element_in_shadow(selectors)
        pierce_js = self._build_shadow_pierce_js(selectors)
        js = (
            f"(function(){{var el=({pierce_js});"
            f"if(!el)return false;"
            f"el.scrollIntoView({{block:'center',behavior:'instant'}});"
            f"el.dispatchEvent(new MouseEvent('click',{{bubbles:true,composed:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(" -> ".join(selectors))

    async def shadow_fill(
        self, selectors: list[str], value: str, auto_wait: bool = True
    ) -> None:
        """Fill an input element inside a shadow DOM tree.

        Args:
            selectors: List of CSS selectors piercing shadow boundaries.
            value: Value to set in the input field.
            auto_wait: If True, wait for element to be visible before filling.
        """
        session = self._require_session()
        if auto_wait:
            await self._wait_for_element_in_shadow(selectors)
        pierce_js = self._build_shadow_pierce_js(selectors)
        escaped_val = json.dumps(value)
        js = (
            f"(function(){{var el=({pierce_js});"
            f"if(!el)return false;"
            f"el.focus();el.value='{escaped_val}';"
            f"el.dispatchEvent(new Event('input',{{bubbles:true,composed:true}}));"
            f"el.dispatchEvent(new Event('change',{{bubbles:true,composed:true}}));"
            f"return true;}})()"
        )
        result = await session.runtime.evaluate(js)
        if not result.get("result", {}).get("value"):
            raise ElementNotFoundError(" -> ".join(selectors))

    # ── Network advanced ───────────────────────────────────

    async def block_requests(self, patterns: list[str]) -> None:
        """Block requests matching URL patterns.

        Args:
            patterns: List of glob-style URL patterns to block.
        """
        session = self._require_session()
        await session.network.enable()
        await session.send(
            "Network.setBlockedURLs",
            {"urls": patterns},
        )

    async def throttle_network(self, params: ThrottleParams) -> None:
        """Throttle network conditions.

        Args:
            params: Throttle parameters (offline, latency, throughput).
        """
        session = self._require_session()
        await session.network.enable()
        await session.send(
            "Network.emulateNetworkConditions",
            {
                "offline": params.offline,
                "latency": params.latency_ms,
                "downloadThroughput": params.download_bps,
                "uploadThroughput": params.upload_bps,
            },
        )

    async def set_cache_disabled(self, disabled: bool = True) -> None:
        """Disable or enable the browser cache.

        Args:
            disabled: True to disable cache, False to enable.
        """
        session = self._require_session()
        await session.network.enable()
        await session.network.set_cache_disabled(disabled)

    async def intercept_requests(self, pattern: dict[str, Any]) -> None:
        """Intercept requests matching a pattern dict.

        Args:
            pattern: Fetch.enable pattern dict (urlPattern, resourceType, requestStage).
        """
        session = self._require_session()
        await session.send(
            "Fetch.enable",
            {"patterns": [pattern]},
        )

    async def mock_response(self, url: str, response: dict[str, Any]) -> None:
        """Mock a response for requests matching a URL pattern.

        Uses Fetch.enable to intercept and fulfill requests with a mocked response.

        Args:
            url: URL pattern to intercept.
            response: Response dict with optional keys: status, headers, body.
        """
        session = self._require_session()

        body = response.get("body", "")
        if isinstance(body, (dict, list)):
            body = json.dumps(body)
        body_b64 = base64.b64encode(body.encode("utf-8")).decode("ascii")

        fulfilled: list[bool] = [False]

        async def on_request_paused(event_params: dict[str, Any]) -> None:
            """Handle Fetch.requestPaused and fulfill with the mocked response.

            Args:
                event_params: CDP event parameters with the paused request ID.
            """
            request_id = event_params.get("requestId", "")
            await session.send(
                "Fetch.fulfillRequest",
                {
                    "requestId": request_id,
                    "responseCode": response.get("status", 200),
                    "responseHeaders": [
                        {
                            "name": "Content-Type",
                            "value": response.get("content_type", "application/json"),
                        }
                    ],
                    "body": body_b64,
                },
            )
            fulfilled[0] = True

        session.on("Fetch.requestPaused", on_request_paused)
        await session.send(
            "Fetch.enable",
            {"patterns": [{"urlPattern": url, "requestStage": "Response"}]},
        )

    # ── Network inspection (W3, W6, W7) ───────────────────

    async def get_request_body(self, request_id: str) -> str | None:
        """Get the body of a network request by ID.

        Args:
            request_id: The CDP network request ID.

        Returns:
            The request body as a string, or None if not available.
        """
        session = self._require_session()
        try:
            result = await session.send(
                "Network.getRequestPostData",
                {"requestId": request_id},
            )
            return result.get("postData")
        except Exception:
            return None

    async def get_response_body(self, request_id: str) -> str | None:
        """Get the body of a network response by ID.

        Args:
            request_id: The CDP network request ID.

        Returns:
            The response body as a string, or None if not available.
        """
        session = self._require_session()
        try:
            result = await session.send(
                "Network.getResponseBody",
                {"requestId": request_id},
            )
            return result.get("body")
        except Exception:
            return None

    async def modify_request(
        self,
        pattern: dict[str, Any],
        modifications: dict[str, Any],
    ) -> None:
        """Intercept and modify requests matching a pattern.

        Uses CDP Fetch domain to pause requests and continue with modifications.

        Args:
            pattern: Pattern dict with optional keys: urlPattern, resourceType,
                requestStage.
            modifications: Dict with optional keys: headers, url, method, post_data.
        """
        session = self._require_session()

        async def on_request_paused(event_params: dict[str, Any]) -> None:
            """Handle Fetch.requestPaused and continue with modifications."""
            request_id = event_params.get("requestId", "")
            await session.send(
                "Fetch.continueRequest",
                {
                    "requestId": request_id,
                    "url": modifications.get("url", event_params.get("request", {}).get("url", "")),
                    "method": modifications.get(
                        "method", event_params.get("request", {}).get("method", "GET")
                    ),
                    "headers": modifications.get(
                        "headers", event_params.get("request", {}).get("headers", [])
                    ),
                    "postData": modifications.get("post_data"),
                },
            )

        session.on("Fetch.requestPaused", on_request_paused)
        await session.send("Fetch.enable", {"patterns": [pattern]})

    async def modify_response(
        self,
        pattern: dict[str, Any],
        modifications: dict[str, Any],
    ) -> None:
        """Intercept responses matching a pattern and modify them in-flight.

        Uses CDP Fetch domain to pause responses and fulfill with modifications.

        Args:
            pattern: Pattern dict with optional keys: urlPattern, resourceType,
                requestStage (defaults to "Response").
            modifications: Dict with optional keys: status, headers, body.
        """
        session = self._require_session()

        response_pattern = dict(pattern)
        response_pattern.setdefault("requestStage", "Response")

        body = modifications.get("body", "")
        if isinstance(body, (dict, list)):
            body = json.dumps(body)
        body_b64 = base64.b64encode(body.encode("utf-8")).decode("ascii")

        async def on_request_paused(event_params: dict[str, Any]) -> None:
            """Handle Fetch.requestPaused and fulfill with modified response."""
            request_id = event_params.get("requestId", "")
            response_headers = modifications.get(
                "headers",
                [
                    {
                        "name": "Content-Type",
                        "value": modifications.get("content_type", "application/json"),
                    }
                ],
            )
            await session.send(
                "Fetch.fulfillRequest",
                {
                    "requestId": request_id,
                    "responseCode": modifications.get("status", 200),
                    "responseHeaders": response_headers,
                    "body": body_b64,
                },
            )

        session.on("Fetch.requestPaused", on_request_paused)
        await session.send("Fetch.enable", {"patterns": [response_pattern]})

    async def replay_har(self, har_path: str, url_filter: str = "") -> None:
        """Replay network requests from a HAR file.

        Reads the HAR JSON, iterates entries, and replays each request using
        the browser's fetch API.

        Args:
            har_path: Path to the HAR file.
            url_filter: Optional URL pattern to filter which entries to replay.
        """
        session = self._require_session()
        from pathlib import Path

        content = await asyncio.to_thread(Path(har_path).read_text, encoding="utf-8")
        har_data = json.loads(content)

        entries = har_data.get("log", {}).get("entries", [])
        for entry in entries:
            request = entry.get("request", {})
            url = request.get("url", "")
            if url_filter and url_filter not in url:
                continue

            method = request.get("method", "GET")
            headers = {
                h["name"]: h["value"]
                for h in request.get("headers", [])
                if "name" in h and "value" in h
            }
            post_data = request.get("postData", {}).get("text", "")

            fetch_js = (
                f"fetch({json.dumps(url)}, {{"
                f"method: {json.dumps(method)},"
                f"headers: {json.dumps(headers)},"
                f"body: {json.dumps(post_data) if post_data else 'undefined'}"
                f"}}).then(r => r.status).catch(e => e.message)"
            )
            await session.runtime.evaluate(fetch_js)

    # ── Combined trace (W8) ────────────────────────────────

    async def start_combined_trace(
        self,
        capture_screenshots: bool = True,
        capture_network: bool = True,
        capture_console: bool = True,
    ) -> str:
        """Start a combined trace capturing screenshots, network, and console.

        Returns:
            A trace ID string for later stopping and collecting results.
        """
        session = self._require_session()
        trace_id = f"trace-{int(time.time() * 1000)}"

        state: dict[str, Any] = {
            "trace_events": [],
            "screenshots": [],
            "network": [],
            "console": [],
            "capture_screenshots": capture_screenshots,
            "capture_network": capture_network,
            "capture_console": capture_console,
        }

        if capture_network:
            await session.network.enable()

            def on_network_request(event_params: dict[str, Any]) -> None:
                state["network"].append({
                    "type": "request",
                    "url": event_params.get("request", {}).get("url", ""),
                    "method": event_params.get("request", {}).get("method", ""),
                    "requestId": event_params.get("requestId", ""),
                    "timestamp": event_params.get("timestamp"),
                })

            def on_network_response(event_params: dict[str, Any]) -> None:
                state["network"].append({
                    "type": "response",
                    "url": event_params.get("response", {}).get("url", ""),
                    "status": event_params.get("response", {}).get("status", 0),
                    "requestId": event_params.get("requestId", ""),
                    "timestamp": event_params.get("timestamp"),
                })

            session.on("Network.requestWillBeSent", on_network_request)
            session.on("Network.responseReceived", on_network_response)

        if capture_console:
            await session.runtime.enable()

            def on_console_api(event_params: dict[str, Any]) -> None:
                state["console"].append({
                    "type": event_params.get("type", "log"),
                    "args": event_params.get("args", []),
                    "timestamp": event_params.get("timestamp"),
                })

            session.on("Runtime.consoleAPICalled", on_console_api)

        if capture_screenshots:
            screenshot = await session.page.capture_screenshot()
            if screenshot:
                state["screenshots"].append({
                    "timestamp": time.time(),
                    "data": screenshot,
                })

        await session.send("Tracing.start", {"traceType": "devtools-timeline"})

        self._combined_traces: dict[str, dict[str, Any]] = getattr(
            self, "_combined_traces", {}
        )
        self._combined_traces[trace_id] = state
        return trace_id

    async def stop_combined_trace(self, trace_id: str) -> dict[str, Any]:
        """Stop a combined trace and return collected data.

        Args:
            trace_id: The trace ID returned by start_combined_trace.

        Returns:
            Dict with keys: trace_events, screenshots, network, console.
        """
        session = self._require_session()
        traces: dict[str, dict[str, Any]] = getattr(self, "_combined_traces", {})
        state = traces.get(trace_id)
        if state is None:
            return {"error": f"Unknown trace_id: {trace_id}"}

        trace_events: list[dict[str, Any]] = []

        async def _on_tracing_complete(params: dict[str, Any]) -> None:
            """Handle Tracing.tracingComplete and extract trace events."""
            import io
            import zipfile

            stream_handle = params.get("stream")
            if stream_handle:
                chunks: list[bytes] = []
                while True:
                    resp = await session.send("IO.read", {"handle": stream_handle})
                    data = resp.get("data", "")
                    if not data:
                        break
                    chunks.append(base64.b64decode(data))
                    if not resp.get("base64Encoded", True):
                        break
                raw = b"".join(chunks)
                try:
                    zf = zipfile.ZipFile(io.BytesIO(raw))
                    for name in zf.namelist():
                        content = zf.read(name).decode("utf-8", errors="replace")
                        trace_events.extend(json.loads(content).get("traceEvents", []))
                except (zipfile.BadZipFile, json.JSONDecodeError, KeyError, ValueError):
                    trace_events.append({"raw_size": len(raw)})

        session.on("Tracing.tracingComplete", _on_tracing_complete)
        await session.send("Tracing.end", {})

        if state["capture_screenshots"]:
            screenshot = await session.page.capture_screenshot()
            if screenshot:
                state["screenshots"].append({
                    "timestamp": time.time(),
                    "data": screenshot,
                })

        await asyncio.sleep(0.5)

        result: dict[str, Any] = {
            "trace_events": trace_events,
            "screenshots": state["screenshots"],
            "network": state["network"],
            "console": state["console"],
        }
        del traces[trace_id]
        return result

    # ── axe-core audit (W9) ────────────────────────────────

    async def axe_audit(self) -> dict[str, Any]:
        """Run axe-core accessibility audit on the current page.

        Injects axe-core JS via Runtime.evaluate and returns the results.

        Returns:
            Dict with violations, passes, incomplete, and inapplicable lists.
        """
        session = self._require_session()

        axe_js = (
            "if (typeof axe === 'undefined') { "
            "  import('https://unpkg.com/axe-core@4.9.1/axe.min.js')"
            "    .then(m => { window.axe = m.default || m; }); "
            "} "
            "await new Promise(r => setTimeout(r, 2000)); "
            "if (typeof axe === 'undefined') { "
            "  const s = document.createElement('script'); "
            "  s.src = 'https://unpkg.com/axe-core@4.9.1/axe.min.js'; "
            "  document.head.appendChild(s); "
            "  await new Promise(r => s.onload = r); "
            "} "
            "await axe.run(document, { "
            "  resultTypes: ['violations', 'passes', 'incomplete', 'inapplicable'] "
            "})"
        )
        result = await session.runtime.evaluate(axe_js, await_promise=True)
        value = result.get("result", {}).get("value")
        if isinstance(value, dict):
            return value
        if isinstance(value, str):
            try:
                return dict(json.loads(value))
            except (json.JSONDecodeError, TypeError):
                pass
        return {"error": "axe-core audit failed", "raw": dict(result)}

    # ── Event subscription (W11) ───────────────────────────

    async def subscribe_events(
        self,
        event_types: list[str],
        callback: Any,
    ) -> str:
        """Subscribe to real-time browser events.

        Args:
            event_types: List of event types to subscribe to.
            callback: Callable that receives event dicts.

        Returns:
            A subscription ID for later unsubscription.
        """
        session = self._require_session()
        sub_id = f"sub-{int(time.time() * 1000)}"

        if not hasattr(self, "_subscriptions"):
            self._subscriptions: dict[str, dict[str, Any]] = {}

        handlers: dict[str, Any] = {}

        event_map = {
            "console": ("Runtime.consoleAPICalled", "console"),
            "network_request": ("Network.requestWillBeSent", "network_request"),
            "network_response": ("Network.responseReceived", "network_response"),
            "dialog": ("Page.javascriptDialogOpening", "dialog"),
            "navigation": ("Page.frameNavigated", "navigation"),
        }

        for evt_type in event_types:
            if evt_type in event_map:
                cdp_event, label = event_map[evt_type]

                def make_handler(lbl: str) -> Any:
                    def _handler(params: dict[str, Any]) -> None:
                        callback({"type": lbl, "data": params})
                    return _handler

                handler = make_handler(label)
                session.on(cdp_event, handler)
                handlers[cdp_event] = handler

                if evt_type in ("network_request", "network_response"):
                    asyncio.ensure_future(session.network.enable())
                elif evt_type == "console":
                    asyncio.ensure_future(session.runtime.enable())

        self._subscriptions[sub_id] = handlers
        return sub_id

    async def unsubscribe_events(self, subscription_id: str) -> None:
        """Unsubscribe from events by subscription ID.

        Args:
            subscription_id: The ID returned by subscribe_events.
        """
        session = self._require_session()
        subs: dict[str, dict[str, Any]] = getattr(self, "_subscriptions", {})
        handlers = subs.pop(subscription_id, {})
        for cdp_event, handler in handlers.items():
            off = getattr(session, "off", None)
            if off is not None:
                off(cdp_event, handler)

    # ── Accessibility ──────────────────────────────────────

    async def a11y_tree(self) -> dict[str, Any]:
        """Get the full accessibility tree of the current page.

        Returns:
            Dict with the accessibility tree nodes.
        """
        session = self._require_session()
        result = await session.send("Accessibility.getFullAXTree")
        return dict(result)

    async def a11y_node(self, node_id: str) -> dict[str, Any]:
        """Get a specific accessibility node by its node ID.

        Args:
            node_id: The accessibility node ID.

        Returns:
            Dict with the node's accessibility properties.
        """
        session = self._require_session()
        result = await session.send("Accessibility.getFullAXTree")
        nodes = result.get("nodes", [])
        for node in nodes:
            if node.get("nodeId") == node_id:
                return dict(node)
        return {}

    async def a11y_ancestors(self, node_id: str) -> list[dict[str, Any]]:
        """Get ancestor nodes of an accessibility node.

        Args:
            node_id: The accessibility node ID.

        Returns:
            List of ancestor node dicts.
        """
        session = self._require_session()
        result = await session.send("Accessibility.getFullAXTree")
        nodes = result.get("nodes", [])

        # Build a map of nodeId -> node for O(1) lookup
        node_map = {node.get("nodeId"): node for node in nodes}

        # Find the target node
        target = node_map.get(node_id)
        if not target:
            return []

        # Traverse up via parentId to find ancestors
        ancestors: list[dict[str, Any]] = []
        current_parent_id = target.get("parentId")
        while current_parent_id:
            parent = node_map.get(current_parent_id)
            if parent:
                ancestors.append(dict(parent))
                current_parent_id = parent.get("parentId")
            else:
                break

        return ancestors

    # ── Downloads ──────────────────────────────────────────

    async def intercept_download(self, pattern: str = ".*") -> bytes:
        """Intercept a file download matching a URL pattern and return bytes.

        Args:
            pattern: URL pattern to match downloads (regex, default matches all).

        Returns:
            Downloaded file bytes.
        """
        session = self._require_session()
        import tempfile

        download_dir = tempfile.mkdtemp()
        await session.send(
            "Page.setDownloadBehavior",
            {"behavior": "allow", "downloadPath": download_dir},
        )

        await asyncio.sleep(2)

        def _list_files() -> list[Path]:
            return list(Path(download_dir).iterdir())

        for fpath in await asyncio.to_thread(_list_files):
            if await asyncio.to_thread(Path(fpath).is_file):
                return await asyncio.to_thread(Path(fpath).read_bytes)

        return b""

    # ── Dialogs ────────────────────────────────────────────

    async def dialog_accept(self, prompt_text: str | None = None) -> None:
        """Accept a JavaScript dialog (alert, confirm, prompt).

        Args:
            prompt_text: Text to enter in a prompt dialog (optional).
        """
        session = self._require_session()
        await session.send(
            "Page.handleJavaScriptDialog",
            {"accept": True, "promptText": prompt_text or ""},
        )

    async def dialog_dismiss(self) -> None:
        """Dismiss a JavaScript dialog."""
        session = self._require_session()
        await session.send(
            "Page.handleJavaScriptDialog",
            {"accept": False},
        )

    # ── Permissions ────────────────────────────────────────

    async def grant_permission(self, permission: str) -> None:
        """Grant a browser permission.

        Args:
            permission: Permission name (e.g. 'geolocation', 'notifications').
        """
        session = self._require_session()
        await session.send(
            "Browser.grantPermissions",
            {"permissions": [permission]},
        )

    async def reset_permissions(self) -> None:
        """Reset all granted permissions."""
        session = self._require_session()
        await session.send("Browser.resetPermissions", {})

    # ── Security ───────────────────────────────────────────

    async def get_security_state(self) -> dict[str, Any]:
        """Get the current security state of the page.

        Returns:
            Dict with security state info (secure, explanations, etc.).
        """
        session = self._require_session()
        await session.send("Security.enable")
        # Listen for security state change event
        state = await session.send("Security.getVisibleSecurityState")
        return dict(state) if state else {}

    async def ignore_cert_errors(self, ignore: bool = True) -> None:
        """Enable or disable ignoring of certificate errors.

        Args:
            ignore: True to ignore cert errors, False to enforce.
        """
        session = self._require_session()
        await session.send(
            "Security.setIgnoreCertificateErrors",
            {"ignore": ignore},
        )

    # ── Emulation advanced ─────────────────────────────────

    async def set_locale(self, locale: str) -> None:
        """Override the browser locale.

        Args:
            locale: Locale string (e.g. 'en-US', 'fr-FR').
        """
        session = self._require_session()
        await session.send(
            "Emulation.setLocaleOverride",
            {"locale": locale},
        )

    async def set_cpu_throttle(self, rate: float) -> None:
        """Throttle CPU performance by a rate multiplier.

        Args:
            rate: Throttle rate (e.g. 4 = 4x slower than normal).
        """
        session = self._require_session()
        await session.send(
            "Emulation.setCPUThrottlingRate",
            {"rate": rate},
        )

    async def set_touch_emulation(self, enabled: bool) -> None:
        """Enable or disable touch emulation.

        Args:
            enabled: True to enable touch emulation, False to disable.
        """
        session = self._require_session()
        await session.emulation.set_touch_emulation_enabled(enabled)

    async def set_sensors(self, sensors: SensorParams) -> None:
        """Override sensor values.

        Args:
            sensors: Sensor parameters with type and values.
        """
        session = self._require_session()
        if sensors.type == "device-orientation":
            await session.send(
                "DeviceOrientation.setDeviceOrientationOverride",
                {
                    "alpha": sensors.values.get("alpha", 0),
                    "beta": sensors.values.get("beta", 0),
                    "gamma": sensors.values.get("gamma", 0),
                },
            )
        elif sensors.type == "geolocation":
            await session.emulation.set_geolocation_override(
                latitude=sensors.values.get("latitude", 0),
                longitude=sensors.values.get("longitude", 0),
                accuracy=sensors.values.get("accuracy", 100),
            )

    # ── Performance ───────────────────────────────────────

    async def perf_metrics(self) -> dict[str, Any]:
        """Get current performance metrics from the page.

        Returns:
            Dict mapping metric names to values (e.g. Timestamp, Documents,
            Frames, JSEventListeners, JSHeapUsedSize, etc.).
        """
        session = self._require_session()
        await session.send("Performance.enable", {})
        result = await session.send("Performance.getMetrics", {})
        metrics: dict[str, Any] = {}
        for m in result.get("metrics", []):
            metrics[m["name"]] = m["value"]
        return metrics

    async def perf_trace(self, duration_ms: int = 3000) -> dict[str, Any]:
        """Capture a performance trace for the given duration.

        Args:
            duration_ms: Trace duration in milliseconds.

        Returns:
            Dict containing trace events collected during the capture period.
        """
        session = self._require_session()
        trace_events: list[dict[str, Any]] = []

        async def _on_tracing_complete(params: dict[str, Any]) -> None:
            """Handle Tracing.tracingComplete and extract trace events from the stream.

            Args:
                params: CDP event parameters containing the trace data stream handle.
            """
            import io
            import zipfile

            stream_handle = params.get("stream")
            if stream_handle:
                chunks: list[bytes] = []
                while True:
                    resp = await session.send(
                        "IO.read",
                        {"handle": stream_handle},
                    )
                    data = resp.get("data", "")
                    if not data:
                        break
                    chunks.append(base64.b64decode(data))
                    if not resp.get("base64Encoded", True):
                        break
                raw = b"".join(chunks)
                try:
                    zf = zipfile.ZipFile(io.BytesIO(raw))
                    for name in zf.namelist():
                        content = zf.read(name).decode("utf-8", errors="replace")
                        trace_events.extend(json.loads(content).get("traceEvents", []))
                except (zipfile.BadZipFile, json.JSONDecodeError, KeyError, ValueError):
                    trace_events.append({"raw_size": len(raw)})
            else:
                trace_events.append({"error": "No stream handle in tracingComplete"})

        session.on("Tracing.tracingComplete", _on_tracing_complete)
        await session.send(
            "Tracing.start",
            {"traceType": "devtools-timeline"},
        )
        await asyncio.sleep(duration_ms / 1000)
        await session.send("Tracing.end", {})
        return {"traceEvents": trace_events}

    async def perf_profile(self, duration_ms: int = 3000) -> dict[str, Any]:
        """Capture a CPU profile for the given duration.

        Args:
            duration_ms: Profile duration in milliseconds.

        Returns:
            Dict containing CPU profile data (nodes, samples, timeDeltas, etc.).
        """
        session = self._require_session()
        await session.send("Profiler.enable", {})
        await session.send("Profiler.start", {})
        await asyncio.sleep(duration_ms / 1000)
        result = await session.send("Profiler.stop", {})
        profile = result.get("profile", result)
        return dict(profile) if profile else {}

    async def perf_heap_snapshot(self) -> dict[str, Any]:
        """Capture a heap snapshot and return it as a dict.

        Returns:
            Dict containing heap snapshot data (nodes, edges, etc.).
        """
        session = self._require_session()
        await session.send("HeapProfiler.enable", {})
        result = await session.send(
            "HeapProfiler.takeHeapSnapshot",
            {"reportProgress": False},
        )
        return dict(result) if result else {"snapshot": "taken"}

    async def perf_coverage(self) -> dict[str, Any]:
        """Get JavaScript code coverage for the current page.

        Returns:
            Dict with 'result' key containing a list of script coverage entries.
        """
        session = self._require_session()
        await session.send("Profiler.enable", {})
        await session.send(
            "Profiler.startPreciseCoverage",
            {"callCount": True, "detailed": True},
        )
        result = await session.send("Profiler.takePreciseCoverage", {})
        return dict(result) if result else {}

    async def perf_css_coverage(self) -> dict[str, Any]:
        """Get CSS rule usage coverage for the current page.

        Returns:
            Dict with 'result' key containing a list of CSS coverage entries.
        """
        session = self._require_session()
        await session.dom.enable()
        await session.send("CSS.enable", {})
        await session.send("CSS.startRuleUsageTracking", {})
        await asyncio.sleep(1)
        result = await session.send("CSS.stopRuleUsageTracking", {})
        return dict(result) if result else {}

    # ── CSS ────────────────────────────────────────────────

    async def css_get_styles(self, selector: str) -> dict[str, Any]:
        """Get inline and computed styles for an element by CSS selector.

        Args:
            selector: CSS selector for the target element.

        Returns:
            Dict containing inlineStyles and computedStyles.
        """
        session = self._require_session()
        await session.dom.enable()
        await session.send("CSS.enable")
        node_id = await self._find_node(selector)
        try:
            inline = await session.send("CSS.getInlineStyles", {"nodeId": node_id})
        except Exception:
            escaped = json.dumps(selector)
            inline = await session.runtime.evaluate(
                expression=(
                    "(() => {const el = document.querySelector('"
                    + escaped
                    + "'); const s = getComputedStyle(el); "
                    + "const result = {}; for (let i = 0; i < s.length; i++) "
                    + "{result[s[i]] = s.getPropertyValue(s[i]);} return result;})()"
                ),
                return_by_value=True,
            )
            inline = inline.get("result", {}).get("value", {})
        try:
            computed = await session.send(
                "CSS.getComputedStyleForNode", {"nodeId": node_id}
            )
        except Exception:
            escaped = json.dumps(selector)
            computed = await session.runtime.evaluate(
                expression=(
                    "(() => {const el = document.querySelector('"
                    + escaped
                    + "'); const s = getComputedStyle(el); "
                    + "const result = []; for (let i = 0; i < s.length; i++) "
                    + "{result.push({name: s[i], value: s.getPropertyValue(s[i])});} "
                    + "return result;})()"
                ),
                return_by_value=True,
            )
            computed = computed.get("result", {}).get("value", {})
        return {"inlineStyles": inline, "computedStyles": computed}

    async def css_get_stylesheets(self) -> list[dict[str, Any]]:
        """List all stylesheets in the current page.

        Returns:
            List of stylesheet info dicts.
        """
        session = self._require_session()
        await session.dom.enable()
        await session.send("CSS.enable")
        try:
            result = await session.send("CSS.getLayoutTreeAndStyles", {})
            stylesheets = result.get("stylesheets", [])
            return [dict(s) for s in stylesheets] if stylesheets else []
        except Exception:
            js = (
                "Array.from(document.styleSheets).map((s, i) => ({"
                "styleSheetId: String(i), "
                "sourceURL: s.href || '', "
                "disabled: s.disabled, "
                "isInline: !s.href}))"
            )
            result = await session.runtime.evaluate(
                expression=js, return_by_value=True
            )
            value = result.get("result", {}).get("value", [])
            return [dict(v) for v in value] if value else []

    async def css_get_rules(self, stylesheet_id: str) -> list[dict[str, Any]]:
        """Get CSS rules from a specific stylesheet.

        Args:
            stylesheet_id: The styleSheetId from css_get_stylesheets.

        Returns:
            List of CSS rule dicts.
        """
        session = self._require_session()
        await session.send("CSS.enable", {})
        result = await session.send(
            "CSS.getStyleSheetText", {"styleSheetId": stylesheet_id}
        )
        text = result.get("text", "")
        rules: list[dict[str, Any]] = []
        import re

        for match in re.finditer(r"([^{}]+)\{([^}]*)\}", text):
            selector_text = match.group(1).strip()
            body = match.group(2).strip()
            rules.append({"selectorText": selector_text, "cssText": body})
        return rules

    async def css_get_computed(self, selector: str) -> dict[str, Any]:
        """Get computed styles for an element by CSS selector.

        Args:
            selector: CSS selector for the target element.

        Returns:
            Dict mapping CSS property names to computed values.
        """
        session = self._require_session()
        await session.send("DOM.enable", {})
        await session.send("CSS.enable", {})
        node_id = await self._find_node(selector)
        resolved = await session.send(
            "DOM.resolveNode", {"nodeId": node_id}
        )
        object_id = resolved.get("object", {}).get("objectId", "")
        if not object_id:
            raise ElementNotFoundError(selector)
        result = await session.send(
            "CSS.getComputedStyleForNode", {"nodeId": node_id}
        )
        computed: dict[str, Any] = {}
        for prop in result.get("computedStyle", []):
            computed[prop.get("name", "")] = prop.get("value", "")
        return computed

    # ── Debugging ──────────────────────────────────────────

    async def debug_set_breakpoint(
        self, url: str, line: int, condition: str | None = None
    ) -> str:
        """Set a breakpoint by URL and line number.

        Args:
            url: URL of the script to set the breakpoint in.
            line: Line number (0-based) for the breakpoint.
            condition: Optional condition expression.

        Returns:
            The breakpoint ID string.
        """
        session = self._require_session()
        await session.send("Debugger.enable", {})
        params: dict[str, Any] = {"url": url, "lineNumber": line}
        if condition:
            params["condition"] = condition
        result = await session.send(
            "Debugger.setBreakpointByUrl", params
        )
        return str(result.get("breakpointId", ""))

    async def debug_set_breakpoint_function(self, function_name: str) -> str:
        """Set a breakpoint by function name.

        Args:
            function_name: Name of the function to break on.

        Returns:
            The breakpoint ID string.
        """
        session = self._require_session()
        await session.send("Debugger.enable", {})
        result = await session.send(
            "Debugger.setBreakpointOnFunctionCall",
            {"functionName": function_name},
        )
        return str(result.get("breakpointId", ""))

    async def debug_remove_breakpoint(self, breakpoint_id: str) -> None:
        """Remove a breakpoint by ID.

        Args:
            breakpoint_id: The breakpoint ID returned from set_breakpoint.
        """
        session = self._require_session()
        await session.send(
            "Debugger.removeBreakpoint", {"breakpointId": breakpoint_id}
        )

    async def debug_step_over(self) -> None:
        """Step over the current statement in the debugger."""
        session = self._require_session()
        await session.debugger.enable()
        await session.debugger.step_over()

    async def debug_step_into(self) -> None:
        """Step into the current function call in the debugger."""
        session = self._require_session()
        await session.debugger.enable()
        await session.debugger.step_into()

    async def debug_step_out(self) -> None:
        """Step out of the current function in the debugger."""
        session = self._require_session()
        await session.debugger.enable()
        await session.debugger.step_out()

    async def debug_pause(self) -> None:
        """Pause JavaScript execution."""
        session = self._require_session()
        await session.debugger.enable()
        paused_event = asyncio.Event()
        session.on("Debugger.paused", lambda _: paused_event.set())
        await session.debugger.pause()
        with contextlib.suppress(TimeoutError):
            await asyncio.wait_for(paused_event.wait(), timeout=5.0)

    async def debug_resume(self) -> None:
        """Resume JavaScript execution after a pause."""
        session = self._require_session()
        await session.debugger.enable()
        await session.debugger.resume()

    async def debug_get_listeners(self, selector: str) -> list[dict[str, Any]]:
        """Get event listeners attached to an element by CSS selector.

        Args:
            selector: CSS selector for the target element.

        Returns:
            List of listener dicts (type, useCapture, passive, etc.).
        """
        session = self._require_session()
        node_id = await self._find_node(selector)
        resolved = await session.send(
            "DOM.resolveNode", {"nodeId": node_id}
        )
        object_id = resolved.get("object", {}).get("objectId", "")
        if not object_id:
            raise ElementNotFoundError(selector)
        result = await session.send(
            "DOMDebugger.getEventListeners", {"objectId": object_id}
        )
        listeners: list[dict[str, Any]] = []
        for listener in result.get("listeners", []):
            listeners.append(dict(listener))
        return listeners

    # ── DOM Snapshot ───────────────────────────────────────

    async def dom_snapshot(self) -> dict[str, Any]:
        """Capture a DOM snapshot of the current page.

        Returns:
            Dict containing the raw DOM snapshot (documents, strings, etc.).
        """
        session = self._require_session()
        result = await session.send(
            "DOMSnapshot.captureSnapshot",
            {"computedStyles": [], "includePaintOrder": True, "includeDOMRects": False},
        )
        return dict(result) if result else {}

    # ── Overlay ────────────────────────────────────────────

    async def overlay_highlight(
        self, selector: str, color: str = "rgba(255,0,0,0.5)"
    ) -> None:
        """Highlight an element with a colored overlay.

        Args:
            selector: CSS selector for the element to highlight.
            color: RGBA color string for the highlight overlay.
        """
        session = self._require_session()
        await session.dom.enable()
        await session.overlay.enable()
        node_id = await self._find_node(selector)
        highlight_config: dict[str, Any] = {
            "showInfo": True,
            "contentColor": {"r": 255, "g": 0, "b": 0, "a": 0.5},
            "contentOutlineColor": {"r": 0, "g": 0, "b": 0, "a": 0},
            "borderColor": {"r": 0, "g": 0, "b": 0, "a": 0},
            "paddingColor": {"r": 0, "g": 0, "b": 0, "a": 0},
            "marginColor": {"r": 0, "g": 0, "b": 0, "a": 0},
        }
        await session.overlay.highlight_node(
            highlight_config=highlight_config, node_id=node_id,
        )

    async def overlay_clear(self) -> None:
        """Clear all highlight overlays from the page."""
        session = self._require_session()
        await session.overlay.hide_highlight()

    # ── Storage ────────────────────────────────────────────

    def _get_origin(self) -> str:
        """Extract the security origin from the current page URL."""
        if self._current_url:
            from urllib.parse import urlparse

            parsed = urlparse(self._current_url)
            return f"{parsed.scheme}://{parsed.netloc}"
        return ""

    async def _get_storage_id(self, storage_type: str) -> dict[str, Any]:
        """Get a DOMStorage.StorageId with the current page's security origin."""
        if storage_type not in ("local", "session"):
            raise NavigationError(
                "", f"Invalid storage_type: {storage_type}. Must be 'local' or 'session'."
            )
        return {
            "securityOrigin": self._get_origin(),
            "isLocalStorage": storage_type == "local",
        }

    async def storage_get(self, key: str, storage_type: str = "local") -> str:
        """Get a value from DOM storage (local or session).

        Args:
            key: The storage key to retrieve.
            storage_type: "local" or "session".

        Returns:
            The stored value as a string, or empty string if not found.
        """
        session = self._require_session()
        await session.send("DOMStorage.enable", {})
        storage_id = await self._get_storage_id(storage_type)
        result = await session.send(
            "DOMStorage.getDOMStorageItems", {"storageId": storage_id}
        )
        for entry in result.get("entries", []):
            if len(entry) >= 2 and entry[0] == key:
                return str(entry[1])
        return ""

    async def storage_set(
        self, key: str, value: str, storage_type: str = "local"
    ) -> None:
        """Set a value in DOM storage (local or session).

        Args:
            key: The storage key.
            value: The value to store.
            storage_type: "local" or "session".
        """
        session = self._require_session()
        await session.send("DOMStorage.enable", {})
        storage_id = await self._get_storage_id(storage_type)
        await session.send(
            "DOMStorage.setDOMStorageItem",
            {"storageId": storage_id, "key": key, "value": value},
        )

    async def storage_clear(self, storage_type: str = "local") -> None:
        """Clear all entries in DOM storage.

        Args:
            storage_type: "local" or "session".
        """
        session = self._require_session()
        origin = self._get_origin()
        storage_types = "local_storage" if storage_type == "local" else "session_storage"
        await session.storage.clear_data_for_origin(
            origin=origin, storage_types=storage_types,
        )

    async def storage_list(self, storage_type: str = "local") -> dict[str, str]:
        """List all key-value pairs in DOM storage.

        Args:
            storage_type: "local" or "session".

        Returns:
            Dict mapping keys to values.
        """
        session = self._require_session()
        await session.send("DOMStorage.enable", {})
        storage_id = await self._get_storage_id(storage_type)
        result = await session.send(
            "DOMStorage.getDOMStorageItems", {"storageId": storage_id}
        )
        items: dict[str, str] = {}
        for entry in result.get("entries", []):
            if len(entry) >= 2:
                items[str(entry[0])] = str(entry[1])
        return items

    async def cache_storage_list(self) -> list[str]:
        """List all Cache Storage cache names.

        Returns:
            List of cache names.
        """
        session = self._require_session()
        result = await session.send(
            "CacheStorage.requestCacheNames",
            {"securityOrigin": self._get_origin()},
        )
        caches: list[str] = []
        for cache in result.get("caches", []):
            name = cache.get("cacheName", "")
            if name:
                caches.append(str(name))
        return caches

    async def cache_storage_entries(self, cache_name: str) -> list[dict[str, Any]]:
        """List entries in a Cache Storage cache.

        Args:
            cache_name: Name of the cache to inspect.

        Returns:
            List of cache entry dicts (url, status, etc.).
        """
        session = self._require_session()

        # First, get the actual cacheId for the given cache_name
        caches_result = await session.send(
            "CacheStorage.requestCacheNames",
            {"securityOrigin": self._get_origin()},
        )

        # Find the cacheId for the requested cache_name
        cache_id = None
        for cache in caches_result.get("caches", []):
            if cache.get("cacheName") == cache_name:
                cache_id = cache.get("cacheId")
                break

        if not cache_id:
            return []

        result = await session.send(
            "CacheStorage.requestEntries",
            {"cacheId": cache_id, "skipCount": 0, "pageSize": 1000},
        )
        entries: list[dict[str, Any]] = []
        for entry in result.get("cacheDataEntries", []):
            entries.append(dict(entry))
        return entries

    async def cache_storage_delete(self, cache_name: str) -> None:
        """Delete a Cache Storage cache.

        Args:
            cache_name: Name of the cache to delete.
        """
        session = self._require_session()

        # First, get the actual cacheId for the given cache_name
        caches_result = await session.send(
            "CacheStorage.requestCacheNames",
            {"securityOrigin": self._get_origin()},
        )

        # Find the cacheId for the requested cache_name
        cache_id = None
        for cache in caches_result.get("caches", []):
            if cache.get("cacheName") == cache_name:
                cache_id = cache.get("cacheId")
                break

        if cache_id:
            await session.send(
                "CacheStorage.deleteCache",
                {"cacheId": cache_id},
            )

    async def indexeddb_list(self) -> list[dict[str, Any]]:
        """List all IndexedDB databases.

        Returns:
            List of database info dicts (name, version, etc.).
        """
        session = self._require_session()
        result = await session.send(
            "IndexedDB.requestDatabaseNames",
            {"securityOrigin": self._get_origin()},
        )
        databases: list[dict[str, Any]] = []
        for name in result.get("databaseNames", []):
            databases.append({"name": str(name)})
        return databases

    async def indexeddb_get_data(
        self, database: str, store: str, key: str = ""
    ) -> Any:
        """Get data from an IndexedDB object store.

        Args:
            database: Database name.
            store: Object store name.
            key: Optional key to retrieve a specific entry. If empty, returns all.

        Returns:
            The stored data, or list of all entries if key is empty.
        """
        session = self._require_session()
        result = await session.send(
            "IndexedDB.requestObjectStoreData",
            {
                "securityOrigin": self._get_origin(),
                "databaseName": database,
                "objectStoreName": store,
                "indexName": "",
                "skipCount": 0,
                "pageSize": 1000,
                "keyRange": None,
            },
        )
        entries: list[dict[str, Any]] = []
        for entry in result.get("objectStoreDataEntries", []):
            entries.append(dict(entry))
        if key:
            for entry in entries:
                if str(entry.get("key", "")) == key:
                    return entry
            return None
        return entries

    async def indexeddb_clear(self, database: str, store: str) -> None:
        """Clear all entries in an IndexedDB object store.

        Args:
            database: Database name.
            store: Object store name.
        """
        session = self._require_session()
        await session.send(
            "IndexedDB.clearObjectStore",
            {
                "securityOrigin": self._get_origin(),
                "databaseName": database,
                "objectStoreName": store,
            },
        )

    # ── Service Workers ────────────────────────────────────

    async def sw_list(self) -> list[dict[str, Any]]:
        """List registered service workers.

        Returns:
            List of service worker target dicts.
        """
        session = self._require_session()
        await session.send("ServiceWorker.enable", {})
        result = await session.send("Target.getTargets", {})
        registrations: list[dict[str, Any]] = []
        for target in result.get("targetInfos", []):
            if target.get("type") == "service_worker":
                registrations.append(dict(target))
        return registrations

    async def sw_unregister(self, registration_id: str) -> None:
        """Unregister a service worker by registration ID.

        Args:
            registration_id: The service worker registration ID.
        """
        session = self._require_session()
        await session.send("ServiceWorker.enable", {})
        await session.send(
            "ServiceWorker.unregister", {"registrationId": registration_id}
        )

    async def sw_update(self, registration_id: str) -> None:
        """Trigger an update for a service worker registration.

        Args:
            registration_id: The service worker registration ID.
        """
        session = self._require_session()
        await session.send("ServiceWorker.enable", {})
        await session.send(
            "ServiceWorker.updateRegistration", {"registrationId": registration_id}
        )

    # ── Animations ─────────────────────────────────────────

    async def animation_list(self) -> list[dict[str, Any]]:
        """List all active animations on the page.

        Returns:
            List of animation dicts (id, name, state, etc.).
        """
        session = self._require_session()
        await session.animation.enable()
        result = await session.runtime.evaluate(
            expression=(
                "Array.from(document.getAnimations()).map(a => "
                "({id: a.id, name: a.animationName, "
                "playState: a.playState, duration: a.effect?.timing?.duration || 0}))"
            ),
            return_by_value=True,
        )
        value = result.get("result", {}).get("value", [])
        return [dict(a) for a in value] if isinstance(value, list) else []

    async def animation_pause(self, animation_id: str) -> None:
        """Pause an animation by ID.

        Args:
            animation_id: The animation ID to pause.
        """
        session = self._require_session()
        await session.send("Animation.enable", {})
        await session.send(
            "Animation.setPaused", {"animations": [animation_id], "paused": True}
        )

    async def animation_play(self, animation_id: str) -> None:
        """Play/resume an animation by ID.

        Args:
            animation_id: The animation ID to play.
        """
        session = self._require_session()
        await session.send("Animation.enable", {})
        await session.send(
            "Animation.setPaused", {"animations": [animation_id], "paused": False}
        )

    async def animation_seek(self, animation_id: str, time_ms: int) -> None:
        """Seek an animation to a specific time.

        Args:
            animation_id: The animation ID to seek.
            time_ms: Target time in milliseconds.
        """
        session = self._require_session()
        await session.send("Animation.enable", {})
        await session.send(
            "Animation.seekTo",
            {"animations": [animation_id], "currentTime": time_ms},
        )

    # ── WebAuthn (experimental) ───────────────────────────

    async def webauthn_add_virtual_authenticator(
        self, protocol: str, transport: str
    ) -> str:
        """Add a virtual authenticator via CDP WebAuthn domain."""
        session = self._require_session()
        await session.web_authn.enable()
        result = await session.web_authn.add_virtual_authenticator(
            options={"protocol": protocol, "transport": transport},
        )
        return str(result.get("authenticatorId", ""))

    async def webauthn_remove_authenticator(self, authenticator_id: str) -> None:
        """Remove a virtual authenticator via CDP WebAuthn domain."""
        session = self._require_session()
        await session.web_authn.enable()
        await session.web_authn.remove_virtual_authenticator(
            authenticator_id=authenticator_id,
        )

    async def webauthn_add_credential(
        self, authenticator_id: str, credential: dict[str, Any]
    ) -> None:
        """Add a credential to a virtual authenticator via CDP WebAuthn domain."""
        session = self._require_session()
        await session.web_authn.enable()
        await session.web_authn.add_credential(
            authenticator_id=authenticator_id, credential=credential,
        )

    async def webauthn_get_credentials(
        self, authenticator_id: str
    ) -> list[dict[str, Any]]:
        """Get credentials from a virtual authenticator via CDP WebAuthn domain."""
        session = self._require_session()
        await session.web_authn.enable()
        result = await session.web_authn.get_credentials(
            authenticator_id=authenticator_id,
        )
        return list(result.get("credentials", []))

    # ── WebAudio (experimental) ────────────────────────────

    async def webaudio_get_contexts(self) -> list[dict[str, Any]]:
        """Get all WebAudio contexts via CDP WebAudio domain."""
        session = self._require_session()
        await session.send("WebAudio.enable", {})
        contexts: list[dict[str, Any]] = []
        try:
            event = await asyncio.wait_for(
                session.wait_for_event("WebAudio.contextCreated"),
                timeout=1.0,
            )
            contexts.append(dict(event.get("context", event)))
        except TimeoutError:
            pass
        return contexts

    async def webaudio_get_context(self, context_id: str) -> dict[str, Any]:
        """Get a specific WebAudio context by ID via CDP WebAudio domain."""
        contexts = await self.webaudio_get_contexts()
        for ctx in contexts:
            if ctx.get("contextId") == context_id:
                return dict(ctx)
        return {}

    # ── Media (experimental) ───────────────────────────────

    async def media_get_players(self) -> list[dict[str, Any]]:
        """Get all media players via CDP Media domain."""
        session = self._require_session()
        await session.send("Media.enable", {})
        result = await session.runtime.evaluate(
            expression=(
                "Array.from(document.querySelectorAll('video, audio')).map(el => "
                "({id: el.id || '', tagName: el.tagName, "
                "src: el.src || '', currentTime: el.currentTime, "
                "duration: el.duration, paused: el.paused}))"
            ),
            return_by_value=True,
        )
        value = result.get("result", {}).get("value", [])
        return [dict(p) for p in value] if isinstance(value, list) else []

    async def media_get_messages(self, player_id: str) -> list[dict[str, Any]]:
        """Get messages for a specific media player via CDP Media domain."""
        session = self._require_session()
        result = await session.send("Media.getPlayerMessages", {"playerId": player_id})
        return list(result.get("messages", []))

    # ── Cast (experimental) ────────────────────────────────

    async def cast_list(self) -> list[dict[str, Any]]:
        """List available cast sinks via CDP Cast domain."""
        session = self._require_session()
        await session.send("Cast.enable", {})
        result = await session.send("Cast.getSupportedSinks", {})
        sinks = result.get("sinks", [])
        return [dict(s) for s in sinks] if sinks else []

    async def cast_start_tab(self, sink_name: str) -> None:
        """Start tab mirroring to a cast sink via CDP Cast domain."""
        session = self._require_session()
        await session.send("Cast.enable", {})
        await session.send(
            "Cast.startTabMirroring",
            {"sinkName": sink_name},
        )

    async def cast_stop(self) -> None:
        """Stop active cast mirroring via CDP Cast domain."""
        session = self._require_session()
        await session.send("Cast.enable", {})
        await session.send("Cast.stopCasting", {})

    # ── Bluetooth (experimental) ───────────────────────────

    async def bluetooth_emulate(
        self, name: str, address: str = "00:00:00:00:00:01"
    ) -> None:
        """Emulate a Bluetooth Low Energy device via CDP BluetoothEmulation domain."""
        session = self._require_session()
        await session.send("BluetoothEmulation.enable", {})
        await session.send(
            "BluetoothEmulation.simulatePreconnected",
            {"name": name, "address": address},
        )

    async def bluetooth_stop(self) -> None:
        """Stop Bluetooth emulation via CDP BluetoothEmulation domain."""
        session = self._require_session()
        await session.send("BluetoothEmulation.disable", {})

    # ── WebExtensions ──────────────────────────────────────

    async def extension_install(self, path: str) -> str:
        """Install a browser extension via CDP.

        Args:
            path: Path to the .crx file or unpacked extension directory.

        Returns:
            The extension ID.
        """
        import hashlib
        import os

        session = self._require_session()
        is_dir = await asyncio.to_thread(os.path.isdir, path)
        if is_dir:
            abs_path = await asyncio.to_thread(os.path.abspath, path)
            ext_id = hashlib.sha256(abs_path.encode()).hexdigest()[:32]
            await session.send(
                "Extensions.loadUnpacked",
                {"path": abs_path},
            )
        else:
            ext_id = hashlib.sha256(path.encode()).hexdigest()[:32]
            data = await asyncio.to_thread(
                lambda: open(path, "rb").read()  # noqa: SIM115
            )
            await session.send(
                "Extensions.load",
                {"data": data.hex(), "id": ext_id},
            )
        return ext_id

    async def extension_uninstall(self, extension_id: str) -> None:
        """Uninstall a browser extension by ID.

        Args:
            extension_id: The extension ID returned by extension_install.
        """
        session = self._require_session()
        await session.send(
            "Extensions.uninstall",
            {"id": extension_id},
        )

    async def extension_list(self) -> list[dict[str, Any]]:
        """List installed browser extensions.

        Returns:
            List of extension dicts (id, name, version, enabled).
        """
        session = self._require_session()
        result = await session.send("Extensions.getInfo", {})
        extensions = result.get("extensions", [])
        return [
            {
                "id": ext.get("id", ""),
                "name": ext.get("name", ""),
                "version": ext.get("version", ""),
                "enabled": ext.get("enabled", True),
            }
            for ext in extensions
        ]

    # ── Browser preferences ────────────────────────────────

    async def get_pref(self, key: str) -> Any:
        """Get a browser preference value by key.

        Args:
            key: The preference key (e.g. "download.default_directory").

        Returns:
            The preference value.
        """
        session = self._require_session()
        result = await session.send(
            "Browser.getPreference",
            {"name": key},
        )
        return result.get("value")

    async def set_pref(self, key: str, value: Any) -> None:
        """Set a browser preference value.

        Args:
            key: The preference key.
            value: The value to set.
        """
        session = self._require_session()
        await session.send(
            "Browser.setPreference",
            {"name": key, "value": value},
        )

    async def __aenter__(self) -> CDPBackend:
        """Enter async context manager, returning self.

        Returns:
            The CDPBackend instance.
        """
        return self

    async def __aexit__(
        self, exc_type: object, exc_val: object, exc_tb: object
    ) -> None:
        """Exit async context manager, closing the backend.

        Args:
            exc_type: Exception type if raised, else None.
            exc_val: Exception value if raised, else None.
            exc_tb: Traceback if raised, else None.
        """
        await self.close()

__init__

__init__() -> None

Initialize the CDP backend.

Raises:

Type Description
ImportError

If cdpwave is not installed.

Source code in wavexis/backend/cdp.py
def __init__(self) -> None:
    """Initialize the CDP backend.

    Raises:
        ImportError: If cdpwave is not installed.
    """
    if CDPClient is None:
        raise ImportError(
            "cdpwave is not installed. Run: pip install wavexis[cdp]"
        )
    self._client: CDPClient | None = None
    self._session: CDPSession | None = None
    self._console_entries: list[dict[str, Any]] = []
    self._log_entries: list[dict[str, Any]] = []
    self._current_url: str = ""

new_tab_handle async

new_tab_handle(url: str = 'about:blank') -> TabHandle

Create a new tab with its own session, sharing the browser process.

Parameters:

Name Type Description Default
url str

Initial URL for the new tab.

'about:blank'

Returns:

Type Description
TabHandle

A TabHandle that can be used like a CDPBackend for concurrent operations.

Raises:

Type Description
SessionNotInitializedError

If launch() has not been called.

Source code in wavexis/backend/cdp.py
async def new_tab_handle(self, url: str = "about:blank") -> TabHandle:
    """Create a new tab with its own session, sharing the browser process.

    Args:
        url: Initial URL for the new tab.

    Returns:
        A TabHandle that can be used like a CDPBackend for concurrent operations.

    Raises:
        SessionNotInitializedError: If launch() has not been called.
    """
    if self._client is None:
        raise SessionNotInitializedError(
            "Backend not launched. Call launch() first."
        )
    session = await self._client.new_page(url)
    return TabHandle(self._client, session)

launch async

launch(options: BrowserOptions) -> None

Launch Chrome and create a new page session.

Parameters:

Name Type Description Default
options BrowserOptions

Browser launch options (headless, width, height, proxy, etc.).

required
Source code in wavexis/backend/cdp.py
async def launch(self, options: BrowserOptions) -> None:
    """Launch Chrome and create a new page session.

    Args:
        options: Browser launch options (headless, width, height, proxy, etc.).
    """
    extra_args: list[str] = []
    if options.width and options.height:
        extra_args.append(f"--window-size={options.width},{options.height}")
    if options.proxy:
        extra_args.append(f"--proxy-server={options.proxy}")

    if options.browser_url:
        from urllib.parse import urlparse

        parsed = urlparse(options.browser_url)
        host = parsed.hostname or "localhost"
        port = parsed.port or 9222
        self._client = await CDPClient.connect(host=host, port=port)
    elif options.remote_url:
        self._client = await CDPClient.connect(
            ws_url=options.remote_url
        )
    else:
        self._client = await CDPClient.launch(
            headless=options.headless,
            user_data_dir=options.user_data_dir,  # type: ignore[call-arg]
            extra_args=extra_args if extra_args else None,
        )
    self._session = await self._client.new_page()

    if options.user_agent:
        await self._session.emulation.set_user_agent_override(
            user_agent=options.user_agent
        )

    if options.extra_headers:
        await self._session.network.set_extra_http_headers(
            options.extra_headers
        )

    if options.stealth:
        from wavexis.actions.stealth import get_stealth_js

        await self._session.runtime.evaluate(
            get_stealth_js(), await_promise=False
        )

close async

close() -> None

Close the browser client and release resources.

Source code in wavexis/backend/cdp.py
async def close(self) -> None:
    """Close the browser client and release resources."""
    if self._session is not None:
        await self._session.close()
        self._session = None
    if self._client is not None:
        await self._client.close()
        self._client = None

navigate async

navigate(url: str, wait: WaitStrategy | None = None) -> None

Navigate to a URL and optionally wait for a condition.

Parameters:

Name Type Description Default
url str

The URL to navigate to.

required
wait WaitStrategy | None

Wait strategy to apply after navigation.

None

Raises:

Type Description
SessionNotInitializedError

If launch() has not been called.

WaitTimeoutError

If the wait strategy times out.

Source code in wavexis/backend/cdp.py
async def navigate(self, url: str, wait: WaitStrategy | None = None) -> None:
    """Navigate to a URL and optionally wait for a condition.

    Args:
        url: The URL to navigate to.
        wait: Wait strategy to apply after navigation.

    Raises:
        SessionNotInitializedError: If launch() has not been called.
        WaitTimeoutError: If the wait strategy times out.
    """
    session = self._require_session()

    await session.page.enable()
    await session.page.navigate(url)
    self._current_url = url

    if wait is None or wait.strategy == "load":
        timeout_sec = (wait.timeout if wait else 30000) / 1000
        try:
            await session.wait_for_event(
                "Page.loadEventFired", timeout=timeout_sec
            )
        except TimeoutError:
            raise WaitTimeoutError("load", wait.timeout if wait else 30000) from None
    elif wait.strategy == "selector":
        await self.wait_for(wait)
    elif wait.strategy == "domcontentloaded":
        timeout_sec = wait.timeout / 1000
        try:
            await session.wait_for_event(
                "Page.domContentEventFired", timeout=timeout_sec
            )
        except TimeoutError:
            raise WaitTimeoutError("domcontentloaded", wait.timeout) from None
    elif wait.strategy == "networkidle":
        raise ValueError(
            "networkidle wait strategy is not implemented in CDP backend. "
            "Use 'load', 'domcontentloaded', or 'selector' instead."
        )

screenshot async

screenshot(params: ScreenshotParams) -> bytes

Take a screenshot of the current page.

Parameters:

Name Type Description Default
params ScreenshotParams

Screenshot parameters (format, quality, full_page, etc.).

required

Returns:

Type Description
bytes

Screenshot image bytes (PNG or JPEG).

Raises:

Type Description
SessionNotInitializedError

If launch() has not been called.

Source code in wavexis/backend/cdp.py
async def screenshot(self, params: ScreenshotParams) -> bytes:
    """Take a screenshot of the current page.

    Args:
        params: Screenshot parameters (format, quality, full_page, etc.).

    Returns:
        Screenshot image bytes (PNG or JPEG).

    Raises:
        SessionNotInitializedError: If launch() has not been called.
    """
    session = self._require_session()

    if params.device and params.device in DEVICE_PRESETS:
        preset = DEVICE_PRESETS[params.device]
        await session.emulation.set_device_metrics_override(
            width=preset["width"],
            height=preset["height"],
            device_scale_factor=preset["device_scale_factor"],
            mobile=preset["mobile"],
            user_agent=preset["user_agent"],
        )
        if preset.get("touch"):
            await session.emulation.set_touch_emulation_enabled(True)

    result = await session.page.capture_screenshot(
        format=params.format,
        quality=params.quality,
        capture_beyond_viewport=params.full_page,
    )
    data_b64 = result.get("data", "")
    return base64.b64decode(data_b64)

screenshot_selector async

screenshot_selector(selector: str, format: str = 'png', quality: int = 80) -> bytes

Take a screenshot of an element matching a CSS selector.

Uses CDP to get the element's bounding box and clips the screenshot.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
format str

Image format ("png" or "jpeg").

'png'
quality int

JPEG quality (0-100).

80

Returns:

Type Description
bytes

Screenshot image bytes.

Source code in wavexis/backend/cdp.py
async def screenshot_selector(
    self, selector: str, format: str = "png", quality: int = 80
) -> bytes:
    """Take a screenshot of an element matching a CSS selector.

    Uses CDP to get the element's bounding box and clips the screenshot.

    Args:
        selector: CSS selector for the target element.
        format: Image format ("png" or "jpeg").
        quality: JPEG quality (0-100).

    Returns:
        Screenshot image bytes.
    """
    session = self._require_session()

    doc = await session.dom.get_document()
    root_node_id = doc.get("root", {}).get("nodeId", 0)
    node = await session.dom.query_selector(root_node_id, selector)
    node_id = node.get("nodeId", 0)
    box = await session.dom.get_box_model(node_id)
    model = box.get("model", {})
    borders = model.get("border", [])
    if len(borders) >= 8:
        x = min(borders[0], borders[2], borders[4], borders[6])
        y = min(borders[1], borders[3], borders[5], borders[7])
        width = max(borders[0], borders[2], borders[4], borders[6]) - x
        height = max(borders[1], borders[3], borders[5], borders[7]) - y
    else:
        raise NavigationError(selector, "Could not determine element bounds.")

    clip = {
        "x": x,
        "y": y,
        "width": width,
        "height": height,
        "scale": 1,
    }
    result = await session.page.capture_screenshot(
        format=format,
        quality=quality,
        clip=clip,
    )
    data_b64 = result.get("data", "")
    return base64.b64decode(data_b64)

annotated_screenshot async

annotated_screenshot(selectors: list[str], format: str = 'png') -> tuple[bytes, dict[str, str]]

Take a screenshot with numbered labels overlaid on elements.

Parameters:

Name Type Description Default
selectors list[str]

List of CSS selectors to annotate.

required
format str

Image format: "png" or "jpeg".

'png'

Returns:

Type Description
tuple[bytes, dict[str, str]]

Tuple of (image_bytes, label_map).

Source code in wavexis/backend/cdp.py
async def annotated_screenshot(
    self,
    selectors: list[str],
    format: str = "png",
) -> tuple[bytes, dict[str, str]]:
    """Take a screenshot with numbered labels overlaid on elements.

    Args:
        selectors: List of CSS selectors to annotate.
        format: Image format: "png" or "jpeg".

    Returns:
        Tuple of (image_bytes, label_map).
    """
    session = self._require_session()
    js = self._annotate_js(selectors)
    result = await session.runtime.evaluate(js)
    raw = result.get("result", {}).get("value")
    label_map: dict[str, str] = (
        json.loads(raw) if isinstance(raw, str) else {}
    )
    screenshot = await session.page.capture_screenshot(format=format)
    await session.runtime.evaluate(self._remove_annotate_js())
    data_b64 = screenshot.get("data", "")
    return base64.b64decode(data_b64), label_map

eval async

eval(expression: str, await_promise: bool = False) -> Any

Evaluate a JavaScript expression.

Parameters:

Name Type Description Default
expression str

JavaScript expression to evaluate.

required
await_promise bool

Whether to await a returned Promise.

False

Returns:

Type Description
Any

The evaluation result value.

Source code in wavexis/backend/cdp.py
async def eval(self, expression: str, await_promise: bool = False) -> Any:
    """Evaluate a JavaScript expression.

    Args:
        expression: JavaScript expression to evaluate.
        await_promise: Whether to await a returned Promise.

    Returns:
        The evaluation result value.
    """
    session = self._require_session()

    await session.runtime.enable()
    result = await session.runtime.evaluate(
        expression,
        await_promise=await_promise,
    )
    return result.get("result", {}).get("value")

raw async

raw(method: str, params: dict[str, Any] | None = None) -> dict[str, Any]

Send a raw CDP command.

Parameters:

Name Type Description Default
method str

CDP method name (e.g. "Page.navigate").

required
params dict[str, Any] | None

Optional command parameters.

None

Returns:

Type Description
dict[str, Any]

The CDP response result dict.

Source code in wavexis/backend/cdp.py
async def raw(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
    """Send a raw CDP command.

    Args:
        method: CDP method name (e.g. "Page.navigate").
        params: Optional command parameters.

    Returns:
        The CDP response result dict.
    """
    session = self._require_session()
    result: dict[str, Any] = await session.send(method, params)
    return result

go_back async

go_back() -> None

Navigate back in browser history.

Source code in wavexis/backend/cdp.py
async def go_back(self) -> None:
    """Navigate back in browser history."""
    session = self._require_session()
    history = await session.page.get_navigation_history()
    current_idx = history.get("currentIndex", 0)
    entries = history.get("entries", [])
    if current_idx > 0 and entries:
        prev_entry = entries[current_idx - 1]
        await session.page.navigate_to_history_entry(
            prev_entry.get("id", 0)
        )

go_forward async

go_forward() -> None

Navigate forward in browser history.

Source code in wavexis/backend/cdp.py
async def go_forward(self) -> None:
    """Navigate forward in browser history."""
    session = self._require_session()
    history = await session.page.get_navigation_history()
    current_idx = history.get("currentIndex", 0)
    entries = history.get("entries", [])
    if current_idx < len(entries) - 1:
        next_entry = entries[current_idx + 1]
        await session.page.navigate_to_history_entry(
            next_entry.get("id", 0)
        )

reload async

reload(ignore_cache: bool = False) -> None

Reload the current page.

Parameters:

Name Type Description Default
ignore_cache bool

If True, bypass the browser cache.

False
Source code in wavexis/backend/cdp.py
async def reload(self, ignore_cache: bool = False) -> None:
    """Reload the current page.

    Args:
        ignore_cache: If True, bypass the browser cache.
    """
    session = self._require_session()
    await session.page.reload(ignore_cache=ignore_cache)

stop_loading async

stop_loading() -> None

Stop all pending navigations and resource loads.

Source code in wavexis/backend/cdp.py
async def stop_loading(self) -> None:
    """Stop all pending navigations and resource loads."""
    session = self._require_session()
    await session.page.stop()

wait_for async

wait_for(strategy: WaitStrategy) -> None

Wait for a specific condition.

Parameters:

Name Type Description Default
strategy WaitStrategy

Wait strategy (selector, load, url).

required

Raises:

Type Description
WaitTimeoutError

If the condition is not met within the timeout.

Source code in wavexis/backend/cdp.py
async def wait_for(self, strategy: WaitStrategy) -> None:
    """Wait for a specific condition.

    Args:
        strategy: Wait strategy (selector, load, url).

    Raises:
        WaitTimeoutError: If the condition is not met within the timeout.
    """
    session = self._require_session()

    timeout_sec = strategy.timeout / 1000
    deadline = time.monotonic() + timeout_sec

    if strategy.strategy == "selector" and strategy.selector:
        escaped = json.dumps(strategy.selector)
        js = f"document.querySelector('{escaped}') !== null"
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate(js)
            if result.get("result", {}).get("value") is True:
                return
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("selector", strategy.timeout)

    if strategy.strategy == "load":
        try:
            await session.wait_for_event(
                "Page.loadEventFired", timeout=timeout_sec
            )
        except TimeoutError:
            raise WaitTimeoutError("load", strategy.timeout) from None
        return

    if strategy.strategy == "url" and strategy.url_pattern:
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate("window.location.href")
            href = result.get("result", {}).get("value", "")
            if strategy.url_pattern in href:
                return
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("url", strategy.timeout)

    if strategy.strategy == "domcontentloaded":
        try:
            await session.wait_for_event(
                "Page.domContentEventFired", timeout=timeout_sec
            )
        except TimeoutError:
            raise WaitTimeoutError("domcontentloaded", strategy.timeout) from None
        return

    if strategy.strategy == "networkidle":
        # Poll for network idle: no more than 2 active requests for 500ms
        js = """
        (function() {
            return window.performance.getEntries()
                .filter(e => e.entryType === 'resource')
                .filter(e => !e.duration || e.duration < 0)
                .length <= 2;
        })()
        """
        deadline = time.monotonic() + timeout_sec
        idle_start = None
        while time.monotonic() < deadline:
            result = await session.runtime.evaluate(js)
            is_idle = result.get("result", {}).get("value", False)
            if is_idle:
                if idle_start is None:
                    idle_start = time.monotonic()
                elif time.monotonic() - idle_start >= 0.5:
                    return
            else:
                idle_start = None
            await asyncio.sleep(0.1)
        raise WaitTimeoutError("networkidle", strategy.timeout)

    # If we get here, the strategy is not supported
    raise ValueError(f"Unsupported wait strategy: {strategy.strategy}")

pdf async

pdf(params: PDFParams) -> bytes

Generate a PDF of the current page.

Parameters:

Name Type Description Default
params PDFParams

PDF generation parameters.

required

Returns:

Type Description
bytes

PDF bytes.

Source code in wavexis/backend/cdp.py
async def pdf(self, params: PDFParams) -> bytes:
    """Generate a PDF of the current page.

    Args:
        params: PDF generation parameters.

    Returns:
        PDF bytes.
    """
    session = self._require_session()

    await session.emulation.set_emulated_media(media=params.media)

    paper_dims = PAPER_SIZES.get(params.paper, PAPER_SIZES["letter"])
    margin_val = float(params.margin.replace("in", "").replace("cm", ""))

    result = await session.page.print_to_pdf(
        landscape=params.landscape,
        display_header_footer=not params.no_header_footer,
        print_background=True,
        paper_width=paper_dims["width"],
        paper_height=paper_dims["height"],
        margin_top=margin_val,
        margin_bottom=margin_val,
        margin_left=margin_val,
        margin_right=margin_val,
    )
    data_b64 = result.get("data", "")
    return base64.b64decode(data_b64)

screencast async

screencast(params: ScreencastParams) -> list[bytes]

Capture a screencast and return a list of frame bytes.

Parameters:

Name Type Description Default
params ScreencastParams

Screencast parameters.

required

Returns:

Type Description
list[bytes]

List of frame image bytes.

Source code in wavexis/backend/cdp.py
async def screencast(self, params: ScreencastParams) -> list[bytes]:
    """Capture a screencast and return a list of frame bytes.

    Args:
        params: Screencast parameters.

    Returns:
        List of frame image bytes.
    """
    session = self._require_session()

    frames: list[bytes] = []

    def on_frame(event_params: dict[str, Any]) -> None:
        """Handle a screencast frame event and decode the image data.

        Args:
            event_params: CDP event parameters containing base64-encoded frame data.
        """
        data = event_params.get("data")
        if data:
            frames.append(base64.b64decode(data))

    session.on("Page.screencastFrame", on_frame)

    await session.send("Page.startScreencast", {
        "format": params.format,
        "quality": params.quality,
        "maxWidth": params.max_width,
        "maxHeight": params.max_height,
    })

    await asyncio.sleep(params.duration)

    await session.send("Page.stopScreencast")

    return frames

list_tabs async

list_tabs() -> list[dict[str, Any]]

List all open browser tabs/targets.

Returns:

Type Description
list[dict[str, Any]]

List of target info dicts.

Source code in wavexis/backend/cdp.py
async def list_tabs(self) -> list[dict[str, Any]]:
    """List all open browser tabs/targets.

    Returns:
        List of target info dicts.
    """
    session = self._require_session()
    result = await session.target.get_targets()
    targets = result.get("targetInfos", [])
    return [t for t in targets if t.get("type") == "page"]

new_tab async

new_tab(url: str = 'about:blank') -> str

Create a new tab and return its target ID.

Parameters:

Name Type Description Default
url str

Initial URL for the new tab.

'about:blank'

Returns:

Type Description
str

The target ID of the new tab.

Source code in wavexis/backend/cdp.py
async def new_tab(self, url: str = "about:blank") -> str:
    """Create a new tab and return its target ID.

    Args:
        url: Initial URL for the new tab.

    Returns:
        The target ID of the new tab.
    """
    session = self._require_session()
    result = await session.target.create_target(url)
    return str(result.get("targetId", ""))

close_tab async

close_tab(tab_id: str) -> None

Close a tab by its target ID.

Parameters:

Name Type Description Default
tab_id str

The target ID of the tab to close.

required
Source code in wavexis/backend/cdp.py
async def close_tab(self, tab_id: str) -> None:
    """Close a tab by its target ID.

    Args:
        tab_id: The target ID of the tab to close.
    """
    session = self._require_session()
    await session.target.close_target(tab_id)

activate_tab async

activate_tab(tab_id: str) -> None

Activate (focus) a tab by its target ID.

Parameters:

Name Type Description Default
tab_id str

The target ID of the tab to activate.

required
Source code in wavexis/backend/cdp.py
async def activate_tab(self, tab_id: str) -> None:
    """Activate (focus) a tab by its target ID.

    Args:
        tab_id: The target ID of the tab to activate.
    """
    session = self._require_session()
    await session.target.activate_target(tab_id)

capture_console async

capture_console(level: str = 'all') -> list[dict[str, Any]]

Capture console messages at or above the given level.

Parameters:

Name Type Description Default
level str

Minimum log level ("all", "error", "warning", "info", "log").

'all'

Returns:

Type Description
list[dict[str, Any]]

List of console entry dicts with type, args, and timestamp.

Source code in wavexis/backend/cdp.py
async def capture_console(self, level: str = "all") -> list[dict[str, Any]]:
    """Capture console messages at or above the given level.

    Args:
        level: Minimum log level ("all", "error", "warning", "info", "log").

    Returns:
        List of console entry dicts with type, args, and timestamp.
    """
    session = self._require_session()

    entries: list[dict[str, Any]] = []

    def on_console_api(event_params: dict[str, Any]) -> None:
        """Handle a Runtime.consoleAPICalled event and append matching entries.

        Args:
            event_params: CDP event parameters with console API call data.
        """
        entry_type = event_params.get("type", "log")
        if level == "all" or entry_type == level:
            entries.append({
                "type": entry_type,
                "args": event_params.get("args", []),
                "executionContextId": event_params.get("executionContextId"),
                "timestamp": event_params.get("timestamp"),
            })

    session.on("Runtime.consoleAPICalled", on_console_api)

    await session.runtime.enable()
    await asyncio.sleep(0.5)

    return entries

capture_logs async

capture_logs() -> list[dict[str, Any]]

Capture browser log entries.

Returns:

Type Description
list[dict[str, Any]]

List of log entry dicts with level, text, and timestamp.

Source code in wavexis/backend/cdp.py
async def capture_logs(self) -> list[dict[str, Any]]:
    """Capture browser log entries.

    Returns:
        List of log entry dicts with level, text, and timestamp.
    """
    session = self._require_session()

    entries: list[dict[str, Any]] = []

    def on_log_entry(event_params: dict[str, Any]) -> None:
        """Handle a Log.entryAdded event and append the log entry.

        Args:
            event_params: CDP event parameters containing the log entry.
        """
        entry = event_params.get("entry", {})
        entries.append({
            "level": entry.get("level", "info"),
            "text": entry.get("text", ""),
            "timestamp": entry.get("timestamp"),
            "url": entry.get("url"),
            "lineNumber": entry.get("lineNumber"),
            "stackTrace": entry.get("stackTrace", []),
        })

    session.on("Log.entryAdded", on_log_entry)

    await session.log.enable()
    await asyncio.sleep(0.5)

    return entries

dom_get async

dom_get(selector: str, outer: bool = True) -> str

Get the HTML of an element matching a CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
outer bool

If True, return outerHTML; otherwise innerHTML.

True

Returns:

Type Description
str

The HTML string of the element.

Source code in wavexis/backend/cdp.py
async def dom_get(self, selector: str, outer: bool = True) -> str:
    """Get the HTML of an element matching a CSS selector.

    Args:
        selector: CSS selector for the target element.
        outer: If True, return outerHTML; otherwise innerHTML.

    Returns:
        The HTML string of the element.
    """
    session = self._require_session()
    node_id = await self._find_node(selector)
    if outer:
        result = await session.dom.get_outer_html(node_id)
        return str(result.get("outerHTML", ""))
    result = await session.dom.get_outer_html(node_id)
    outer_html = str(result.get("outerHTML", ""))
    inner = re.sub(r"^<[^>]+>", "", outer_html, count=1)
    inner = re.sub(r"<[^>]+>$", "", inner, count=1)
    return inner

dom_query async

dom_query(selector: str, all: bool = False) -> list[dict[str, Any]] | dict[str, Any]

Query elements by CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector string.

required
all bool

If True, return all matches as a list; otherwise first match.

False

Returns:

Type Description
list[dict[str, Any]] | dict[str, Any]

List of node dicts when all=True, single dict when all=False.

Source code in wavexis/backend/cdp.py
async def dom_query(
    self, selector: str, all: bool = False
) -> list[dict[str, Any]] | dict[str, Any]:
    """Query elements by CSS selector.

    Args:
        selector: CSS selector string.
        all: If True, return all matches as a list; otherwise first match.

    Returns:
        List of node dicts when all=True, single dict when all=False.
    """
    session = self._require_session()
    await session.dom.enable()
    doc = await session.dom.get_document()
    root_node_id = doc.get("root", {}).get("nodeId", 0)

    if all:
        result = await session.dom.query_selector_all(root_node_id, selector)
        node_ids = result.get("nodeIds", [])
        nodes: list[dict[str, Any]] = []
        for nid in node_ids:
            desc = await session.dom.describe_node(node_id=nid)
            nodes.append(desc.get("node", {}))
        return nodes

    result = await session.dom.query_selector(root_node_id, selector)
    node_id = result.get("nodeId", 0)
    if node_id == 0:
        raise ElementNotFoundError(selector)
    desc = await session.dom.describe_node(node_id=node_id)
    return dict(desc.get("node", {}))

dom_set_attr async

dom_set_attr(selector: str, name: str, value: str) -> None

Set an attribute on an element matching a CSS selector.

Source code in wavexis/backend/cdp.py
async def dom_set_attr(self, selector: str, name: str, value: str) -> None:
    """Set an attribute on an element matching a CSS selector."""
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.dom.set_attribute_value(node_id, name, value)

dom_get_attr async

dom_get_attr(selector: str, name: str) -> str

Get an attribute value from an element matching a CSS selector.

Source code in wavexis/backend/cdp.py
async def dom_get_attr(self, selector: str, name: str) -> str:
    """Get an attribute value from an element matching a CSS selector."""
    session = self._require_session()
    node_id = await self._find_node(selector)
    result = await session.dom.get_attribute(node_id, name)
    attrs = result.get("attributes", [])
    for i in range(0, len(attrs) - 1, 2):
        if attrs[i] == name:
            return str(attrs[i + 1])
    return ""

dom_remove_attr async

dom_remove_attr(selector: str, name: str) -> None

Remove an attribute from an element matching a CSS selector.

Source code in wavexis/backend/cdp.py
async def dom_remove_attr(self, selector: str, name: str) -> None:
    """Remove an attribute from an element matching a CSS selector."""
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.dom.remove_attribute(node_id, name)

dom_remove async

dom_remove(selector: str) -> None

Remove an element matching a CSS selector from the DOM.

Source code in wavexis/backend/cdp.py
async def dom_remove(self, selector: str) -> None:
    """Remove an element matching a CSS selector from the DOM."""
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.dom.remove_node(node_id)

dom_focus async

dom_focus(selector: str) -> None

Focus an element matching a CSS selector.

Source code in wavexis/backend/cdp.py
async def dom_focus(self, selector: str) -> None:
    """Focus an element matching a CSS selector."""
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.dom.focus(node_id)

dom_scroll async

dom_scroll(selector: str | None = None, x: int = 0, y: int = 0) -> None

Scroll to an element or by offset.

Parameters:

Name Type Description Default
selector str | None

CSS selector to scroll to. If None, scroll by offset.

None
x int

Horizontal scroll offset.

0
y int

Vertical scroll offset.

0
Source code in wavexis/backend/cdp.py
async def dom_scroll(
    self, selector: str | None = None, x: int = 0, y: int = 0
) -> None:
    """Scroll to an element or by offset.

    Args:
        selector: CSS selector to scroll to. If None, scroll by offset.
        x: Horizontal scroll offset.
        y: Vertical scroll offset.
    """
    session = self._require_session()
    if selector:
        escaped = json.dumps(selector)
        js = f"document.querySelector('{escaped}').scrollIntoView()"
    else:
        js = f"window.scrollBy({x}, {y})"
    await session.runtime.evaluate(js)

suggest_locator async

suggest_locator(selector: str, all: bool = False) -> list[str] | str

Suggest the best CSS selector for an element.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
all bool

If True, return multiple suggestions; otherwise just the best one.

False

Returns:

Type Description
list[str] | str

List of selector strings when all=True, single best selector when all=False.

Source code in wavexis/backend/cdp.py
async def suggest_locator(
    self, selector: str, all: bool = False
) -> list[str] | str:
    """Suggest the best CSS selector for an element.

    Args:
        selector: CSS selector for the target element.
        all: If True, return multiple suggestions; otherwise just the best one.

    Returns:
        List of selector strings when all=True, single best selector when all=False.
    """
    session = self._require_session()
    escaped = json.dumps(selector)
    js = self._suggest_locator_js(escaped)
    result = await session.runtime.evaluate(js)
    raw = result.get("result", {}).get("value")
    if not raw:
        raise ElementNotFoundError(selector)
    suggestions: list[str] = json.loads(raw)
    if all:
        return suggestions
    return suggestions[0] if suggestions else selector

find_by_text async

find_by_text(query: str, all: bool = False) -> list[str] | str

Find elements by natural language text query.

Parameters:

Name Type Description Default
query str

Natural language query (e.g. "the login button").

required
all bool

If True, return all matches; otherwise just the best one.

False

Returns:

Type Description
list[str] | str

List of CSS selector strings when all=True, single best when all=False.

Raises:

Type Description
ElementNotFoundError

If no element matches the query.

Source code in wavexis/backend/cdp.py
async def find_by_text(
    self, query: str, all: bool = False
) -> list[str] | str:
    """Find elements by natural language text query.

    Args:
        query: Natural language query (e.g. "the login button").
        all: If True, return all matches; otherwise just the best one.

    Returns:
        List of CSS selector strings when all=True, single best when all=False.

    Raises:
        ElementNotFoundError: If no element matches the query.
    """
    session = self._require_session()
    js = self._find_by_text_js(query)
    result = await session.runtime.evaluate(js)
    raw = result.get("result", {}).get("value")
    if not raw:
        raise ElementNotFoundError(query)
    selectors: list[str] = json.loads(raw)
    if not selectors:
        raise ElementNotFoundError(query)
    if all:
        return selectors
    return selectors[0]

nl_click async

nl_click(query: str, auto_wait: bool = True) -> None

Click an element found by natural language text query.

Parameters:

Name Type Description Default
query str

Natural language query (e.g. "login button").

required
auto_wait bool

If True, wait for element to be visible before clicking.

True
Source code in wavexis/backend/cdp.py
async def nl_click(
    self, query: str, auto_wait: bool = True
) -> None:
    """Click an element found by natural language text query.

    Args:
        query: Natural language query (e.g. "login button").
        auto_wait: If True, wait for element to be visible before clicking.
    """
    selector = await self.find_by_text(query)
    assert isinstance(selector, str)
    await self.click(selector, auto_wait=auto_wait)

nl_fill async

nl_fill(query: str, value: str, auto_wait: bool = True) -> None

Fill an input element found by natural language text query.

Parameters:

Name Type Description Default
query str

Natural language query (e.g. "email field").

required
value str

Value to set in the input field.

required
auto_wait bool

If True, wait for element to be visible before filling.

True
Source code in wavexis/backend/cdp.py
async def nl_fill(
    self, query: str, value: str, auto_wait: bool = True
) -> None:
    """Fill an input element found by natural language text query.

    Args:
        query: Natural language query (e.g. "email field").
        value: Value to set in the input field.
        auto_wait: If True, wait for element to be visible before filling.
    """
    selector = await self.find_by_text(query)
    assert isinstance(selector, str)
    await self.fill(selector, value, auto_wait=auto_wait)

capture_har async

capture_har(params: HarParams) -> dict[str, Any]

Navigate to a URL and capture network traffic as HAR 1.2 dict.

Parameters:

Name Type Description Default
params HarParams

HAR capture parameters.

required

Returns:

Type Description
dict[str, Any]

HAR 1.2 compliant dict with log.entries.

Source code in wavexis/backend/cdp.py
async def capture_har(self, params: HarParams) -> dict[str, Any]:
    """Navigate to a URL and capture network traffic as HAR 1.2 dict.

    Args:
        params: HAR capture parameters.

    Returns:
        HAR 1.2 compliant dict with log.entries.
    """
    session = self._require_session()

    requests: dict[str, dict[str, Any]] = {}
    responses: dict[str, dict[str, Any]] = {}
    finished: dict[str, dict[str, Any]] = {}

    def on_request(event_params: dict[str, Any]) -> None:
        """Handle Network.requestWillBeSent and record the request.

        Args:
            event_params: CDP event parameters with request data.
        """
        req_id = event_params.get("requestId", "")
        request = event_params.get("request", {})
        requests[req_id] = {
            "method": request.get("method", "GET"),
            "url": request.get("url", ""),
            "headers": [
                {"name": k, "value": v}
                for k, v in request.get("headers", {}).items()
            ],
            "queryString": [
                {"name": k, "value": v}
                for k, v in request.get("queryString", {}).items()
            ],
            "headersSize": -1,
            "bodySize": -1,
            "timestamp": event_params.get("timestamp", 0),
            "wallTime": event_params.get("wallTime", 0),
            "type": event_params.get("type", ""),
        }

    def on_response(event_params: dict[str, Any]) -> None:
        """Handle Network.responseReceived and record the response.

        Args:
            event_params: CDP event parameters with response data.
        """
        req_id = event_params.get("requestId", "")
        response = event_params.get("response", {})
        responses[req_id] = {
            "status": response.get("status", 0),
            "statusText": response.get("statusText", ""),
            "headers": [
                {"name": k, "value": v}
                for k, v in response.get("headers", {}).items()
            ],
            "mimeType": response.get("mimeType", ""),
            "redirectURL": response.get("redirectUrl", ""),
            "headersSize": response.get("headersSize", -1),
            "bodySize": response.get("encodedDataLength", -1),
            "content": {
                "size": response.get("content", {}).get("size", 0),
                "mimeType": response.get("content", {}).get("mimeType", ""),
            },
        }

    def on_loading_finished(event_params: dict[str, Any]) -> None:
        """Handle Network.loadingFinished and mark a request as complete.

        Args:
            event_params: CDP event parameters with loading finish data.
        """
        req_id = event_params.get("requestId", "")
        finished[req_id] = {
            "timestamp": event_params.get("timestamp", 0),
            "encodedDataLength": event_params.get("encodedDataLength", 0),
        }

    session.on("Network.requestWillBeSent", on_request)
    session.on("Network.responseReceived", on_response)
    session.on("Network.loadingFinished", on_loading_finished)

    await session.network.enable()
    await self.navigate(params.url, WaitStrategy(strategy="load"))
    await asyncio.sleep(params.wait / 1000)

    entries: list[dict[str, Any]] = []
    for req_id, req_data in requests.items():
        url = req_data.get("url", "")
        if params.filter and params.filter not in url:
            continue
        resp = responses.get(req_id, {})
        fin = finished.get(req_id, {})
        wall_time = req_data.get("wallTime", 0)
        started_dt = (
            f"{time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(wall_time))}"
            if wall_time
            else ""
        )
        send_time = 0
        wait_time = max(
            float(fin.get("timestamp", 0)) - float(req_data.get("timestamp", 0)),
            0.0,
        )
        receive_time = 0
        entries.append({
            "request": {
                "method": req_data.get("method", "GET"),
                "url": url,
                "headers": req_data.get("headers", []),
                "queryString": req_data.get("queryString", []),
                "headersSize": req_data.get("headersSize", -1),
                "bodySize": req_data.get("bodySize", -1),
            },
            "response": {
                "status": resp.get("status", 0),
                "statusText": resp.get("statusText", ""),
                "headers": resp.get("headers", []),
                "content": resp.get("content", {"size": 0, "mimeType": ""}),
                "redirectURL": resp.get("redirectURL", ""),
                "headersSize": resp.get("headersSize", -1),
                "bodySize": resp.get("bodySize", -1),
            },
            "timings": {
                "send": send_time,
                "wait": round(wait_time * 1000, 2),
                "receive": receive_time,
            },
            "time": round((wait_time + send_time + receive_time) * 1000, 2),
            "startedDateTime": started_dt,
        })

    return {
        "log": {
            "version": "1.2",
            "creator": {"name": "wavexis", "version": "0.3.0"},
            "entries": entries,
        }
    }

get_cookies async

get_cookies() -> list[dict[str, Any]]

Get all cookies for the current page.

Returns:

Type Description
list[dict[str, Any]]

List of cookie dicts.

Source code in wavexis/backend/cdp.py
async def get_cookies(self) -> list[dict[str, Any]]:
    """Get all cookies for the current page.

    Returns:
        List of cookie dicts.
    """
    session = self._require_session()
    result = await session.network.get_cookies()
    return list(result.get("cookies", []))
set_cookie(params: CookieParams) -> None

Set a cookie in the browser.

Parameters:

Name Type Description Default
params CookieParams

Cookie parameters.

required
Source code in wavexis/backend/cdp.py
async def set_cookie(self, params: CookieParams) -> None:
    """Set a cookie in the browser.

    Args:
        params: Cookie parameters.
    """
    session = self._require_session()
    await session.network.set_cookie(
        name=params.name,
        value=params.value,
        domain=params.domain or None,
        path=params.path,
        secure=params.secure,
        http_only=params.http_only,
        same_site=params.same_site,
    )
delete_cookie(name: str, domain: str) -> None

Delete cookies matching name and domain.

Parameters:

Name Type Description Default
name str

Cookie name to delete.

required
domain str

Cookie domain to scope deletion.

required
Source code in wavexis/backend/cdp.py
async def delete_cookie(self, name: str, domain: str) -> None:
    """Delete cookies matching name and domain.

    Args:
        name: Cookie name to delete.
        domain: Cookie domain to scope deletion.
    """
    session = self._require_session()
    await session.network.delete_cookies(name=name, domain=domain)

clear_cookies async

clear_cookies() -> None

Clear all browser cookies.

Source code in wavexis/backend/cdp.py
async def clear_cookies(self) -> None:
    """Clear all browser cookies."""
    session = self._require_session()
    await session.network.clear_browser_cookies()

set_headers async

set_headers(headers: dict[str, str]) -> None

Set extra HTTP headers for all requests.

Parameters:

Name Type Description Default
headers dict[str, str]

Dict of header name to value.

required
Source code in wavexis/backend/cdp.py
async def set_headers(self, headers: dict[str, str]) -> None:
    """Set extra HTTP headers for all requests.

    Args:
        headers: Dict of header name to value.
    """
    session = self._require_session()
    await session.network.enable()
    await session.network.set_extra_request_headers(headers)

set_user_agent async

set_user_agent(user_agent: str) -> None

Override the browser's User-Agent string.

Parameters:

Name Type Description Default
user_agent str

The User-Agent string to use.

required
Source code in wavexis/backend/cdp.py
async def set_user_agent(self, user_agent: str) -> None:
    """Override the browser's User-Agent string.

    Args:
        user_agent: The User-Agent string to use.
    """
    session = self._require_session()
    await session.network.set_user_agent_override(user_agent=user_agent)

new_context async

new_context() -> str

Create a new browser context and return its ID.

Returns:

Type Description
str

The browser context ID string.

Source code in wavexis/backend/cdp.py
async def new_context(self) -> str:
    """Create a new browser context and return its ID.

    Returns:
        The browser context ID string.
    """
    self._require_session()
    if self._client is None:
        raise NavigationError("", "Client not initialized.")
    result = await self._client.send("Target.createBrowserContext", {})
    return str(result.get("browserContextId", ""))

list_contexts async

list_contexts() -> list[dict[str, Any]]

List all browser contexts.

Returns:

Type Description
list[dict[str, Any]]

List of context info dicts.

Source code in wavexis/backend/cdp.py
async def list_contexts(self) -> list[dict[str, Any]]:
    """List all browser contexts.

    Returns:
        List of context info dicts.
    """
    session = self._require_session()
    result = await session.send("Target.getBrowserContexts")
    contexts = result.get("browserContextIds", [])
    return [{"contextId": ctx} for ctx in contexts]

close_context async

close_context(context_id: str) -> None

Close a browser context by ID.

Parameters:

Name Type Description Default
context_id str

The browser context ID to close.

required
Source code in wavexis/backend/cdp.py
async def close_context(self, context_id: str) -> None:
    """Close a browser context by ID.

    Args:
        context_id: The browser context ID to close.
    """
    session = self._require_session()
    await session.target.dispose_browser_context(context_id)

get_window_bounds async

get_window_bounds() -> dict[str, Any]

Get the current window bounds.

Returns:

Type Description
dict[str, Any]

Dict with width, height, left, top.

Source code in wavexis/backend/cdp.py
async def get_window_bounds(self) -> dict[str, Any]:
    """Get the current window bounds.

    Returns:
        Dict with width, height, left, top.
    """
    session = self._require_session()
    if self._client is None:
        raise NavigationError("", "Client not initialized.")
    result = await self._client.browser.get_window_for_target(
        target_id=session.target_id
    )
    bounds = result.get("bounds", {})
    return {
        "width": bounds.get("width", 0),
        "height": bounds.get("height", 0),
        "x": bounds.get("left", 0),
        "y": bounds.get("top", 0),
    }

set_window_bounds async

set_window_bounds(width: int, height: int, x: int = 0, y: int = 0) -> None

Set the window bounds.

Parameters:

Name Type Description Default
width int

Window width in pixels.

required
height int

Window height in pixels.

required
x int

Window X position.

0
y int

Window Y position.

0
Source code in wavexis/backend/cdp.py
async def set_window_bounds(
    self, width: int, height: int, x: int = 0, y: int = 0
) -> None:
    """Set the window bounds.

    Args:
        width: Window width in pixels.
        height: Window height in pixels.
        x: Window X position.
        y: Window Y position.
    """
    session = self._require_session()
    if self._client is None:
        raise NavigationError("", "Client not initialized.")
    result = await self._client.browser.get_window_for_target(
        target_id=session.target_id
    )
    window_id = result.get("windowId", 0)
    bounds = {
        "left": x,
        "top": y,
        "width": width,
        "height": height,
        "windowState": "normal",
    }
    await self._client.browser.set_window_bounds(window_id, bounds)

browser_version async

browser_version() -> str

Get the browser version string.

Returns:

Type Description
str

The browser product/version string.

Source code in wavexis/backend/cdp.py
async def browser_version(self) -> str:
    """Get the browser version string.

    Returns:
        The browser product/version string.
    """
    if self._client is None:
        raise NavigationError("", "Client not initialized.")
    result = await self._client.browser.get_version()
    return str(result.get("product", ""))

emulate_device async

emulate_device(device: str) -> None

Emulate a device by preset name.

Parameters:

Name Type Description Default
device str

Device preset name (e.g. 'iphone-15').

required

Raises:

Type Description
ValueError

If the device name is not in DEVICE_PRESETS.

Source code in wavexis/backend/cdp.py
async def emulate_device(self, device: str) -> None:
    """Emulate a device by preset name.

    Args:
        device: Device preset name (e.g. 'iphone-15').

    Raises:
        ValueError: If the device name is not in DEVICE_PRESETS.
    """
    session = self._require_session()
    preset = DEVICE_PRESETS.get(device)
    if preset is None:
        raise ValueError(f"Unknown device preset: {device}")
    await session.emulation.set_device_metrics_override(
        width=int(preset["width"]),
        height=int(preset["height"]),
        device_scale_factor=float(preset["device_scale_factor"]),
        mobile=bool(preset["mobile"]),
        user_agent=str(preset["user_agent"]),
    )
    if preset.get("touch"):
        await session.emulation.set_touch_emulation_enabled(True)

set_viewport async

set_viewport(width: int, height: int, device_scale_factor: float = 1.0) -> None

Set a custom viewport with given dimensions and scale factor.

Parameters:

Name Type Description Default
width int

Viewport width in CSS pixels.

required
height int

Viewport height in CSS pixels.

required
device_scale_factor float

Device pixel scale factor.

1.0
Source code in wavexis/backend/cdp.py
async def set_viewport(
    self, width: int, height: int, device_scale_factor: float = 1.0
) -> None:
    """Set a custom viewport with given dimensions and scale factor.

    Args:
        width: Viewport width in CSS pixels.
        height: Viewport height in CSS pixels.
        device_scale_factor: Device pixel scale factor.
    """
    session = self._require_session()
    await session.emulation.set_device_metrics_override(
        width=width,
        height=height,
        device_scale_factor=device_scale_factor,
        mobile=False,
    )

set_geolocation async

set_geolocation(latitude: float, longitude: float, accuracy: float = 100.0) -> None

Override the geolocation position.

Parameters:

Name Type Description Default
latitude float

Latitude in degrees.

required
longitude float

Longitude in degrees.

required
accuracy float

Accuracy in meters.

100.0
Source code in wavexis/backend/cdp.py
async def set_geolocation(
    self, latitude: float, longitude: float, accuracy: float = 100.0
) -> None:
    """Override the geolocation position.

    Args:
        latitude: Latitude in degrees.
        longitude: Longitude in degrees.
        accuracy: Accuracy in meters.
    """
    session = self._require_session()
    await session.emulation.set_geolocation_override(
        latitude=latitude,
        longitude=longitude,
        accuracy=accuracy,
    )

set_timezone async

set_timezone(timezone: str) -> None

Override the system timezone.

Parameters:

Name Type Description Default
timezone str

IANA timezone ID (e.g. 'America/New_York').

required
Source code in wavexis/backend/cdp.py
async def set_timezone(self, timezone: str) -> None:
    """Override the system timezone.

    Args:
        timezone: IANA timezone ID (e.g. 'America/New_York').
    """
    session = self._require_session()
    await session.emulation.set_timezone_override(timezone)

set_dark_mode async

set_dark_mode(enabled: bool) -> None

Enable or disable dark mode emulation.

Parameters:

Name Type Description Default
enabled bool

True to enable dark mode, False to disable.

required
Source code in wavexis/backend/cdp.py
async def set_dark_mode(self, enabled: bool) -> None:
    """Enable or disable dark mode emulation.

    Args:
        enabled: True to enable dark mode, False to disable.
    """
    session = self._require_session()
    features = [{"name": "prefers-color-scheme", "value": "dark" if enabled else "light"}]
    await session.emulation.set_emulated_media(features=features)

click async

click(selector: str, button: str = 'left', click_count: int = 1, auto_wait: bool = True) -> None

Click an element matching a CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
button str

Mouse button — "left", "right", or "middle".

'left'
click_count int

Number of clicks to dispatch.

1
auto_wait bool

If True, wait for element to be visible before clicking.

True
Source code in wavexis/backend/cdp.py
async def click(
    self,
    selector: str,
    button: str = "left",
    click_count: int = 1,
    auto_wait: bool = True,
) -> None:
    """Click an element matching a CSS selector.

    Args:
        selector: CSS selector for the target element.
        button: Mouse button — "left", "right", or "middle".
        click_count: Number of clicks to dispatch.
        auto_wait: If True, wait for element to be visible before clicking.
    """
    session = self._require_session()
    if auto_wait:
        await self._wait_for_element(selector)
    await self._scroll_into_view_if_needed(selector)
    x, y = await self._get_box_center(selector)
    btn_map = {"left": "left", "right": "right", "middle": "middle"}
    btn = btn_map.get(button, "left")
    for _ in range(click_count):
        await session.input.dispatch_mouse_event(
            **{"type": "mousePressed"}, x=x, y=y, button=btn, click_count=1
        )
        await session.input.dispatch_mouse_event(
            **{"type": "mouseReleased"}, x=x, y=y, button=btn, click_count=1
        )

type_text async

type_text(selector: str, text: str, delay: int = 0) -> None

Type text into an element, optionally with delay between keystrokes.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
text str

Text to type character by character.

required
delay int

Delay between keystrokes in milliseconds.

0
Source code in wavexis/backend/cdp.py
async def type_text(self, selector: str, text: str, delay: int = 0) -> None:
    """Type text into an element, optionally with delay between keystrokes.

    Args:
        selector: CSS selector for the target element.
        text: Text to type character by character.
        delay: Delay between keystrokes in milliseconds.
    """
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.dom.focus(node_id)
    for char in text:
        await session.input.dispatch_key_event(
            **{"type": "char"}, text=char
        )
        if delay > 0:
            await asyncio.sleep(delay / 1000)

fill async

fill(selector: str, value: str, auto_wait: bool = True) -> None

Fill an input element with a value (replaces existing content).

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
value str

Value to set in the input field.

required
auto_wait bool

If True, wait for element to be visible before filling.

True
Source code in wavexis/backend/cdp.py
async def fill(
    self, selector: str, value: str, auto_wait: bool = True
) -> None:
    """Fill an input element with a value (replaces existing content).

    Args:
        selector: CSS selector for the target element.
        value: Value to set in the input field.
        auto_wait: If True, wait for element to be visible before filling.
    """
    session = self._require_session()
    if auto_wait:
        await self._wait_for_element(selector)
    await self._scroll_into_view_if_needed(selector)
    escaped = json.dumps(selector)
    js = (
        f"(function(){{var el=document.querySelector('{escaped}');"
        f"if(!el)return false;el.focus();el.value='{value}';"
        f"el.dispatchEvent(new Event('input',{{bubbles:true}}));"
        f"el.dispatchEvent(new Event('change',{{bubbles:true}}));"
        f"return true;}})()"
    )
    result = await session.runtime.evaluate(js)
    if not result.get("result", {}).get("value"):
        raise ElementNotFoundError(selector)

select_option async

select_option(selector: str, value: str) -> None

Select an option in a element.

required value str

Option value to select.

required
Source code in wavexis/backend/cdp.py
async def select_option(self, selector: str, value: str) -> None:
    """Select an option in a <select> element by value.

    Args:
        selector: CSS selector for the <select> element.
        value: Option value to select.
    """
    session = self._require_session()
    escaped = json.dumps(selector)
    escaped_val = json.dumps(value)
    js = (
        f"(function(){{var el=document.querySelector('{escaped}');"
        f"if(!el)return false;el.value='{escaped_val}';"
        f"el.dispatchEvent(new Event('change',{{bubbles:true}}));"
        f"return true;}})()"
    )
    result = await session.runtime.evaluate(js)
    if not result.get("result", {}).get("value"):
        raise ElementNotFoundError(selector)

hover async

hover(selector: str, auto_wait: bool = True) -> None

Hover over an element matching a CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
auto_wait bool

If True, wait for element to be visible before hovering.

True
Source code in wavexis/backend/cdp.py
async def hover(self, selector: str, auto_wait: bool = True) -> None:
    """Hover over an element matching a CSS selector.

    Args:
        selector: CSS selector for the target element.
        auto_wait: If True, wait for element to be visible before hovering.
    """
    session = self._require_session()
    if auto_wait:
        await self._wait_for_element(selector)
    await self._scroll_into_view_if_needed(selector)
    x, y = await self._get_box_center(selector)
    await session.input.dispatch_mouse_event(
        **{"type": "mouseMoved"}, x=x, y=y
    )

key_press async

key_press(key: str) -> None

Press a keyboard key.

Parameters:

Name Type Description Default
key str

Key name (e.g. 'Enter', 'Tab', 'Escape').

required
Source code in wavexis/backend/cdp.py
async def key_press(self, key: str) -> None:
    """Press a keyboard key.

    Args:
        key: Key name (e.g. 'Enter', 'Tab', 'Escape').
    """
    session = self._require_session()
    key_map = {
        "Enter": {"key": "Enter", "code": "Enter", "windows_virtual_key_code": 13},
        "Tab": {"key": "Tab", "code": "Tab", "windows_virtual_key_code": 9},
        "Escape": {"key": "Escape", "code": "Escape", "windows_virtual_key_code": 27},
        "Space": {"key": " ", "code": "Space", "windows_virtual_key_code": 32},
        "Backspace": {"key": "Backspace", "code": "Backspace", "windows_virtual_key_code": 8},
    }
    key_info = key_map.get(key, {"key": key, "code": key})
    await session.input.dispatch_key_event(
        **{"type": "keyDown"}, **key_info
    )
    await session.input.dispatch_key_event(
        **{"type": "keyUp"}, **key_info
    )

drag async

drag(source: str, target: str) -> None

Drag an element from source selector to target selector.

Parameters:

Name Type Description Default
source str

CSS selector for the element to drag.

required
target str

CSS selector for the drop target.

required
Source code in wavexis/backend/cdp.py
async def drag(self, source: str, target: str) -> None:
    """Drag an element from source selector to target selector.

    Args:
        source: CSS selector for the element to drag.
        target: CSS selector for the drop target.
    """
    session = self._require_session()
    sx, sy = await self._get_box_center(source)
    tx, ty = await self._get_box_center(target)
    await session.input.dispatch_mouse_event(
        **{"type": "mousePressed"}, x=sx, y=sy, button="left", click_count=1
    )
    await session.input.dispatch_mouse_event(
        **{"type": "mouseMoved"}, x=tx, y=ty
    )
    await session.input.dispatch_mouse_event(
        **{"type": "mouseReleased"}, x=tx, y=ty, button="left", click_count=1
    )

tap async

tap(selector: str) -> None

Tap an element (touch emulation click).

Parameters:

Name Type Description Default
selector str

CSS selector for the target element.

required
Source code in wavexis/backend/cdp.py
async def tap(self, selector: str) -> None:
    """Tap an element (touch emulation click).

    Args:
        selector: CSS selector for the target element.
    """
    session = self._require_session()
    x, y = await self._get_box_center(selector)
    await session.input.dispatch_touch_event(
        **{"type": "touchStart"}, touch_points=[{"x": x, "y": y}]
    )
    await session.input.dispatch_touch_event(
        **{"type": "touchEnd"}, touch_points=[]
    )

set_files async

set_files(selector: str, files: list[str]) -> None

Set files on a file input element.

Parameters:

Name Type Description Default
selector str

CSS selector for the element.

required
files list[str]

List of absolute file paths to upload.

required
Source code in wavexis/backend/cdp.py
async def set_files(self, selector: str, files: list[str]) -> None:
    """Set files on a file input element.

    Args:
        selector: CSS selector for the <input type="file"> element.
        files: List of absolute file paths to upload.
    """
    session = self._require_session()
    node_id = await self._find_node(selector)
    await session.send(
        "DOM.setFileInputFiles",
        {"files": files, "nodeId": node_id},
    )

iframe_eval async

iframe_eval(iframe_selector: str, expression: str, await_promise: bool = False) -> Any

Evaluate a JavaScript expression inside an iframe.

Parameters:

Name Type Description Default
iframe_selector str

CSS selector for the