ferridriver-script 0.4.0

Sandboxed QuickJS scripting engine for ferridriver. Runs JS scripts against Page/Browser/Context with bound args, per-call isolation, scoped fs, and structured errors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
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
//! `PageJs`: JS wrapper around `ferridriver::Page`.
//!
//! Methods mirror `ferridriver::Page`'s public surface one-for-one; each is a
//! small delegation that converts `FerriError` into `rquickjs::Error` at the
//! boundary via [`super::convert::FerriResultExt`].

use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use ferridriver::Page;
use rquickjs::JsLifetime;
use rquickjs::class::Trace;

use ferridriver::options::WaitOptions;
use rquickjs::function::Opt;
use serde::Deserialize;

use crate::bindings::convert::{
  FerriResultExt, extract_page_function, init_script_from_js, quickjs_arg_to_serialized, serde_from_js,
  serialized_value_to_quickjs,
};
use crate::bindings::keyboard::KeyboardJs;
use crate::bindings::locator::LocatorJs;
use crate::bindings::mouse::MouseJs;

/// Shape of `waitForSelector` options accepted from JS.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct JsWaitOptions {
  state: Option<String>,
  timeout: Option<u64>,
}

pub(crate) fn parse_wait_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<WaitOptions> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let js: JsWaitOptions = serde_from_js(ctx, v)?;
      Ok(WaitOptions {
        state: js.state,
        timeout: js.timeout,
      })
    },
    _ => Ok(WaitOptions::default()),
  }
}

#[derive(serde::Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase", default)]
struct JsGotoOptions {
  wait_until: Option<String>,
  timeout: Option<u64>,
  referer: Option<String>,
}

fn parse_goto_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<Option<ferridriver::options::GotoOptions>> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let js: JsGotoOptions = serde_from_js(ctx, v)?;
      Ok(Some(ferridriver::options::GotoOptions {
        wait_until: js.wait_until,
        timeout: js.timeout,
        referer: js.referer,
      }))
    },
    _ => Ok(None),
  }
}

#[derive(serde::Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase", default)]
struct JsPageCloseOptions {
  run_before_unload: Option<bool>,
  reason: Option<String>,
}

/// Shape of `page.dragAndDrop` / `locator.dragTo` options. Mirrors
/// Playwright's `FrameDragAndDropOptions & TimeoutOptions` per
/// `/tmp/playwright/packages/playwright-core/types/types.d.ts:2486`.
#[derive(serde::Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase", default)]
pub(crate) struct JsDragAndDropOptions {
  force: Option<bool>,
  no_wait_after: Option<bool>,
  source_position: Option<JsPoint>,
  target_position: Option<JsPoint>,
  steps: Option<u32>,
  strict: Option<bool>,
  timeout: Option<u64>,
  trial: Option<bool>,
}

#[derive(serde::Deserialize, Debug, Default, Clone, Copy)]
pub(crate) struct JsPoint {
  x: f64,
  y: f64,
}

impl From<JsPoint> for ferridriver::options::Point {
  fn from(p: JsPoint) -> Self {
    Self { x: p.x, y: p.y }
  }
}

/// Parse the Playwright-shaped `emulateMedia` options bag from a
/// `rquickjs::Value`. Unlike `serde_from_js`, this walks the JS object
/// manually so we can distinguish three states for every field:
///
/// * absent → [`MediaOverride::Unchanged`]
/// * explicit `null` → [`MediaOverride::Disabled`]
/// * string value → [`MediaOverride::Set`]
///
/// serde-based deserialization conflates `undefined` and `null` into a
/// single `Option::None`, which breaks the Playwright null-disables-the-
/// override contract. See `/tmp/playwright/packages/playwright-core/types/types.d.ts:2580`
/// for the `T | null | undefined` shape we're mirroring.
fn parse_emulate_media_field<'js>(
  obj: &rquickjs::Object<'js>,
  key: &str,
) -> rquickjs::Result<ferridriver::options::MediaOverride> {
  use ferridriver::options::MediaOverride;
  if !obj.contains_key(key)? {
    return Ok(MediaOverride::Unchanged);
  }
  let val: rquickjs::Value<'js> = obj.get(key)?;
  if val.is_undefined() {
    Ok(MediaOverride::Unchanged)
  } else if val.is_null() {
    Ok(MediaOverride::Disabled)
  } else if let Some(s) = val.as_string() {
    Ok(MediaOverride::Set(s.to_string()?))
  } else {
    Err(rquickjs::Error::new_from_js_message(
      "emulateMedia options",
      "field",
      format!("{key}: expected null, undefined, or string"),
    ))
  }
}

pub(crate) fn parse_emulate_media_options<'js>(
  _ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<ferridriver::options::EmulateMediaOptions> {
  let Some(v) = value.0.filter(|v| !v.is_undefined() && !v.is_null()) else {
    return Ok(ferridriver::options::EmulateMediaOptions::default());
  };
  let Some(obj) = v.as_object() else {
    return Ok(ferridriver::options::EmulateMediaOptions::default());
  };
  Ok(ferridriver::options::EmulateMediaOptions {
    media: parse_emulate_media_field(obj, "media")?,
    color_scheme: parse_emulate_media_field(obj, "colorScheme")?,
    reduced_motion: parse_emulate_media_field(obj, "reducedMotion")?,
    forced_colors: parse_emulate_media_field(obj, "forcedColors")?,
    contrast: parse_emulate_media_field(obj, "contrast")?,
  })
}

pub(crate) fn parse_drag_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<Option<ferridriver::options::DragAndDropOptions>> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let js: JsDragAndDropOptions = serde_from_js(ctx, v)?;
      Ok(Some(ferridriver::options::DragAndDropOptions {
        force: js.force,
        no_wait_after: js.no_wait_after,
        source_position: js.source_position.map(Into::into),
        target_position: js.target_position.map(Into::into),
        steps: js.steps,
        strict: js.strict,
        timeout: js.timeout,
        trial: js.trial,
      }))
    },
    _ => Ok(None),
  }
}

fn parse_page_close_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<Option<ferridriver::options::PageCloseOptions>> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let js: JsPageCloseOptions = serde_from_js(ctx, v)?;
      Ok(Some(ferridriver::options::PageCloseOptions {
        run_before_unload: js.run_before_unload,
        reason: js.reason,
      }))
    },
    _ => Ok(None),
  }
}

/// Native registry for every page JS callback dispatched cross-task
/// (outside the QuickJS context, from a backend tokio task): `page.route`
/// handlers + URL predicates (keyed by registration id), `page.exposeFunction`
/// callbacks (keyed by binding name), and the single `page.startScreencast`
/// frame callback. All kept as `Persistent<Function>` in context
/// userdata — no `globalThis.__fd*`, exactly the `Persistent`/userdata
/// pattern the extension registry uses.
///
/// Single-threaded VM ⇒ `RefCell`, never `Arc`/`Mutex` (same rationale
/// as `BddUserData`).
#[derive(Default)]
pub(crate) struct PageCallbacks {
  route_handlers: rustc_hash::FxHashMap<u64, rquickjs::Persistent<rquickjs::Function<'static>>>,
  route_preds: rustc_hash::FxHashMap<u64, rquickjs::Persistent<rquickjs::Function<'static>>>,
  exposed: rustc_hash::FxHashMap<String, rquickjs::Persistent<rquickjs::Function<'static>>>,
  screencast: Option<rquickjs::Persistent<rquickjs::Function<'static>>>,
  /// `addLocatorHandler` JS callbacks, keyed by core-registry uid so the
  /// cross-task dispatch bridge can restore the persisted function.
  locator_handlers: rustc_hash::FxHashMap<u64, rquickjs::Persistent<rquickjs::Function<'static>>>,
}

impl PageCallbacks {
  pub(crate) fn insert_route_handler(&mut self, id: u64, f: rquickjs::Persistent<rquickjs::Function<'static>>) {
    self.route_handlers.insert(id, f);
  }

  pub(crate) fn insert_route_pred(&mut self, id: u64, f: rquickjs::Persistent<rquickjs::Function<'static>>) {
    self.route_preds.insert(id, f);
  }

  pub(crate) fn get_route_handler(&self, id: u64) -> Option<rquickjs::Persistent<rquickjs::Function<'static>>> {
    self.route_handlers.get(&id).cloned()
  }

  pub(crate) fn get_route_pred(&self, id: u64) -> Option<rquickjs::Persistent<rquickjs::Function<'static>>> {
    self.route_preds.get(&id).cloned()
  }

  pub(crate) fn route_preds_snapshot(&self) -> Vec<(u64, rquickjs::Persistent<rquickjs::Function<'static>>)> {
    self.route_preds.iter().map(|(k, v)| (*k, v.clone())).collect()
  }

  pub(crate) fn remove_route(&mut self, id: u64) {
    self.route_preds.remove(&id);
    self.route_handlers.remove(&id);
  }

  pub(crate) fn remove_locator_handler(&mut self, id: u64) {
    self.locator_handlers.remove(&id);
  }
}

pub(crate) struct PageCallbacksUd(std::cell::RefCell<PageCallbacks>);

// SAFETY: holds only `'static` data (`Persistent<…>` handles), so
// re-stating the unused `'js` lifetime is sound — identical rationale to
// `BddUserData` / `SessionAsyncCtx`.
#[allow(unsafe_code)]
unsafe impl rquickjs::JsLifetime<'_> for PageCallbacksUd {
  type Changed<'to> = PageCallbacksUd;
}

/// Ensure the page-callbacks userdata exists on this context.
/// Idempotent; called at `Session::create` and defensively from the
/// `page.route` / `exposeFunction` / `startScreencast` bindings.
pub(crate) fn ensure_page_callbacks(ctx: &rquickjs::Ctx<'_>) {
  if ctx.userdata::<PageCallbacksUd>().is_none() {
    let _ = ctx.store_userdata(PageCallbacksUd(std::cell::RefCell::new(PageCallbacks::default())));
  }
}

pub(crate) fn with_page_callbacks<R>(
  ctx: &rquickjs::Ctx<'_>,
  f: impl FnOnce(&mut PageCallbacks) -> R,
) -> rquickjs::Result<R> {
  ensure_page_callbacks(ctx);
  let ud = ctx.userdata::<PageCallbacksUd>().ok_or_else(|| {
    rquickjs::Error::new_from_js_message("page", "Error", "page callbacks registry missing".to_string())
  })?;
  let mut reg = ud.0.borrow_mut();
  Ok(f(&mut reg))
}

/// Stash an exposed-binding JS callback keyed by binding name. Shared
/// by `page.exposeFunction` and `context.exposeBinding` /
/// `context.exposeFunction` — both inject `window[name]`, so a single
/// name-keyed registry suffices. Exposed `pub(crate)` so the context
/// binding (in a sibling module) can reuse the same userdata.
pub(crate) fn insert_exposed_callback(
  ctx: &rquickjs::Ctx<'_>,
  name: String,
  cb: rquickjs::Persistent<rquickjs::Function<'static>>,
) -> rquickjs::Result<()> {
  with_page_callbacks(ctx, |r| r.exposed.insert(name, cb))?;
  Ok(())
}

/// Look up a previously stashed exposed-binding callback by name.
pub(crate) fn get_exposed_callback(
  ctx: &rquickjs::Ctx<'_>,
  name: &str,
) -> rquickjs::Result<Option<rquickjs::Persistent<rquickjs::Function<'static>>>> {
  with_page_callbacks(ctx, |r| r.exposed.get(name).cloned())
}

fn parse_unroute_behavior(behavior: &str) -> rquickjs::Result<ferridriver::options::UnrouteBehavior> {
  match behavior {
    "default" => Ok(ferridriver::options::UnrouteBehavior::Default),
    "wait" => Ok(ferridriver::options::UnrouteBehavior::Wait),
    "ignoreErrors" => Ok(ferridriver::options::UnrouteBehavior::IgnoreErrors),
    other => Err(rquickjs::Error::new_from_js_message(
      "unrouteAll options",
      "behavior",
      format!("invalid behavior {other:?} (expected 'wait', 'ignoreErrors', or 'default')"),
    )),
  }
}

/// Extract the `times` field from a `route(url, handler, { times })` options
/// bag. Absent/undefined options or a missing `times` yields `None`
/// (unlimited). Shared by `page.route` and `context.route`.
pub(crate) fn parse_route_times(
  options: &rquickjs::function::Opt<rquickjs::Value<'_>>,
) -> rquickjs::Result<Option<u32>> {
  let Some(v) = options.0.as_ref() else { return Ok(None) };
  if v.is_undefined() || v.is_null() {
    return Ok(None);
  }
  let Some(obj) = v.as_object() else { return Ok(None) };
  let t: rquickjs::Value<'_> = obj.get("times")?;
  if t.is_undefined() || t.is_null() {
    return Ok(None);
  }
  #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
  Ok(t.as_number().map(|n| if n < 0.0 { 0 } else { n as u32 }))
}

/// Parse the `{ url?, notFound? }` options bag for `routeFromHAR`. Shared by
/// `page.routeFromHAR` and `context.routeFromHAR`. `url` is a glob string.
pub(crate) fn parse_har_options(
  options: &rquickjs::function::Opt<rquickjs::Value<'_>>,
) -> rquickjs::Result<ferridriver::har::RouteFromHarOptions> {
  let mut out = ferridriver::har::RouteFromHarOptions::default();
  let Some(v) = options.0.as_ref() else { return Ok(out) };
  let Some(obj) = v.as_object() else { return Ok(out) };
  let url: rquickjs::Value<'_> = obj.get("url")?;
  if let Some(s) = url.as_string() {
    let glob = s.to_string()?;
    out.url = Some(
      ferridriver::url_matcher::UrlMatcher::glob(glob)
        .map_err(|e| rquickjs::Error::new_from_js_message("routeFromHAR", "url", format!("invalid url glob: {e}")))?,
    );
  }
  let nf: rquickjs::Value<'_> = obj.get("notFound")?;
  if let Some(s) = nf.as_string() {
    match s.to_string()?.as_str() {
      "fallback" => out.not_found = ferridriver::har::HarNotFound::Fallback,
      "abort" => out.not_found = ferridriver::har::HarNotFound::Abort,
      other => {
        return Err(rquickjs::Error::new_from_js_message(
          "routeFromHAR",
          "notFound",
          format!("invalid notFound {other:?} (expected 'abort' or 'fallback')"),
        ));
      },
    }
  }
  Ok(out)
}

/// JS-visible wrapper around [`ferridriver::Page`].
///
/// Held as `Arc<Page>` so the same page can be shared with the MCP session
/// while the script runs; dropping the wrapper does not close the page.
#[derive(JsLifetime, Trace)]
#[rquickjs::class(rename = "Page")]
pub struct PageJs {
  // rquickjs requires fields to implement Trace/JsLifetime; Arc<Page> does
  // not, and there's nothing inside a Page that holds JS values. Mark with
  // `#[qjs(skip_trace)]` so the macro skips tracing this field.
  #[qjs(skip_trace)]
  inner: Arc<Page>,
  /// `AsyncContext` used by `page.route` to dispatch JS callbacks
  /// from a separate tokio task back into the script's JS context.
  /// `None` only when the wrapper was constructed directly (e.g. by
  /// tests); the engine always installs PageJs via
  /// `install_page` which sets this field.
  #[qjs(skip_trace)]
  async_ctx: Option<rquickjs::AsyncContext>,
  /// Per-page route registration counter. Each `page.route(matcher, fn)`
  /// gets a unique numeric ID; the handler/predicate are stored in the
  /// native `RouteRegistry` userdata under that ID and the Rust handler
  /// dispatches by ID via the AsyncContext.
  #[qjs(skip_trace)]
  next_route_id: Arc<AtomicU64>,
  /// Core `UrlMatcher` registered for each function-predicate `page.route`,
  /// keyed by the same id as the native `RouteRegistry` handler/predicate
  /// entries. A predicate route registers an always-true matcher whose
  /// `Arc` identity lets `unroute(fn)` remove exactly that registration
  /// (core compares `UrlMatcher::Predicate` by `Arc::ptr_eq`). Shared so
  /// `route` and `unroute` on the same `Page` wrapper see one table.
  #[qjs(skip_trace)]
  route_matchers: Arc<std::sync::Mutex<rustc_hash::FxHashMap<u64, ferridriver::url_matcher::UrlMatcher>>>,
  /// Maps a handler locator's selector to the persisted-callback ids so
  /// `removeLocatorHandler` can drop them. (QuickJS `addLocatorHandler`
  /// itself is Unsupported -- see its binding -- so this normally stays empty.)
  #[qjs(skip_trace)]
  locator_handler_ids: Arc<std::sync::Mutex<rustc_hash::FxHashMap<String, Vec<u64>>>>,
}

impl PageJs {
  #[must_use]
  pub fn new(inner: Arc<Page>) -> Self {
    Self {
      inner,
      async_ctx: None,
      next_route_id: Arc::new(AtomicU64::new(0)),
      route_matchers: Arc::new(std::sync::Mutex::new(rustc_hash::FxHashMap::default())),
      locator_handler_ids: Arc::new(std::sync::Mutex::new(rustc_hash::FxHashMap::default())),
    }
  }

  #[must_use]
  pub fn new_with_async_ctx(inner: Arc<Page>, async_ctx: rquickjs::AsyncContext) -> Self {
    Self {
      inner,
      async_ctx: Some(async_ctx),
      next_route_id: Arc::new(AtomicU64::new(0)),
      route_matchers: Arc::new(std::sync::Mutex::new(rustc_hash::FxHashMap::default())),
      locator_handler_ids: Arc::new(std::sync::Mutex::new(rustc_hash::FxHashMap::default())),
    }
  }

  /// Clone of the wrapped `Arc<Page>` for cross-binding consumers
  /// (used by `expect()` to lift a `PageJs` into an assertion target).
  #[must_use]
  pub fn page_arc(&self) -> Arc<Page> {
    self.inner.clone()
  }

  #[must_use]
  pub fn page(&self) -> &Arc<Page> {
    &self.inner
  }
}

/// Build a `PageJs` for a page minted from script (`newPage`,
/// `locator.page()`, `frame.page()`), threading the session's
/// `AsyncContext` (stashed as userdata at `Session::create`) so
/// `page.route` / `page.exposeFunction` cross-task dispatch works on
/// script-launched browsers — not just the MCP-prebound page.
pub(crate) fn pagejs_for_ctx(ctx: &rquickjs::Ctx<'_>, page: Arc<Page>) -> PageJs {
  match ctx.userdata::<crate::engine::SessionAsyncCtx>() {
    Some(ud) => PageJs::new_with_async_ctx(page, ud.0.clone()),
    None => PageJs::new(page),
  }
}

#[rquickjs::methods]
impl PageJs {
  // ── Navigation ────────────────────────────────────────────────────────────

  /// Navigate to `url`. Accepts `{ waitUntil?, timeout?, referer? }` to
  /// mirror Playwright's `page.goto(url, options?)`.
  #[qjs(rename = "goto")]
  pub async fn goto<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    url: String,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Option<crate::bindings::network::ResponseJs>> {
    let opts = parse_goto_options(&ctx, options)?;
    let resp = self.inner.goto(&url, opts).await.into_js()?;
    Ok(resp.map(|r| crate::bindings::network::ResponseJs::new_with_page(r, self.inner.clone())))
  }

  /// Reload the current page. Accepts the same option bag as `goto`.
  #[qjs(rename = "reload")]
  pub async fn reload<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Option<crate::bindings::network::ResponseJs>> {
    let opts = parse_goto_options(&ctx, options)?;
    let resp = self.inner.reload(opts).await.into_js()?;
    Ok(resp.map(|r| crate::bindings::network::ResponseJs::new_with_page(r, self.inner.clone())))
  }

  /// Navigate back in history. Accepts the same option bag as `goto`.
  #[qjs(rename = "goBack")]
  pub async fn go_back<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Option<crate::bindings::network::ResponseJs>> {
    let opts = parse_goto_options(&ctx, options)?;
    let resp = self.inner.go_back(opts).await.into_js()?;
    Ok(resp.map(|r| crate::bindings::network::ResponseJs::new_with_page(r, self.inner.clone())))
  }

  /// Navigate forward in history. Accepts the same option bag as `goto`.
  #[qjs(rename = "goForward")]
  pub async fn go_forward<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Option<crate::bindings::network::ResponseJs>> {
    let opts = parse_goto_options(&ctx, options)?;
    let resp = self.inner.go_forward(opts).await.into_js()?;
    Ok(resp.map(|r| crate::bindings::network::ResponseJs::new_with_page(r, self.inner.clone())))
  }

  /// Current URL of the page.
  /// Playwright: `page.url(): string` — synchronous.
  #[qjs(rename = "url")]
  pub fn url(&self) -> String {
    self.inner.url()
  }

  /// Document title.
  #[qjs(rename = "title")]
  pub async fn title(&self) -> rquickjs::Result<String> {
    self.inner.title().await.into_js()
  }

  /// Playwright: `page.video(): null | Video` —
  /// `/tmp/playwright/packages/playwright-core/types/types.d.ts:4756`.
  /// Returns a live `Video` handle when the owning context was
  /// created with `recordVideo`, or `null` otherwise.
  #[qjs(rename = "video")]
  pub fn video<'js>(&self, ctx: rquickjs::Ctx<'js>) -> rquickjs::Result<rquickjs::Value<'js>> {
    use rquickjs::class::Class;
    match self.inner.video() {
      Some(video) => {
        let wrapper = crate::bindings::video::VideoJs::new(video);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      None => Ok(rquickjs::Value::new_null(ctx)),
    }
  }

  /// Full HTML content of the page.
  #[qjs(rename = "content")]
  pub async fn content(&self) -> rquickjs::Result<String> {
    self.inner.content().await.into_js()
  }

  /// Replace the page's HTML with `html`.
  #[qjs(rename = "setContent")]
  pub async fn set_content(&self, html: String) -> rquickjs::Result<()> {
    self.inner.set_content(&html).await.into_js()
  }

  /// Register a JS snippet to run on every new document before any page
  /// script executes. Mirrors Playwright's
  /// `page.addInitScript(script, arg)` — see
  /// `/tmp/playwright/packages/playwright-core/src/client/page.ts:520`.
  /// Accepts `Function | string | { path?, content? }` + optional `arg`
  /// exactly like the NAPI binding; all lowering runs in Rust core via
  /// [`ferridriver::options::evaluation_script`].
  #[qjs(rename = "addInitScript")]
  pub async fn add_init_script<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    script: rquickjs::Value<'js>,
    arg: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    let (init, arg_json) = init_script_from_js(&ctx, script, arg.0)?;
    let disposable = self.inner.add_init_script(init, arg_json).await.into_js()?;
    let instance =
      rquickjs::class::Class::instance(ctx.clone(), crate::bindings::disposable::DisposableJs::new(disposable))?;
    rquickjs::IntoJs::into_js(instance, &ctx)
  }

  /// Remove a previously-registered init script by identifier.
  #[qjs(rename = "removeInitScript")]
  pub async fn remove_init_script(&self, identifier: String) -> rquickjs::Result<()> {
    self.inner.remove_init_script(&identifier).await.into_js()
  }

  /// Full page rendered as clean Markdown (headings, lists, links, tables
  /// preserved; chrome and boilerplate stripped).
  #[qjs(rename = "markdown")]
  pub async fn markdown(&self) -> rquickjs::Result<String> {
    self.inner.markdown().await.into_js()
  }

  /// Wait for an element matching `selector`. Optional `options` object
  /// accepts `{ state?: 'visible'|'hidden'|'attached'|'stable', timeout?: ms }`.
  /// Resolves when the condition is met; throws on timeout.
  #[qjs(rename = "waitForSelector")]
  pub async fn wait_for_selector<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = parse_wait_options(&ctx, options)?;
    self.inner.wait_for_selector(&selector, opts).await.into_js()
  }

  // ── Locators ──────────────────────────────────────────────────────────────

  /// Playwright: `page.querySelector(selector): Promise<ElementHandle | null>`.
  /// Mints a lifecycle [`crate::bindings::element_handle::ElementHandleJs`]
  /// pinned to the first element matching `selector`, or `null` when no
  /// element matches. Callers `dispose()` the handle when done to
  /// release the backend remote.
  #[qjs(rename = "querySelector")]
  pub async fn query_selector(
    &self,
    selector: String,
  ) -> rquickjs::Result<Option<crate::bindings::element_handle::ElementHandleJs>> {
    let inner = self.inner.query_selector(&selector).await.into_js()?;
    Ok(inner.map(crate::bindings::element_handle::ElementHandleJs::new))
  }

  /// Playwright `$` shortcut for [`Self::query_selector`].
  #[qjs(rename = "$")]
  pub async fn dollar(
    &self,
    selector: String,
  ) -> rquickjs::Result<Option<crate::bindings::element_handle::ElementHandleJs>> {
    self.query_selector(selector).await
  }

  /// Playwright: `page.querySelectorAll(selector): Promise<ElementHandle[]>`.
  #[qjs(rename = "querySelectorAll")]
  pub async fn query_selector_all(
    &self,
    selector: String,
  ) -> rquickjs::Result<Vec<crate::bindings::element_handle::ElementHandleJs>> {
    let inner_handles = self.inner.query_selector_all(&selector).await.into_js()?;
    Ok(
      inner_handles
        .into_iter()
        .map(crate::bindings::element_handle::ElementHandleJs::new)
        .collect(),
    )
  }

  /// Playwright `$$` shortcut for [`Self::query_selector_all`].
  #[qjs(rename = "$$")]
  pub async fn dollar_dollar(
    &self,
    selector: String,
  ) -> rquickjs::Result<Vec<crate::bindings::element_handle::ElementHandleJs>> {
    self.query_selector_all(selector).await
  }

  /// Playwright: `page.evaluate(pageFunction, arg?): Promise<R>`.
  /// `pageFunction` accepts a string or a JS function; rich return
  /// types (`Date` / `RegExp` / `BigInt` / `URL` / `Error` / typed
  /// arrays / `NaN` / `±Infinity` / `undefined` / `-0`) arrive as
  /// native JS, matching Playwright's `parseResult`.
  #[qjs(rename = "evaluate")]
  pub async fn evaluate<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    page_function: rquickjs::Value<'js>,
    arg: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    let (source, is_fn) = extract_page_function(&ctx, page_function)?;
    let serialized = quickjs_arg_to_serialized(&ctx, arg.0)?;
    let result = self.inner.evaluate(&source, serialized, is_fn).await.into_js()?;
    serialized_value_to_quickjs(&ctx, &result)
  }

  /// Playwright: `page.evaluateHandle(pageFunction, arg?): Promise<JSHandle>`.
  #[qjs(rename = "evaluateHandle")]
  pub async fn evaluate_handle<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    page_function: rquickjs::Value<'js>,
    arg: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<crate::bindings::js_handle::JSHandleJs> {
    let (source, is_fn) = extract_page_function(&ctx, page_function)?;
    let serialized = quickjs_arg_to_serialized(&ctx, arg.0)?;
    let handle = self.inner.evaluate_handle(&source, serialized, is_fn).await.into_js()?;
    Ok(crate::bindings::js_handle::JSHandleJs::new(handle))
  }

  /// Playwright: `page.locator(selector, options?: LocatorOptions): Locator`.
  /// Thin delegator to Rust core's `Page::locator`.
  #[qjs(rename = "locator")]
  pub fn locator<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<LocatorJs> {
    let parsed = crate::bindings::locator::parse_locator_options_public(&ctx, options, true)?;
    let opts = ferridriver::options::FilterOptions {
      has_text: parsed.has_text,
      has_not_text: parsed.has_not_text,
      has: parsed.has,
      has_not: parsed.has_not,
      visible: parsed.visible,
    };
    let filter = if crate::bindings::locator::is_empty_filter(&opts) {
      None
    } else {
      Some(opts)
    };
    Ok(LocatorJs::new(self.inner.locator(&selector, filter)))
  }

  /// Locate elements by ARIA role. Accepts `{ name: string | RegExp,
  /// exact, checked, disabled, expanded, level, pressed, selected,
  /// includeHidden }` via the options bag.
  #[qjs(rename = "getByRole")]
  pub fn get_by_role(
    &self,
    role: String,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let opts = parse_role_options(options)?;
    Ok(LocatorJs::new(self.inner.get_by_role(&role, &opts)))
  }

  /// Locate elements containing the given text. Accepts `string | RegExp`.
  #[qjs(rename = "getByText")]
  pub fn get_by_text(
    &self,
    text: rquickjs::Value<'_>,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(text)?;
    let opts = parse_text_options(options);
    Ok(LocatorJs::new(self.inner.get_by_text(&t, &opts)))
  }

  /// Locate form controls by associated label text.
  #[qjs(rename = "getByLabel")]
  pub fn get_by_label(
    &self,
    text: rquickjs::Value<'_>,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(text)?;
    let opts = parse_text_options(options);
    Ok(LocatorJs::new(self.inner.get_by_label(&t, &opts)))
  }

  /// Locate inputs by placeholder text.
  #[qjs(rename = "getByPlaceholder")]
  pub fn get_by_placeholder(
    &self,
    text: rquickjs::Value<'_>,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(text)?;
    let opts = parse_text_options(options);
    Ok(LocatorJs::new(self.inner.get_by_placeholder(&t, &opts)))
  }

  /// Locate images/media by alt text.
  #[qjs(rename = "getByAltText")]
  pub fn get_by_alt_text(
    &self,
    text: rquickjs::Value<'_>,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(text)?;
    let opts = parse_text_options(options);
    Ok(LocatorJs::new(self.inner.get_by_alt_text(&t, &opts)))
  }

  /// Locate elements by `title` attribute text.
  #[qjs(rename = "getByTitle")]
  pub fn get_by_title(
    &self,
    text: rquickjs::Value<'_>,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(text)?;
    let opts = parse_text_options(options);
    Ok(LocatorJs::new(self.inner.get_by_title(&t, &opts)))
  }

  /// Locate elements by `data-testid`. Accepts `string | RegExp`.
  #[qjs(rename = "getByTestId")]
  pub fn get_by_test_id(&self, test_id: rquickjs::Value<'_>) -> rquickjs::Result<LocatorJs> {
    let t = string_or_regex_from_js(test_id)?;
    Ok(LocatorJs::new(self.inner.get_by_test_id(&t)))
  }

  // ── Interaction ───────────────────────────────────────────────────────────

  /// Click the first element matching `selector`. Accepts Playwright's
  /// full `PageClickOptions` bag.
  #[qjs(rename = "click")]
  pub async fn click<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_click_options(&ctx, options)?;
    self.inner.click(&selector, opts).await.into_js()
  }

  /// Double-click the first element matching `selector`. Accepts
  /// Playwright's full `PageDblClickOptions` bag.
  #[qjs(rename = "dblclick")]
  pub async fn dblclick<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_dblclick_options(&ctx, options)?;
    self.inner.dblclick(&selector, opts).await.into_js()
  }

  /// Fill `value` into the input matching `selector`. Accepts
  /// Playwright's full `PageFillOptions` bag.
  #[qjs(rename = "fill")]
  pub async fn fill<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    value: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_fill_options(&ctx, options)?;
    self.inner.fill(&selector, &value, opts).await.into_js()
  }

  /// Type `text` into the input matching `selector`. Accepts
  /// Playwright's full `PageTypeOptions` bag.
  ///
  /// Exposed as `type` in JS (matches Playwright) — Rust renames to avoid
  /// the `type` keyword.
  #[qjs(rename = "type")]
  pub async fn type_<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    text: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_type_options(&ctx, options)?;
    self.inner.r#type(&selector, &text, opts).await.into_js()
  }

  /// Press `key` on the element matching `selector`. Accepts Playwright's
  /// full `PagePressOptions` bag.
  #[qjs(rename = "press")]
  pub async fn press<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    key: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_press_options(&ctx, options)?;
    self.inner.press(&selector, &key, opts).await.into_js()
  }

  /// `page.focus(selector, options?)`.
  #[qjs(rename = "focus")]
  pub async fn focus(
    &self,
    selector: String,
    _options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<()> {
    self.inner.focus(&selector).await.into_js()
  }

  /// Hover the first element matching `selector`. Accepts Playwright's
  /// full `PageHoverOptions` bag.
  #[qjs(rename = "hover")]
  pub async fn hover<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_hover_options(&ctx, options)?;
    self.inner.hover(&selector, opts).await.into_js()
  }

  /// Dispatch a DOM event on the first element matching `selector`.
  /// Mirrors Playwright's `page.dispatchEvent(selector, type, eventInit?, options?)`.
  #[qjs(rename = "dispatchEvent")]
  pub async fn dispatch_event<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    event_type: String,
    event_init: rquickjs::function::Opt<rquickjs::Value<'js>>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let init_json = match event_init.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => {
        Some(crate::bindings::convert::serde_from_js::<serde_json::Value>(&ctx, v)?)
      },
      _ => None,
    };
    let opts = crate::bindings::convert::parse_dispatch_event_options(&ctx, options)?;
    self
      .inner
      .dispatch_event(&selector, &event_type, init_json, opts)
      .await
      .into_js()
  }

  /// Tap (touch) the first element matching `selector`. Accepts
  /// Playwright's full `PageTapOptions` bag.
  #[qjs(rename = "tap")]
  pub async fn tap<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_tap_options(&ctx, options)?;
    self.inner.tap(&selector, opts).await.into_js()
  }

  /// Check a checkbox matching `selector`. Accepts Playwright's full
  /// `PageCheckOptions` bag.
  #[qjs(rename = "check")]
  pub async fn check<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_check_options(&ctx, options)?;
    self.inner.check(&selector, opts).await.into_js()
  }

  /// Uncheck a checkbox matching `selector`. Accepts Playwright's full
  /// `PageUncheckOptions` bag.
  #[qjs(rename = "uncheck")]
  pub async fn uncheck<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_check_options(&ctx, options)?;
    self.inner.uncheck(&selector, opts).await.into_js()
  }

  /// Set the checked state of a checkbox/radio matching `selector`.
  /// Accepts Playwright's full `PageSetCheckedOptions` bag.
  #[qjs(rename = "setChecked")]
  pub async fn set_checked<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    checked: bool,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = crate::bindings::convert::parse_check_options(&ctx, options)?;
    self.inner.set_checked(&selector, checked, opts).await.into_js()
  }

  /// Select options on the `<select>` matching `selector`. Returns the
  /// values of the selected options. Accepts Playwright's full
  /// `string | string[] | { value?, label?, index? } | Array<...>` union.
  #[qjs(rename = "selectOption")]
  pub async fn select_option<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    values: rquickjs::Value<'js>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Vec<String>> {
    let values = crate::bindings::convert::parse_select_option_values(&ctx, values)?;
    let opts = crate::bindings::convert::parse_select_option_options(&ctx, options)?;
    self.inner.select_option(&selector, values, opts).await.into_js()
  }

  // ── Info ──────────────────────────────────────────────────────────────────

  /// Text content of the first element matching `selector` (or `null`).
  #[qjs(rename = "textContent")]
  pub async fn text_content(&self, selector: String) -> rquickjs::Result<Option<String>> {
    self.inner.text_content(&selector).await.into_js()
  }

  /// `innerText` of the first element matching `selector`.
  #[qjs(rename = "innerText")]
  pub async fn inner_text(&self, selector: String) -> rquickjs::Result<String> {
    self.inner.inner_text(&selector).await.into_js()
  }

  /// `innerHTML` of the first element matching `selector`.
  #[qjs(rename = "innerHTML")]
  pub async fn inner_html(&self, selector: String) -> rquickjs::Result<String> {
    self.inner.inner_html(&selector).await.into_js()
  }

  /// Current input value of the first element matching `selector`.
  #[qjs(rename = "inputValue")]
  pub async fn input_value(&self, selector: String) -> rquickjs::Result<String> {
    self.inner.input_value(&selector).await.into_js()
  }

  /// Get attribute `name` on the first element matching `selector`
  /// (or `null` if the attribute is absent).
  #[qjs(rename = "getAttribute")]
  pub async fn get_attribute(&self, selector: String, name: String) -> rquickjs::Result<Option<String>> {
    self.inner.get_attribute(&selector, &name).await.into_js()
  }

  /// Whether the first element matching `selector` is visible.
  #[qjs(rename = "isVisible")]
  pub async fn is_visible(&self, selector: String) -> rquickjs::Result<bool> {
    self.inner.is_visible(&selector).await.into_js()
  }

  /// Whether the first element matching `selector` is hidden.
  #[qjs(rename = "isHidden")]
  pub async fn is_hidden(&self, selector: String) -> rquickjs::Result<bool> {
    self.inner.is_hidden(&selector).await.into_js()
  }

  /// Whether the first element matching `selector` is enabled.
  #[qjs(rename = "isEnabled")]
  pub async fn is_enabled(&self, selector: String) -> rquickjs::Result<bool> {
    self.inner.is_enabled(&selector).await.into_js()
  }

  /// Whether the first element matching `selector` is disabled.
  #[qjs(rename = "isDisabled")]
  pub async fn is_disabled(&self, selector: String) -> rquickjs::Result<bool> {
    self.inner.is_disabled(&selector).await.into_js()
  }

  /// Whether the first checkbox matching `selector` is checked.
  #[qjs(rename = "isChecked")]
  pub async fn is_checked(&self, selector: String) -> rquickjs::Result<bool> {
    self.inner.is_checked(&selector).await.into_js()
  }

  // ── Mouse / keyboard namespaces (Playwright parity) ──────────────────────

  /// `page.mouse.*` namespace: `click`, `dblclick`, `down`, `up`, `wheel`.
  /// Exposed as a JS property, matching Playwright.
  #[qjs(get, rename = "mouse")]
  pub fn mouse(&self) -> MouseJs {
    MouseJs::new(self.inner.clone())
  }

  /// `page.keyboard.*` namespace: `down`, `up`, `press` (no selector; acts on
  /// the currently focused element). Exposed as a JS property.
  #[qjs(get, rename = "keyboard")]
  pub fn keyboard(&self) -> KeyboardJs {
    KeyboardJs::new(self.inner.clone())
  }

  /// ferridriver-specific (NOT Playwright): click at viewport
  /// coordinates without a selector. Playwright equivalent: `mouse.click(x, y)`.
  #[qjs(rename = "clickAt")]
  pub async fn click_at(&self, x: f64, y: f64) -> rquickjs::Result<()> {
    self.inner.click_at(x, y).await.into_js()
  }

  /// ferridriver-specific (NOT Playwright): interpolated mouse move
  /// from `(fromX, fromY)` to `(toX, toY)` in `steps` points. Playwright
  /// equivalent: `mouse.move(x, y, { steps })`.
  #[qjs(rename = "moveMouseSmooth")]
  pub async fn move_mouse_smooth(
    &self,
    from_x: f64,
    from_y: f64,
    to_x: f64,
    to_y: f64,
    steps: u32,
  ) -> rquickjs::Result<()> {
    self
      .inner
      .move_mouse_smooth(from_x, from_y, to_x, to_y, steps)
      .await
      .into_js()
  }

  /// Drag from the source selector to the target selector. Accepts
  /// Playwright's `FrameDragAndDropOptions & TimeoutOptions` bag:
  /// `{ force?, noWaitAfter?, sourcePosition?, targetPosition?, steps?, strict?, timeout?, trial? }`.
  #[qjs(rename = "dragAndDrop")]
  pub async fn drag_and_drop<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    source: String,
    target: String,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = parse_drag_options(&ctx, options)?;
    self.inner.drag_and_drop(&source, &target, opts).await.into_js()
  }

  // ── File input ────────────────────────────────────────────────────────────

  /// Attach files to a `<input type="file">` selector. Accepts
  /// Playwright's full `string | string[] | FilePayload | FilePayload[]`
  /// union plus the `PageSetInputFilesOptions` bag.
  #[qjs(rename = "setInputFiles")]
  pub async fn set_input_files<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: String,
    files: rquickjs::Value<'js>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let files = crate::bindings::convert::parse_input_files(&ctx, files)?;
    let opts = crate::bindings::convert::parse_set_input_files_options(&ctx, options)?;
    self.inner.set_input_files(&selector, files, opts).await.into_js()
  }

  // ── Emulation (page-scoped Playwright API) ───────────────────────────────

  /// Override the viewport size for this page. Playwright public:
  /// `page.setViewportSize({ width, height })`.
  /// Playwright: `page.setViewportSize({ width, height })` — a single
  /// object, not two positional numbers.
  #[qjs(rename = "setViewportSize")]
  pub async fn set_viewport_size<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    size: rquickjs::Value<'js>,
  ) -> rquickjs::Result<()> {
    #[derive(serde::Deserialize)]
    struct Size {
      width: i64,
      height: i64,
    }
    let s: Size = crate::bindings::convert::serde_from_js(&ctx, size)?;
    self.inner.set_viewport_size(s.width, s.height).await.into_js()
  }

  /// Emulate media features. Accepts Playwright's
  /// `{ media?, colorScheme?, reducedMotion?, forcedColors?, contrast? }`
  /// option bag — each call is a partial update layered on top of the
  /// page's persistent emulated-media state.
  #[qjs(rename = "emulateMedia")]
  pub async fn emulate_media<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let opts = parse_emulate_media_options(&ctx, options)?;
    self.inner.emulate_media(&opts).await.into_js()
  }

  // ── Screenshots / PDF (return raw bytes; pair with `artifacts.writeBytes`) ─

  /// Capture the page as a PNG (raw bytes — Uint8Array in JS). Pair with
  /// `await artifacts.writeBytes('page.png', bytes)` to save to disk.
  /// Optional `options` accept `{ fullPage?: boolean, format?: 'png'|'jpeg'|'webp', quality?: number }`.
  #[qjs(rename = "screenshot")]
  pub async fn screenshot<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Vec<u8>> {
    let opts = parse_screenshot_options(&ctx, options)?;
    self.inner.screenshot(opts).await.into_js()
  }

  /// Capture a single element as PNG bytes.
  #[qjs(rename = "screenshotElement")]
  pub async fn screenshot_element(&self, selector: String) -> rquickjs::Result<Vec<u8>> {
    self.inner.screenshot_element(&selector).await.into_js()
  }

  /// Render the current page as a PDF (raw bytes). Accepts a Playwright-shape
  /// options object: `{ format?, landscape?, printBackground?, scale?, ... }`.
  /// Pair with `await artifacts.writeBytes('page.pdf', bytes)` to save.
  #[qjs(rename = "pdf")]
  pub async fn pdf<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<Vec<u8>> {
    let opts = parse_pdf_options(&ctx, options)?;
    self.inner.pdf(opts).await.into_js()
  }

  // ── Lifecycle ─────────────────────────────────────────────────────────────

  /// Close the page. Accepts `{ runBeforeUnload?, reason? }` to mirror
  /// Playwright's `page.close(options?)`.
  #[qjs(rename = "close")]
  pub async fn close<'js>(&self, ctx: rquickjs::Ctx<'js>, options: Opt<rquickjs::Value<'js>>) -> rquickjs::Result<()> {
    let opts = parse_page_close_options(&ctx, options)?;
    self.inner.close(opts).await.into_js()
  }

  /// Set the default timeout for all non-navigation operations
  /// (milliseconds). Mirrors Playwright's `page.setDefaultTimeout(timeout)`.
  #[qjs(rename = "setDefaultTimeout")]
  pub fn set_default_timeout(&self, ms: u64) {
    self.inner.set_default_timeout(ms);
  }

  /// Set the default timeout for navigation-family operations
  /// (`goto`, `reload`, `goBack`, `goForward`, `waitForUrl`). Mirrors
  /// Playwright's `page.setDefaultNavigationTimeout(timeout)`.
  #[qjs(rename = "setDefaultNavigationTimeout")]
  pub fn set_default_navigation_timeout(&self, ms: u64) {
    self.inner.set_default_navigation_timeout(ms);
  }

  /// Whether the page has been closed.
  #[qjs(rename = "isClosed")]
  pub fn is_closed(&self) -> bool {
    self.inner.is_closed()
  }

  // ── Network interception ─────────────────────────────────────────────────

  /// Mirrors Playwright `page.route(url, handler)`. Registers a JS
  /// callback to intercept requests matching `url` (`string | RegExp`).
  /// The callback receives a `Route` instance and must call exactly one
  /// of `route.fulfill()`, `route.continue()`, or `route.abort()` to
  /// resume the request.
  ///
  /// Cross-task dispatch: the Rust route handler runs inside the
  /// backend's network listener (a separate tokio task from the
  /// script's JS context). The handler stashes the JS callback in the
  /// native `RouteRegistry` userdata keyed by ID at registration
  /// time; when a request matches, the handler spawns a task that
  /// `async_with`s back into the script's `AsyncContext`, looks up the
  /// callback by ID, and invokes it with a fresh `RouteJs` wrapper.
  /// `rquickjs`'s scheduler serialises the dispatch against the
  /// script's own `await` points so JS-side state stays consistent.
  #[qjs(rename = "route")]
  pub async fn route<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    url: rquickjs::Value<'js>,
    handler: rquickjs::Function<'js>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    let times = parse_route_times(&options)?;
    let async_ctx = self.async_ctx.clone().ok_or_else(|| {
      rquickjs::Error::new_from_js_message(
        "page.route",
        "Error",
        "page.route requires the script engine's AsyncContext (install_page)".to_string(),
      )
    })?;
    let id = self.next_route_id.fetch_add(1, Ordering::Relaxed);
    let saved_handler = rquickjs::Persistent::save(&ctx, handler);
    with_page_callbacks(&ctx, |r| r.route_handlers.insert(id, saved_handler))?;

    // A JS predicate is `!Send` and core matches on the CDP recv task,
    // so it can't ride `UrlMatcher::Predicate`. Register an always-true
    // matcher with unique `Arc` identity (lets `unroute(fn)` drop
    // exactly it via `Arc::ptr_eq`); evaluate the predicate in the
    // dispatch bridge and continue the request unmodified on falsy.
    let has_predicate = url.as_function().is_some();
    let matcher = if let Some(pred) = url.as_function() {
      let saved_pred = rquickjs::Persistent::save(&ctx, pred.clone());
      with_page_callbacks(&ctx, |r| r.route_preds.insert(id, saved_pred))?;
      let m = ferridriver::url_matcher::UrlMatcher::predicate(|_| true);
      self
        .route_matchers
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(id, m.clone());
      m
    } else {
      url_value_to_matcher(&ctx, url)?
    };

    // LIMITATION (persistent-session VMs): this closure captures a clone
    // of the session's `AsyncContext`. Core route registrations live on
    // the page (independent of the JS VM), so they outlive a poisoning
    // rebuild / LRU eviction of the session VM. After such a discard the
    // closure dispatches into the now-detached old context; the new VM's
    // scripts cannot see or `unroute` it. It stays memory-safe (the Arc
    // keeps the old context alive) and fail-open (the route's `Drop`
    // continues the request if dispatch can't reach JS), and it clears
    // when the page closes. Fully reconciling it needs a cross-backend
    // "unroute all" on VM discard — tracked, not yet implemented.
    let rust_handler: ferridriver::route::RouteHandler = std::sync::Arc::new(move |route| {
      let async_ctx = async_ctx.clone();
      // Cross-task dispatch: spawn a tokio task that grabs the
      // AsyncContext lock and calls the JS callback (restored from the
      // native route registry by id). Errors are swallowed because the
      // route's own `Drop` (fail-open continue) covers the case where
      // dispatch can't reach JS.
      tokio::spawn(async move {
        use rquickjs::class::Class;
        let _: rquickjs::Result<()> = rquickjs::async_with!(async_ctx => |ctx| {
          if has_predicate {
            let pred = with_page_callbacks(&ctx, |r| r.route_preds.get(&id).cloned())?
              .ok_or_else(|| rquickjs::Error::new_from_js_message("page.route", "Error", "route predicate gone".to_string()))?
              .restore(&ctx)?;
            let url_ctor: rquickjs::function::Constructor<'_> = ctx.globals().get("URL")?;
            let url_obj: rquickjs::Value<'_> = url_ctor.construct((route.request().url.clone(),))?;
            if !call_predicate_truthy(&pred, url_obj, &ctx).await? {
              route.continue_route(ferridriver::route::ContinueOverrides::default());
              return Ok(());
            }
          }
          let f = with_page_callbacks(&ctx, |r| r.route_handlers.get(&id).cloned())?
            .ok_or_else(|| rquickjs::Error::new_from_js_message("page.route", "Error", "route handler gone".to_string()))?
            .restore(&ctx)?;
          let route_class = Class::instance(ctx.clone(), crate::bindings::network::RouteJs::new(route))?;
          let _: rquickjs::Value<'_> = f.call((route_class,))?;
          Ok(())
        })
        .await;
      });
    });

    let disposable = self.inner.route(matcher, rust_handler, times).await.into_js()?;
    let instance =
      rquickjs::class::Class::instance(ctx.clone(), crate::bindings::disposable::DisposableJs::new(disposable))?;
    rquickjs::IntoJs::into_js(instance, &ctx)
  }

  /// Playwright: `page.routeFromHAR(har, options?)`. Replay-only.
  #[qjs(rename = "routeFromHAR")]
  pub async fn route_from_har(
    &self,
    har: String,
    options: rquickjs::function::Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<()> {
    let opts = parse_har_options(&options)?;
    self
      .inner
      .route_from_har(std::path::Path::new(&har), opts)
      .await
      .into_js()
  }

  /// `page.unroute(string | RegExp | ((url: URL) => boolean))`. A
  /// predicate is matched by `===` identity against the function passed
  /// to `route`, then its always-true core matcher is dropped by `Arc`
  /// identity so sibling predicate routes survive.
  #[qjs(rename = "unroute")]
  pub async fn unroute<'js>(&self, ctx: rquickjs::Ctx<'js>, url: rquickjs::Value<'js>) -> rquickjs::Result<()> {
    if let Some(pred) = url.as_function() {
      // Find every id whose stored predicate is identical (===) to the
      // passed function, then drop its core registration + registry
      // entries. Restoring each saved predicate yields a handle to the
      // same underlying object, so `Value` `PartialEq` (tag + pointer)
      // is still strict `===` identity.
      let saved: Vec<(u64, rquickjs::Persistent<rquickjs::Function<'static>>)> =
        with_page_callbacks(&ctx, |r| r.route_preds.iter().map(|(k, v)| (*k, v.clone())).collect())?;
      let mut victims: Vec<u64> = Vec::new();
      for (id, sp) in saved {
        let stored = sp.restore(&ctx)?;
        if stored.as_value() == pred.as_value() {
          victims.push(id);
        }
      }
      for id in victims {
        let m = self
          .route_matchers
          .lock()
          .unwrap_or_else(std::sync::PoisonError::into_inner)
          .remove(&id);
        if let Some(m) = m {
          self.inner.unroute(&m).await.into_js()?;
        }
        with_page_callbacks(&ctx, |r| {
          r.route_preds.remove(&id);
          r.route_handlers.remove(&id);
        })?;
      }
      return Ok(());
    }
    let matcher = url_value_to_matcher(&ctx, url)?;
    self.inner.unroute(&matcher).await.into_js()
  }

  /// `page.unrouteAll(options?: { behavior?: 'wait' | 'ignoreErrors' | 'default' })`.
  /// Removes every route registered via `page.route`, clearing the script-side
  /// predicate/handler tables too.
  #[qjs(rename = "unrouteAll")]
  pub async fn unroute_all<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<()> {
    let behavior = match options.0.and_then(rquickjs::Value::into_object) {
      Some(obj) => match obj.get::<_, Option<String>>("behavior")? {
        Some(b) => Some(parse_unroute_behavior(&b)?),
        None => None,
      },
      None => None,
    };
    self.inner.unroute_all(behavior).await.into_js()?;
    self
      .route_matchers
      .lock()
      .unwrap_or_else(std::sync::PoisonError::into_inner)
      .clear();
    with_page_callbacks(&ctx, |r| {
      r.route_preds.clear();
      r.route_handlers.clear();
    })?;
    Ok(())
  }

  /// `page.addLocatorHandler(locator, handler, options?: { times?, noWaitAfter? })`.
  /// Registers `handler` to run whenever `locator` becomes visible during an
  /// actionability wait (dismissing overlays/modals). Mirrors Playwright
  /// `client/page.ts:397`.
  ///
  /// The JS handler runs cross-task via the session `AsyncContext` (same
  /// bridge as `page.route`): the core checkpoint awaits a oneshot that the
  /// spawned dispatch task fulfils once the handler (and any returned
  /// promise) settles, so the original action only resumes afterwards.
  #[qjs(rename = "addLocatorHandler")]
  pub fn add_locator_handler(
    &self,
    _locator: rquickjs::Class<'_, LocatorJs>,
    _handler: rquickjs::Function<'_>,
    _options: Opt<rquickjs::Value<'_>>,
  ) -> rquickjs::Result<()> {
    // The handler must run *during* an in-progress action's actionability
    // wait. In the QuickJS scripting engine every action executes inside an
    // exclusive `async_with` over the single session VM, so a nested
    // handler callback can never acquire the VM until the action finishes --
    // invoking it would deadlock. Playwright sidesteps this with a
    // client/server split; ferridriver-script has none, so this is a typed
    // Unsupported rather than a hang. The core + NAPI layers support it fully.
    ferridriver::error::Result::<()>::Err(ferridriver::error::FerriError::unsupported(
      "page.addLocatorHandler is not available in the QuickJS scripting engine \
       (handlers cannot fire during an in-VM action without deadlocking the \
       single-threaded VM); use the NAPI/core API for locator handlers",
    ))
    .into_js()
  }

  /// `page.removeLocatorHandler(locator)`. Drops every handler registered for
  /// `locator` (by selector) and releases the persisted JS callbacks. Mirrors
  /// Playwright `client/page.ts:423`.
  #[qjs(rename = "removeLocatorHandler")]
  pub fn remove_locator_handler<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    locator: rquickjs::Class<'js, LocatorJs>,
  ) -> rquickjs::Result<()> {
    let core_locator = locator.borrow().inner_ref().clone();
    self.inner.remove_locator_handler(&core_locator);
    let ids = self
      .locator_handler_ids
      .lock()
      .unwrap_or_else(std::sync::PoisonError::into_inner)
      .remove(core_locator.selector())
      .unwrap_or_default();
    with_page_callbacks(&ctx, |r| {
      for id in ids {
        r.remove_locator_handler(id);
      }
    })?;
    Ok(())
  }

  /// `page.pickLocator(): Promise<Locator>`. Highlights elements under the
  /// cursor and resolves with a Locator for the element the user clicks.
  #[qjs(rename = "pickLocator")]
  pub async fn pick_locator(&self) -> rquickjs::Result<LocatorJs> {
    let loc = self.inner.pick_locator().await.into_js()?;
    Ok(LocatorJs::new(loc))
  }

  /// `page.cancelPickLocator(): Promise<void>`.
  #[qjs(rename = "cancelPickLocator")]
  pub async fn cancel_pick_locator(&self) -> rquickjs::Result<()> {
    self.inner.cancel_pick_locator().await.into_js()
  }

  /// `page.hideHighlight(): Promise<void>`.
  #[qjs(rename = "hideHighlight")]
  pub async fn hide_highlight(&self) -> rquickjs::Result<()> {
    self.inner.hide_highlight().await.into_js()
  }

  // ── Network lifecycle waits ──────────────────────────────────────────────
  //
  // Mirror Playwright's `page.waitForRequest` / `page.waitForResponse` /
  // `page.waitForEvent('websocket')` — return live `RequestJs` /
  // `ResponseJs` / `WebSocketJs` so callers can inspect headers, body,
  // failure, etc.

  /// `page.waitForRequest(string | RegExp | ((r: Request) => boolean |
  /// Promise<boolean>), options?)`.
  #[qjs(rename = "waitForRequest")]
  pub async fn wait_for_request<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    url: rquickjs::Value<'js>,
    timeout_ms: Opt<f64>,
  ) -> rquickjs::Result<crate::bindings::network::RequestJs> {
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let timeout = timeout_ms.0.map(|t| t as u64);
    if let Some(pred) = url.as_function() {
      let t = timeout.unwrap_or_else(|| self.inner.default_timeout());
      return wait_request_predicate(ctx.clone(), self.inner.clone(), pred.clone(), t).await;
    }
    let matcher = url_value_to_matcher(&ctx, url)?;
    let req = self.inner.wait_for_request(matcher, timeout).await.into_js()?;
    Ok(crate::bindings::network::RequestJs::new_with_page(
      req,
      self.inner.clone(),
    ))
  }

  /// `page.waitForResponse(string | RegExp | ((r: Response) => boolean |
  /// Promise<boolean>), options?)`.
  #[qjs(rename = "waitForResponse")]
  pub async fn wait_for_response<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    url: rquickjs::Value<'js>,
    timeout_ms: Opt<f64>,
  ) -> rquickjs::Result<crate::bindings::network::ResponseJs> {
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let timeout = timeout_ms.0.map(|t| t as u64);
    if let Some(pred) = url.as_function() {
      let t = timeout.unwrap_or_else(|| self.inner.default_timeout());
      return wait_response_predicate(ctx.clone(), self.inner.clone(), pred.clone(), t).await;
    }
    let matcher = url_value_to_matcher(&ctx, url)?;
    let resp = self.inner.wait_for_response(matcher, timeout).await.into_js()?;
    Ok(crate::bindings::network::ResponseJs::new_with_page(
      resp,
      self.inner.clone(),
    ))
  }

  /// Mirrors Playwright `page.waitForEvent(event, options?)`. Dispatches
  /// on the event name and returns the live class for the lifecycle
  /// events (`Request` / `Response` / `WebSocket`), or a snapshot object
  /// for simpler events. The overloaded return keeps the Playwright-
  /// canonical call shape — scripts write `await page.waitForEvent('websocket')`
  /// and receive a real `WebSocket` instance.
  /// Playwright: `page.waitForLoadState(state?: 'load' |
  /// 'domcontentloaded' | 'networkidle', options?)`. Defaults to
  /// `'load'`. Thin delegator to `Page::wait_for_load_state`.
  #[qjs(rename = "waitForLoadState")]
  pub async fn wait_for_load_state(&self, state: Opt<String>) -> rquickjs::Result<()> {
    use crate::bindings::convert::FerriResultExt;
    self.inner.wait_for_load_state(state.0.as_deref()).await.into_js()
  }

  /// Playwright: `page.waitForURL(url: string | RegExp | (url:URL) =>
  /// boolean, options?)`. Thin delegator to `Page::wait_for_url`
  /// (a function predicate is reduced to an always-true matcher; the
  /// function check is enforced by the core polling against the
  /// current URL).
  #[qjs(rename = "waitForURL")]
  pub async fn wait_for_url<'js>(&self, ctx: rquickjs::Ctx<'js>, url: rquickjs::Value<'js>) -> rquickjs::Result<()> {
    use crate::bindings::convert::FerriResultExt;
    let matcher = url_value_to_matcher(&ctx, url)?;
    self.inner.wait_for_url(matcher).await.into_js()
  }

  /// Playwright: `page.waitForFunction(pageFunction: Function|string,
  /// arg?, options?: { timeout?, polling? })`. Function values get
  /// `String(fn)` (Playwright parity) and are evaluated as IIFEs
  /// inside the page. Returns the truthy value the function resolved
  /// to.
  #[qjs(rename = "waitForFunction")]
  pub async fn wait_for_function<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    page_function: rquickjs::Value<'js>,
    _arg: Opt<rquickjs::Value<'js>>,
    options: Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    #[derive(serde::Deserialize, Default)]
    #[serde(rename_all = "camelCase", default)]
    struct JsOpts {
      timeout: Option<u64>,
    }
    let opts: JsOpts = match options.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => crate::bindings::convert::serde_from_js(&ctx, v)?,
      _ => JsOpts::default(),
    };
    let (src, is_fn) = crate::bindings::convert::extract_page_function(&ctx, page_function)?;
    // For a function: invoke it as `(<src>)()` so the body's return is
    // the polled value. For a string: use as-is (the user passes an
    // expression string, like Playwright).
    let expr = if is_fn.unwrap_or(false) {
      format!("({src})()")
    } else {
      src
    };
    let v = self
      .inner
      .wait_for_function(&expr, opts.timeout)
      .await
      .map_err(|e| crate::bindings::convert::to_rq_error(&e))?;
    crate::bindings::convert::json_to_js(&ctx, &v)
  }

  #[qjs(rename = "waitForEvent")]
  pub async fn wait_for_event<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    event: String,
    timeout_ms: Opt<f64>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    use rquickjs::class::Class;
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let timeout = timeout_ms.0.unwrap_or(30_000.0) as u64;
    let event_lc = event.to_ascii_lowercase();

    // `dialog` bypasses the broadcast — it registers a one-shot
    // handler on the per-page `DialogManager` so the claim is
    // synchronous at `did_open` time (mirrors Playwright's
    // `addDialogHandler` + `dialogDidOpen` flow exactly).
    if event_lc == "dialog" {
      let dialog = self
        .inner
        .wait_for_dialog(timeout)
        .await
        .map_err(|e| rquickjs::Error::new_from_js_message("Page.waitForEvent", "Error", e.to_string()))?;
      let wrapper = crate::bindings::dialog::DialogJs::new(dialog);
      let instance = Class::instance(ctx.clone(), wrapper)?;
      return rquickjs::IntoJs::into_js(instance, &ctx);
    }
    // Same pattern for `filechooser` — one-shot handler on the
    // per-page `FileChooserManager` so the claim is synchronous with
    // the backend event arrival.
    if event_lc == "filechooser" {
      let chooser = self
        .inner
        .wait_for_file_chooser(timeout)
        .await
        .map_err(|e| rquickjs::Error::new_from_js_message("Page.waitForEvent", "Error", e.to_string()))?;
      let wrapper = crate::bindings::file_chooser::FileChooserJs::new(chooser);
      let instance = Class::instance(ctx.clone(), wrapper)?;
      return rquickjs::IntoJs::into_js(instance, &ctx);
    }
    // And for `download` — same one-shot handler pattern via the
    // per-page `DownloadManager`.
    if event_lc == "download" {
      let download = self
        .inner
        .wait_for_download(timeout)
        .await
        .map_err(|e| rquickjs::Error::new_from_js_message("Page.waitForEvent", "Error", e.to_string()))?;
      let wrapper = crate::bindings::download::DownloadJs::new(download);
      let instance = Class::instance(ctx.clone(), wrapper)?;
      return rquickjs::IntoJs::into_js(instance, &ctx);
    }

    let name = event_lc.clone();
    let ev = self
      .inner
      .events()
      .wait_for(move |e| match_event_name(&name, e), timeout)
      .await
      .map_err(|e| rquickjs::Error::new_from_js_message("Page.waitForEvent", "Error", e.to_string()))?;
    match ev {
      ferridriver::events::PageEvent::WebSocket(ws) => {
        let wrapper = crate::bindings::network::WebSocketJs::new(ws);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::Request(req)
      | ferridriver::events::PageEvent::RequestFinished(req)
      | ferridriver::events::PageEvent::RequestFailed(req) => {
        let wrapper = crate::bindings::network::RequestJs::new_with_page(req, self.inner.clone());
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::Response(resp) => {
        let wrapper = crate::bindings::network::ResponseJs::new_with_page(resp, self.inner.clone());
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::Dialog(dialog) => {
        // Reached via broadcast when a `page.events().on("dialog", cb)`
        // listener is also present — fall through to deliver the
        // live handle.
        let wrapper = crate::bindings::dialog::DialogJs::new(dialog);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::FileChooser(chooser) => {
        let wrapper = crate::bindings::file_chooser::FileChooserJs::new(chooser);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::Download(download) => {
        let wrapper = crate::bindings::download::DownloadJs::new(download);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      ferridriver::events::PageEvent::Console(msg) => {
        let wrapper = crate::bindings::console_message::ConsoleMessageJs::new(msg);
        let instance = Class::instance(ctx.clone(), wrapper)?;
        rquickjs::IntoJs::into_js(instance, &ctx)
      },
      // Playwright: `page.waitForEvent('pageerror'): Promise<Error>`.
      // Emit a native JS `Error` (not the `WebError` wrapper — that
      // class only exists for the context-scoped `'weberror'` surface).
      ferridriver::events::PageEvent::PageError(err) => {
        crate::bindings::web_error::build_native_error(&ctx, err.error())
      },
      other => page_event_to_js(&ctx, &other),
    }
  }

  // ── Frames (sync, Playwright parity — task 3.8) ─────────────────────
  //
  // Mirrors `/tmp/playwright/packages/playwright-core/src/client/page.ts:258-275`
  // — `mainFrame`, `frames`, `frame(selector)` are all sync and read
  // from the page-owned [`ferridriver::frame_cache::FrameCache`].

  /// Main frame of this page. Playwright: `page.mainFrame(): Frame`.
  /// Always returns a Frame — the cache is seeded inside `Page::new` /
  /// `Page::with_context` before the Page is handed out.
  #[qjs(rename = "mainFrame")]
  pub fn main_frame(&self) -> crate::bindings::frame::FrameJs {
    crate::bindings::frame::FrameJs::new(self.inner.main_frame())
  }

  /// All non-detached frames on the page. Playwright:
  /// `page.frames(): Frame[]`.
  #[qjs(rename = "frames")]
  pub fn frames(&self) -> Vec<crate::bindings::frame::FrameJs> {
    self
      .inner
      .frames()
      .into_iter()
      .map(crate::bindings::frame::FrameJs::new)
      .collect()
  }

  /// Playwright: `page.frameLocator(selector): FrameLocator`. Targets
  /// an `<iframe>` matching the selector at the page's main-frame
  /// scope.
  #[qjs(rename = "frameLocator")]
  pub fn frame_locator(&self, selector: String) -> crate::bindings::frame_locator::FrameLocatorJs {
    crate::bindings::frame_locator::FrameLocatorJs::new(self.inner.frame_locator(&selector))
  }

  /// Locate a frame by name or URL. Accepts Playwright's union:
  /// `frame(string | { name?: string; url?: string })`.
  ///
  /// Distinct null/undefined handling (like emulateMedia in task 3.24)
  /// is not required here — both absent and explicit-null mean "no
  /// filter on this field", which matches Playwright's optional-field
  /// semantics.
  #[qjs(rename = "frame")]
  pub fn frame<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    selector: rquickjs::Value<'js>,
  ) -> rquickjs::Result<Option<crate::bindings::frame::FrameJs>> {
    let core_sel = if let Some(s) = selector.as_string() {
      ferridriver::options::FrameSelector::by_name(s.to_string()?)
    } else if let Some(obj) = selector.as_object() {
      let read = |key: &str| -> rquickjs::Result<Option<String>> {
        let v: rquickjs::Value<'_> = obj
          .get(key)
          .unwrap_or_else(|_| rquickjs::Value::new_undefined(ctx.clone()));
        if v.is_undefined() || v.is_null() {
          Ok(None)
        } else if let Some(s) = v.as_string() {
          Ok(Some(s.to_string()?))
        } else {
          Ok(None)
        }
      };
      ferridriver::options::FrameSelector {
        name: read("name")?,
        url: read("url")?,
      }
    } else {
      return Ok(None);
    };

    if core_sel.is_empty() {
      return Ok(None);
    }
    Ok(self.inner.frame(core_sel).map(crate::bindings::frame::FrameJs::new))
  }

  /// Playwright: `page.touchscreen: Touchscreen`.
  #[qjs(rename = "touchscreen", get)]
  pub fn touchscreen(&self) -> TouchscreenJs {
    TouchscreenJs {
      page: self.inner.clone(),
    }
  }

  /// ferridriver-specific (NOT Playwright): structured AI snapshot
  /// `{ full: string, incremental?: string, refMap: Record<string, number> }`.
  /// Playwright's public accessibility API is `ariaSnapshot` (string);
  /// this richer shape feeds the MCP server's incremental tracking.
  #[qjs(rename = "snapshotForAI")]
  pub async fn snapshot_for_ai<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<rquickjs::Value<'js>> {
    let core_opts = match options.0 {
      None => ferridriver::snapshot::SnapshotOptions::default(),
      Some(v) if v.is_undefined() || v.is_null() => ferridriver::snapshot::SnapshotOptions::default(),
      Some(v) => {
        #[derive(serde::Deserialize, Default)]
        #[serde(rename_all = "camelCase", default)]
        struct JsSnap {
          depth: Option<i32>,
          track: Option<String>,
        }
        let parsed: JsSnap = crate::bindings::convert::serde_from_js(&ctx, v)?;
        ferridriver::snapshot::SnapshotOptions {
          depth: parsed.depth,
          track: parsed.track,
        }
      },
    };
    let snap = self.inner.snapshot_for_ai(core_opts).await.into_js()?;
    let obj = rquickjs::Object::new(ctx.clone())?;
    obj.set("full", snap.full)?;
    if let Some(inc) = snap.incremental {
      obj.set("incremental", inc)?;
    }
    let ref_map = rquickjs::Object::new(ctx.clone())?;
    for (k, v) in snap.ref_map {
      ref_map.set(k, v as f64)?;
    }
    obj.set("refMap", ref_map)?;
    rquickjs::IntoJs::into_js(obj, &ctx)
  }

  /// Playwright `page.ariaSnapshot(options?): Promise<string>`.
  #[qjs(rename = "ariaSnapshot")]
  pub async fn aria_snapshot<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    options: rquickjs::function::Opt<rquickjs::Value<'js>>,
  ) -> rquickjs::Result<String> {
    let core_opts = match options.0 {
      Some(v) if !v.is_undefined() && !v.is_null() => {
        #[derive(serde::Deserialize, Default)]
        #[serde(rename_all = "camelCase", default)]
        struct JsSnap {
          depth: Option<i32>,
          track: Option<String>,
        }
        let p: JsSnap = crate::bindings::convert::serde_from_js(&ctx, v)?;
        ferridriver::snapshot::SnapshotOptions {
          depth: p.depth,
          track: p.track,
        }
      },
      _ => ferridriver::snapshot::SnapshotOptions::default(),
    };
    self.inner.aria_snapshot(core_opts).await.into_js()
  }

  /// Playwright: `page.exposeFunction(name, callback)`. Binds
  /// `window[name]` to a page-side proxy that asynchronously invokes
  /// `callback(args)` in the script context.
  ///
  /// The callback receives the args as a single array. The page-side
  /// call resolves to `null` since the script-side callback runs
  /// asynchronously (Rust core's `ExposedFn` is sync + JSON-in/out;
  /// QuickJS dispatch is async-only).
  #[qjs(rename = "exposeFunction")]
  pub async fn expose_function<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    name: String,
    callback: rquickjs::Function<'js>,
  ) -> rquickjs::Result<()> {
    let async_ctx = self.async_ctx.clone().ok_or_else(|| {
      rquickjs::Error::new_from_js_message(
        "page.exposeFunction",
        "Error",
        "page.exposeFunction requires the script engine's AsyncContext (install_page)".to_string(),
      )
    })?;
    // Stash the JS callback in the native page-callbacks registry keyed
    // by binding name — cross-task dispatch (the Rust `ExposedFn` runs
    // outside the QuickJS context) restores it by name via `async_with!`.
    let saved = rquickjs::Persistent::save(&ctx, callback);
    with_page_callbacks(&ctx, |r| r.exposed.insert(name.clone(), saved))?;

    let cb: ferridriver::events::ExposedFn = std::sync::Arc::new({
      let name = name.clone();
      move |args: Vec<serde_json::Value>| {
        let async_ctx = async_ctx.clone();
        let name = name.clone();
        // Playwright delivers the callback's return value (awaiting a
        // returned Promise) to the page-side caller. Run the JS
        // callback on the engine context via `async_with`, await it if
        // it returns a thenable, convert to JSON and hand it back so
        // the backend resolves the page binding with the REAL value —
        // not `null` (the previous fire-and-forget behaviour was a
        // Playwright incompatibility).
        Box::pin(async move {
          let out: rquickjs::Result<serde_json::Value> = rquickjs::async_with!(async_ctx => |ctx| {
            let f = with_page_callbacks(&ctx, |r| r.exposed.get(&name).cloned())?
              .ok_or_else(|| {
                rquickjs::Error::new_from_js_message(
                  "page.exposeFunction",
                  "Error",
                  "exposed callback gone".to_string(),
                )
              })?
              .restore(&ctx)?;
            // Playwright spreads the page-side call arguments into the
            // callback: `window.fn(a, b)` -> `callback(a, b)` (see
            // playwright-core client/page.ts `(...args) => callback(...args)`).
            // Build a spread arg list, not a single array.
            let mut call_args = rquickjs::function::Args::new_unsized(ctx.clone());
            for v in args {
              // `json_to_js` (NOT `serde_to_js`): a transitive dep
              // force-enables `serde_json/arbitrary_precision`, under
              // which rquickjs-serde turns every number into a
              // `{$serde_json::private::Number}` object. The AP-safe
              // walker keeps numbers as JS numbers.
              call_args.push_arg(crate::bindings::convert::json_to_js(&ctx, &v)?)?;
            }
            let mp: rquickjs::promise::MaybePromise<'_> = call_args.apply(&f)?;
            let res = mp.into_future::<rquickjs::Value<'_>>().await?;
            // Round-trip through QuickJS `JSON.stringify` + serde_json's
            // own parser — AP-safe both ways (a non-serde_json
            // deserializer mis-handles numbers under
            // `arbitrary_precision`). `undefined`/function -> null.
            let json = match ctx.json_stringify(res)? {
              Some(s) => serde_json::from_str(&s.to_string()?).unwrap_or(serde_json::Value::Null),
              None => serde_json::Value::Null,
            };
            Ok(json)
          })
          .await;
          out.unwrap_or(serde_json::Value::Null)
        })
      }
    });
    self.inner.expose_function(&name, cb).await.into_js()
  }

  /// ferridriver-specific (NOT Playwright): `startScreencast(quality,
  /// maxWidth, maxHeight, callback)`. Callback receives `{ frame:
  /// Uint8Array, timestamp: number }` per frame. Backed by CDP
  /// `Page.startScreencast`; no Playwright client equivalent.
  #[qjs(rename = "startScreencast")]
  pub async fn start_screencast<'js>(
    &self,
    ctx: rquickjs::Ctx<'js>,
    quality: u8,
    max_width: u32,
    max_height: u32,
    callback: rquickjs::Function<'js>,
  ) -> rquickjs::Result<()> {
    let async_ctx = self.async_ctx.clone().ok_or_else(|| {
      rquickjs::Error::new_from_js_message(
        "page.startScreencast",
        "Error",
        "page.startScreencast requires the script engine's AsyncContext (install_page)".to_string(),
      )
    })?;
    let saved = rquickjs::Persistent::save(&ctx, callback);
    with_page_callbacks(&ctx, |r| r.screencast = Some(saved))?;
    // `start_screencast` returns `(rx, shutdown_tx)`. The QuickJS
    // binding doesn't expose a stop hook here; the shutdown signal is
    // dropped (which Chrome's stop-screencast path will subsequently
    // see via teardown), and we forward frames until the listener
    // exits on its own.
    let (mut rx, _shutdown) = self
      .inner
      .start_screencast(quality, max_width, max_height)
      .await
      .into_js()?;
    tokio::spawn(async move {
      while let Some((bytes, ts)) = rx.recv().await {
        let _: rquickjs::Result<()> = rquickjs::async_with!(async_ctx => |ctx| {
          let f = with_page_callbacks(&ctx, |r| r.screencast.clone())?
            .ok_or_else(|| rquickjs::Error::new_from_js_message("page.startScreencast", "Error", "screencast callback gone".to_string()))?
            .restore(&ctx)?;
          let payload = rquickjs::Object::new(ctx.clone())?;
          let buf = rquickjs::TypedArray::<u8>::new(ctx.clone(), bytes)?;
          payload.set("frame", buf)?;
          payload.set("timestamp", ts)?;
          let _: rquickjs::Value<'_> = f.call((payload,))?;
          Ok(())
        })
        .await;
      }
    });
    Ok(())
  }

  /// ferridriver-specific (NOT Playwright): stop the screencast
  /// started by `startScreencast`.
  #[qjs(rename = "stopScreencast")]
  pub async fn stop_screencast(&self) -> rquickjs::Result<()> {
    self.inner.stop_screencast().await.into_js()
  }
}

/// Playwright `Touchscreen`. Construct via `page.touchscreen`.
#[derive(rquickjs::JsLifetime, rquickjs::class::Trace)]
#[rquickjs::class(rename = "Touchscreen")]
pub struct TouchscreenJs {
  #[qjs(skip_trace)]
  page: std::sync::Arc<ferridriver::Page>,
}

#[rquickjs::methods]
impl TouchscreenJs {
  /// Playwright: `touchscreen.tap(x, y)`.
  #[qjs(rename = "tap")]
  pub async fn tap(&self, x: f64, y: f64) -> rquickjs::Result<()> {
    self.page.touchscreen().tap(x, y).await.into_js()
  }
}

/// Shape of `page.screenshot` options accepted from JS. Full Playwright
/// `PageScreenshotOptions` surface per
/// `/tmp/playwright/packages/playwright-core/types/types.d.ts:23280`.
#[derive(Debug, Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct JsScreenshotOptions {
  animations: Option<String>,
  caret: Option<String>,
  clip: Option<JsClipRect>,
  full_page: Option<bool>,
  #[serde(rename = "type")]
  format: Option<String>,
  // `mask` is NOT decoded here: Playwright takes `Locator[]`, and a
  // `LocatorJs` class instance is not serde-deserialisable. It is read
  // manually from the options object via `parse_mask_locators` before
  // this struct is built.
  #[serde(skip)]
  _mask_placeholder: (),
  mask_color: Option<String>,
  omit_background: Option<bool>,
  path: Option<String>,
  quality: Option<i64>,
  scale: Option<String>,
  style: Option<String>,
  timeout: Option<u64>,
}

#[derive(Debug, Default, Deserialize, Clone, Copy)]
struct JsClipRect {
  x: f64,
  y: f64,
  width: f64,
  height: f64,
}

impl From<JsClipRect> for ferridriver::options::ClipRect {
  fn from(c: JsClipRect) -> Self {
    Self {
      x: c.x,
      y: c.y,
      width: c.width,
      height: c.height,
    }
  }
}

/// Read `mask: Locator[]` from the screenshot options object. Each entry
/// must be a `LocatorJs` class instance (Playwright's `mask?: Locator[]`);
/// the core `Locator` is cloned out so the selector string is extracted
/// Rust-side before backend dispatch.
fn parse_mask_locators<'js>(obj: &rquickjs::Object<'js>) -> rquickjs::Result<Vec<ferridriver::Locator>> {
  let v: rquickjs::Value<'js> = obj.get("mask")?;
  if v.is_undefined() || v.is_null() {
    return Ok(Vec::new());
  }
  let arr = v.into_array().ok_or_else(|| {
    rquickjs::Error::new_from_js_message("screenshot options", "mask", "expected an array of Locator")
  })?;
  let mut out = Vec::with_capacity(arr.len());
  for item in arr.iter::<rquickjs::Value<'js>>() {
    let item = item?;
    if let Ok(class) = rquickjs::Class::<LocatorJs>::from_value(&item) {
      out.push(class.borrow().inner_ref().clone());
    } else {
      return Err(rquickjs::Error::new_from_js_message(
        "screenshot options",
        "mask",
        "each mask entry must be a Locator instance",
      ));
    }
  }
  Ok(out)
}

fn parse_screenshot_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<ferridriver::options::ScreenshotOptions> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let mask = match v.as_object() {
        Some(obj) => parse_mask_locators(obj)?,
        None => Vec::new(),
      };
      let js: JsScreenshotOptions = serde_from_js(ctx, v)?;
      Ok(ferridriver::options::ScreenshotOptions {
        animations: js.animations,
        caret: js.caret,
        clip: js.clip.map(Into::into),
        full_page: js.full_page,
        format: js.format,
        mask,
        mask_color: js.mask_color,
        omit_background: js.omit_background,
        path: js.path.map(std::path::PathBuf::from),
        quality: js.quality,
        scale: js.scale,
        style: js.style,
        timeout: js.timeout,
      })
    },
    _ => Ok(ferridriver::options::ScreenshotOptions::default()),
  }
}

/// Subset of Playwright's `PDFOptions` exposed to scripts. Path fields and
/// advanced page-range/margin controls are not wired yet; users who need
/// those can use `page.evaluate` with `window.print` or extend here.
#[derive(Debug, Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct JsPdfOptions {
  format: Option<String>,
  landscape: Option<bool>,
  print_background: Option<bool>,
  scale: Option<f64>,
  display_header_footer: Option<bool>,
  header_template: Option<String>,
  footer_template: Option<String>,
  page_ranges: Option<String>,
  prefer_css_page_size: Option<bool>,
  outline: Option<bool>,
  tagged: Option<bool>,
}

fn parse_pdf_options<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<ferridriver::options::PdfOptions> {
  match value.0 {
    Some(v) if !v.is_undefined() && !v.is_null() => {
      let js: JsPdfOptions = serde_from_js(ctx, v)?;
      Ok(ferridriver::options::PdfOptions {
        format: js.format,
        path: None,
        scale: js.scale,
        display_header_footer: js.display_header_footer,
        header_template: js.header_template,
        footer_template: js.footer_template,
        print_background: js.print_background,
        landscape: js.landscape,
        page_ranges: js.page_ranges,
        width: None,
        height: None,
        margin: None,
        prefer_css_page_size: js.prefer_css_page_size,
        outline: js.outline,
        tagged: js.tagged,
      })
    },
    _ => Ok(ferridriver::options::PdfOptions::default()),
  }
}

fn match_event_name(name: &str, ev: &ferridriver::events::PageEvent) -> bool {
  use ferridriver::events::PageEvent;
  matches!(
    (name, ev),
    ("console", PageEvent::Console(_))
      | ("request", PageEvent::Request(_))
      | ("response", PageEvent::Response(_))
      | ("requestfinished", PageEvent::RequestFinished(_))
      | ("requestfailed", PageEvent::RequestFailed(_))
      | ("websocket", PageEvent::WebSocket(_))
      | ("dialog", PageEvent::Dialog(_))
      | ("filechooser", PageEvent::FileChooser(_))
      | ("frameattached", PageEvent::FrameAttached(_))
      | ("framedetached", PageEvent::FrameDetached { .. })
      | ("framenavigated", PageEvent::FrameNavigated(_))
      | ("load", PageEvent::Load)
      | ("domcontentloaded", PageEvent::DomContentLoaded)
      | ("close", PageEvent::Close)
      | ("pageerror", PageEvent::PageError(_))
      | ("download", PageEvent::Download(_))
  )
}

/// Build the `page.waitForEvent` payload JS object directly — no
/// serde_json::Value middle allocation. `FrameAttached`/`Navigated`
/// serialise their `FrameInfo` through rquickjs-serde (also direct).
fn page_event_to_js<'js>(
  ctx: &rquickjs::Ctx<'js>,
  ev: &ferridriver::events::PageEvent,
) -> rquickjs::Result<rquickjs::Value<'js>> {
  use ferridriver::events::PageEvent;
  let obj = || rquickjs::Object::new(ctx.clone());
  match ev {
    PageEvent::Console(msg) => {
      let loc = msg.location();
      let o = obj()?;
      o.set("type", msg.type_str())?;
      o.set("text", msg.text())?;
      let l = obj()?;
      l.set("url", loc.url.as_str())?;
      l.set("lineNumber", f64::from(loc.line_number))?;
      l.set("columnNumber", f64::from(loc.column_number))?;
      o.set("location", l)?;
      o.set("timestamp", msg.timestamp())?;
      o.set("argsCount", msg.args().len() as f64)?;
      Ok(o.into_value())
    },
    PageEvent::Dialog(d) => {
      let o = obj()?;
      o.set("type", d.dialog_type().as_str())?;
      o.set("message", d.message())?;
      o.set("defaultValue", d.default_value())?;
      Ok(o.into_value())
    },
    PageEvent::FileChooser(fc) => {
      let o = obj()?;
      o.set("isMultiple", fc.is_multiple())?;
      Ok(o.into_value())
    },
    PageEvent::FrameAttached(f) | PageEvent::FrameNavigated(f) => crate::bindings::convert::serde_to_js(ctx, f),
    PageEvent::FrameDetached { frame_id } => {
      let o = obj()?;
      o.set("frameId", frame_id.as_str())?;
      Ok(o.into_value())
    },
    PageEvent::Download(d) => {
      let o = obj()?;
      o.set("url", d.url())?;
      o.set("suggestedFilename", d.suggested_filename())?;
      Ok(o.into_value())
    },
    PageEvent::Load => {
      let o = obj()?;
      o.set("type", "load")?;
      Ok(o.into_value())
    },
    PageEvent::DomContentLoaded => {
      let o = obj()?;
      o.set("type", "domcontentloaded")?;
      Ok(o.into_value())
    },
    PageEvent::Close => {
      let o = obj()?;
      o.set("type", "close")?;
      Ok(o.into_value())
    },
    PageEvent::PageError(err) => {
      let details = err.error();
      let o = obj()?;
      o.set("name", details.name.as_str())?;
      o.set("message", details.message.as_str())?;
      o.set("stack", details.stack.as_str())?;
      Ok(o.into_value())
    },
    _ => Ok(rquickjs::Value::new_null(ctx.clone())),
  }
}

/// ECMAScript `ToBoolean` for a predicate's return value.
fn js_truthy(v: &rquickjs::Value<'_>) -> bool {
  if v.is_undefined() || v.is_null() {
    return false;
  }
  if let Some(b) = v.as_bool() {
    return b;
  }
  if let Some(i) = v.as_int() {
    return i != 0;
  }
  if let Some(f) = v.as_float() {
    return f != 0.0 && !f.is_nan();
  }
  if let Some(s) = v.as_string() {
    return !s.to_string().unwrap_or_default().is_empty();
  }
  true
}

/// Call a JS predicate and resolve `boolean | Promise<boolean>`.
pub(crate) async fn call_predicate_truthy<'js>(
  pred: &rquickjs::Function<'js>,
  arg: impl rquickjs::IntoJs<'js>,
  ctx: &rquickjs::Ctx<'js>,
) -> rquickjs::Result<bool> {
  let arg = arg.into_js(ctx)?;
  let mp: rquickjs::promise::MaybePromise<'js> = pred.call((arg,))?;
  let v: rquickjs::Value<'js> = mp.into_future().await?;
  Ok(js_truthy(&v))
}

/// Binding-side wait loop for a `(Request) => boolean` predicate: the
/// predicate needs a live `RequestJs`, so it runs in the JS runtime
/// while the loop drains the page event broadcast.
async fn wait_request_predicate<'js>(
  ctx: rquickjs::Ctx<'js>,
  page: Arc<Page>,
  pred: rquickjs::Function<'js>,
  timeout_ms: u64,
) -> rquickjs::Result<crate::bindings::network::RequestJs> {
  use ferridriver::events::PageEvent;
  use rquickjs::class::Class;
  let mut rx = page.events().subscribe();
  let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
  loop {
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
      return Err(rquickjs::Error::new_from_js_message(
        "page.waitForRequest",
        "TimeoutError",
        format!("Timeout {timeout_ms}ms exceeded while waiting for request"),
      ));
    }
    match tokio::time::timeout(remaining, rx.recv()).await {
      Ok(Ok(PageEvent::Request(req))) => {
        let probe = crate::bindings::network::RequestJs::new_with_page(req.clone(), page.clone());
        let inst = Class::instance(ctx.clone(), probe)?;
        if call_predicate_truthy(&pred, inst, &ctx).await? {
          return Ok(crate::bindings::network::RequestJs::new_with_page(req, page.clone()));
        }
      },
      Ok(Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => {},
      Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) => {
        return Err(rquickjs::Error::new_from_js_message(
          "page.waitForRequest",
          "Error",
          "page closed while waiting for request".to_string(),
        ));
      },
      Err(_) => {
        return Err(rquickjs::Error::new_from_js_message(
          "page.waitForRequest",
          "TimeoutError",
          format!("Timeout {timeout_ms}ms exceeded while waiting for request"),
        ));
      },
    }
  }
}

/// Response-side twin of [`wait_request_predicate`].
async fn wait_response_predicate<'js>(
  ctx: rquickjs::Ctx<'js>,
  page: Arc<Page>,
  pred: rquickjs::Function<'js>,
  timeout_ms: u64,
) -> rquickjs::Result<crate::bindings::network::ResponseJs> {
  use ferridriver::events::PageEvent;
  use rquickjs::class::Class;
  let mut rx = page.events().subscribe();
  let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
  loop {
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
      return Err(rquickjs::Error::new_from_js_message(
        "page.waitForResponse",
        "TimeoutError",
        format!("Timeout {timeout_ms}ms exceeded while waiting for response"),
      ));
    }
    match tokio::time::timeout(remaining, rx.recv()).await {
      Ok(Ok(PageEvent::Response(resp))) => {
        let probe = crate::bindings::network::ResponseJs::new_with_page(resp.clone(), page.clone());
        let inst = Class::instance(ctx.clone(), probe)?;
        if call_predicate_truthy(&pred, inst, &ctx).await? {
          return Ok(crate::bindings::network::ResponseJs::new_with_page(resp, page.clone()));
        }
      },
      Ok(Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => {},
      Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) => {
        return Err(rquickjs::Error::new_from_js_message(
          "page.waitForResponse",
          "Error",
          "page closed while waiting for response".to_string(),
        ));
      },
      Err(_) => {
        return Err(rquickjs::Error::new_from_js_message(
          "page.waitForResponse",
          "TimeoutError",
          format!("Timeout {timeout_ms}ms exceeded while waiting for response"),
        ));
      },
    }
  }
}

/// Lower a JS `string | RegExp` value into a [`UrlMatcher`]. Mirrors
/// the NAPI `JsRegExpLike` shape — the JS RegExp's `source` and
/// `flags` getters drive `UrlMatcher::regex_from_source`. Plain
/// strings go through `UrlMatcher::glob`.
pub(crate) fn url_value_to_matcher<'js>(
  ctx: &rquickjs::Ctx<'js>,
  value: rquickjs::Value<'js>,
) -> rquickjs::Result<ferridriver::url_matcher::UrlMatcher> {
  use crate::bindings::convert::FerriResultExt;
  if let Some(s) = value.as_string() {
    let glob = s.to_string()?;
    return ferridriver::url_matcher::UrlMatcher::glob(glob).into_js();
  }
  if let Some(obj) = value.as_object() {
    // RegExp constructor.name === "RegExp" — also has `source` (string)
    // and `flags` (string) getters per ECMAScript spec.
    let source: rquickjs::Result<String> = obj.get("source");
    let flags: rquickjs::Result<String> = obj.get("flags");
    if let (Ok(source), Ok(flags)) = (source, flags) {
      return ferridriver::url_matcher::UrlMatcher::regex_from_source(&source, &flags).into_js();
    }
  }
  let _ = ctx;
  Err(rquickjs::Error::new_from_js_message(
    "Page.waitFor*",
    "url",
    "expected string | RegExp".to_string(),
  ))
}

/// Lower a JS `string | RegExp` value into a Rust
/// [`ferridriver::options::StringOrRegex`] for every `getBy*` matcher
/// and `RoleOptions.name`. Reads `source` / `flags` via the RegExp
/// prototype getters (same technique as NAPI's `JsRegExpLike`), so a
/// real JS `RegExp` round-trips without a wire-shape escape.
pub(crate) fn string_or_regex_from_js(
  value: rquickjs::Value<'_>,
) -> rquickjs::Result<ferridriver::options::StringOrRegex> {
  if let Some(s) = value.as_string() {
    return Ok(ferridriver::options::StringOrRegex::String(s.to_string()?));
  }
  if let Some(obj) = value.as_object() {
    let source: rquickjs::Result<String> = obj.get("source");
    let flags: rquickjs::Result<String> = obj.get("flags");
    if let (Ok(source), Ok(flags)) = (source, flags) {
      return Ok(ferridriver::options::StringOrRegex::Regex { source, flags });
    }
  }
  Err(rquickjs::Error::new_from_js_message(
    "getBy*",
    "text",
    "expected string | RegExp".to_string(),
  ))
}

/// Parse `{ exact?: boolean }` options for `getByText` / `getByLabel` / etc.
pub(crate) fn parse_text_options(
  value: rquickjs::function::Opt<rquickjs::Value<'_>>,
) -> ferridriver::options::TextOptions {
  let Some(v) = value.0 else {
    return ferridriver::options::TextOptions::default();
  };
  if v.is_undefined() || v.is_null() {
    return ferridriver::options::TextOptions::default();
  }
  let Some(obj) = v.as_object() else {
    return ferridriver::options::TextOptions::default();
  };
  let exact: Option<bool> = obj.get("exact").ok();
  ferridriver::options::TextOptions { exact }
}

/// Parse the `getByRole` options bag. `{ name?: string | RegExp,
/// exact?, checked?, disabled?, expanded?, level?, pressed?,
/// selected?, includeHidden? }`. Mirrors Playwright's `ByRoleOptions`.
pub(crate) fn parse_role_options<'js>(
  value: rquickjs::function::Opt<rquickjs::Value<'js>>,
) -> rquickjs::Result<ferridriver::options::RoleOptions> {
  let Some(v) = value.0 else {
    return Ok(ferridriver::options::RoleOptions::default());
  };
  if v.is_undefined() || v.is_null() {
    return Ok(ferridriver::options::RoleOptions::default());
  }
  let Some(obj) = v.as_object() else {
    return Ok(ferridriver::options::RoleOptions::default());
  };
  let name_val: Option<rquickjs::Value<'js>> = obj.get("name").ok();
  let name = match name_val {
    Some(val) if !val.is_undefined() && !val.is_null() => Some(string_or_regex_from_js(val)?),
    _ => None,
  };
  let exact: Option<bool> = obj.get("exact").ok();
  let checked: Option<bool> = obj.get("checked").ok();
  let disabled: Option<bool> = obj.get("disabled").ok();
  let expanded: Option<bool> = obj.get("expanded").ok();
  let level: Option<i32> = obj.get("level").ok();
  let pressed: Option<bool> = obj.get("pressed").ok();
  let selected: Option<bool> = obj.get("selected").ok();
  let include_hidden: Option<bool> = obj.get("includeHidden").ok();
  Ok(ferridriver::options::RoleOptions {
    name,
    exact,
    checked,
    disabled,
    expanded,
    level,
    pressed,
    selected,
    include_hidden,
  })
}