spana-test 0.16.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/README.md +11 -0
  2. package/dist/accessibility-audit-IWTD2HPR.js +17 -0
  3. package/dist/agent/index.js +36 -33
  4. package/dist/agent/index.js.map +1 -1
  5. package/dist/{agent-fixture-H6GOUHNX.js → agent-fixture-WQVCNL73.js} +4 -3
  6. package/dist/{allure-XOM7BXL5.js → allure-LF4CALKP.js} +3 -2
  7. package/dist/{allure-XOM7BXL5.js.map → allure-LF4CALKP.js.map} +1 -1
  8. package/dist/{android-C2S4B4TH.js → android-TPO53H5Q.js} +4 -3
  9. package/dist/api/app.d.ts +79 -14
  10. package/dist/api/app.d.ts.map +1 -1
  11. package/dist/api/expect.d.ts +3 -0
  12. package/dist/api/expect.d.ts.map +1 -1
  13. package/dist/api/flow.d.ts +37 -14
  14. package/dist/api/flow.d.ts.map +1 -1
  15. package/dist/app-LGNFQMU7.js +17 -0
  16. package/dist/{appium-CC77BJNK.js → appium-2PJWZXJI.js} +64 -64
  17. package/dist/{appium-CC77BJNK.js.map → appium-2PJWZXJI.js.map} +1 -1
  18. package/dist/{appium-server-M6CWWUWF.js → appium-server-CCTQQGTV.js} +3 -2
  19. package/dist/{appium-server-M6CWWUWF.js.map → appium-server-CCTQQGTV.js.map} +1 -1
  20. package/dist/{baseline-manager-LVUVH2MJ.js → baseline-manager-XJ3LADKC.js} +3 -2
  21. package/dist/{baseline-manager-LVUVH2MJ.js.map → baseline-manager-XJ3LADKC.js.map} +1 -1
  22. package/dist/bridge-server-X5W4PCAR.js +13 -0
  23. package/dist/cache-command-OMV6DPC7.js +13 -0
  24. package/dist/channels/cdp-client.d.ts +15 -2
  25. package/dist/channels/cdp-client.d.ts.map +1 -1
  26. package/dist/channels/dom-channel.d.ts +31 -2
  27. package/dist/channels/dom-channel.d.ts.map +1 -1
  28. package/dist/{chunk-WJH5K42V.js → chunk-3HQKY24K.js} +4 -3
  29. package/dist/{chunk-WJH5K42V.js.map → chunk-3HQKY24K.js.map} +1 -1
  30. package/dist/{chunk-WBCAF7SC.js → chunk-3ONT32BO.js} +314 -182
  31. package/dist/chunk-3ONT32BO.js.map +1 -0
  32. package/dist/{chunk-HIEOI3WN.js → chunk-44U3F2RY.js} +264 -54
  33. package/dist/chunk-44U3F2RY.js.map +1 -0
  34. package/dist/{chunk-FHCOPLYB.js → chunk-4TTYSFBG.js} +4 -2
  35. package/dist/chunk-4TTYSFBG.js.map +1 -0
  36. package/dist/{chunk-4LJ3KYCX.js → chunk-5DSPPJ76.js} +4 -3
  37. package/dist/{chunk-4LJ3KYCX.js.map → chunk-5DSPPJ76.js.map} +1 -1
  38. package/dist/{accessibility-audit-F5KLUHLS.js → chunk-5TAHLRZD.js} +8 -5
  39. package/dist/chunk-5TAHLRZD.js.map +1 -0
  40. package/dist/chunk-67PLJEY2.js +24645 -0
  41. package/dist/chunk-67PLJEY2.js.map +1 -0
  42. package/dist/{chunk-JRGJTUPS.js → chunk-6X2SK2XO.js} +5 -4
  43. package/dist/{chunk-JRGJTUPS.js.map → chunk-6X2SK2XO.js.map} +1 -1
  44. package/dist/{chunk-CA66JCX2.js → chunk-7K24Q7V3.js} +976 -219
  45. package/dist/chunk-7K24Q7V3.js.map +1 -0
  46. package/dist/{chunk-2MA5G2VH.js → chunk-AGG2RJGU.js} +4 -3
  47. package/dist/{chunk-2MA5G2VH.js.map → chunk-AGG2RJGU.js.map} +1 -1
  48. package/dist/{chunk-LGFTUVN4.js → chunk-AP5SGSO7.js} +49 -48
  49. package/dist/{chunk-LGFTUVN4.js.map → chunk-AP5SGSO7.js.map} +1 -1
  50. package/dist/{chunk-NWGA3R2E.js → chunk-B4FOISOF.js} +3 -2
  51. package/dist/{chunk-NWGA3R2E.js.map → chunk-B4FOISOF.js.map} +1 -1
  52. package/dist/{chunk-7Q7TSUNL.js → chunk-B6NTHBPF.js} +3 -2
  53. package/dist/{chunk-7Q7TSUNL.js.map → chunk-B6NTHBPF.js.map} +1 -1
  54. package/dist/{chunk-7WHQIQPM.js → chunk-BPUBV7OF.js} +7 -4
  55. package/dist/chunk-BPUBV7OF.js.map +1 -0
  56. package/dist/{chunk-62SDNQKK.js → chunk-C2YM5GNF.js} +33 -32
  57. package/dist/{chunk-62SDNQKK.js.map → chunk-C2YM5GNF.js.map} +1 -1
  58. package/dist/{chunk-HJZT6YOA.js → chunk-C7HZJIGQ.js} +6 -5
  59. package/dist/{chunk-HJZT6YOA.js.map → chunk-C7HZJIGQ.js.map} +1 -1
  60. package/dist/{chunk-GMEVJQTT.js → chunk-CQ67PB3R.js} +5 -4
  61. package/dist/{chunk-GMEVJQTT.js.map → chunk-CQ67PB3R.js.map} +1 -1
  62. package/dist/{chunk-GDVHJBR2.js → chunk-CZAFFUMN.js} +5 -4
  63. package/dist/{chunk-GDVHJBR2.js.map → chunk-CZAFFUMN.js.map} +1 -1
  64. package/dist/{chunk-4TYO6O7T.js → chunk-DNWVDGKS.js} +46 -45
  65. package/dist/{chunk-4TYO6O7T.js.map → chunk-DNWVDGKS.js.map} +1 -1
  66. package/dist/{chunk-5WPPWTC3.js → chunk-E67QUGT3.js} +1888 -675
  67. package/dist/chunk-E67QUGT3.js.map +1 -0
  68. package/dist/{chunk-FSPMFRJO.js → chunk-FBJPNZUN.js} +3 -2
  69. package/dist/{chunk-FSPMFRJO.js.map → chunk-FBJPNZUN.js.map} +1 -1
  70. package/dist/{chunk-EA7DZ5TN.js → chunk-FLPPA2XY.js} +40 -5
  71. package/dist/chunk-FLPPA2XY.js.map +1 -0
  72. package/dist/{chunk-UZU7VYKN.js → chunk-FZ7EMXIM.js} +289 -125
  73. package/dist/chunk-FZ7EMXIM.js.map +1 -0
  74. package/dist/{chunk-ZCSH3QKX.js → chunk-G4ZUJCEN.js} +1518 -1069
  75. package/dist/chunk-G4ZUJCEN.js.map +1 -0
  76. package/dist/{chunk-X5FRYDZ3.js → chunk-GACJRITH.js} +4 -3
  77. package/dist/{chunk-X5FRYDZ3.js.map → chunk-GACJRITH.js.map} +1 -1
  78. package/dist/{chunk-K4K2ACT2.js → chunk-IC46FAEW.js} +8 -7
  79. package/dist/chunk-IC46FAEW.js.map +1 -0
  80. package/dist/{chunk-7O5YXVCD.js → chunk-IJWAAODK.js} +4 -3
  81. package/dist/{chunk-7O5YXVCD.js.map → chunk-IJWAAODK.js.map} +1 -1
  82. package/dist/{chunk-MUMIMDRJ.js → chunk-IKMNHITS.js} +3 -2
  83. package/dist/{chunk-MUMIMDRJ.js.map → chunk-IKMNHITS.js.map} +1 -1
  84. package/dist/{chunk-6C2EILMC.js → chunk-KIDTBRIV.js} +47 -7
  85. package/dist/chunk-KIDTBRIV.js.map +1 -0
  86. package/dist/{chunk-TFEXYI6N.js → chunk-KRTQZPYL.js} +3 -2
  87. package/dist/{chunk-TFEXYI6N.js.map → chunk-KRTQZPYL.js.map} +1 -1
  88. package/dist/{chunk-HWS3XUEF.js → chunk-LX6GMZIN.js} +8 -7
  89. package/dist/{chunk-HWS3XUEF.js.map → chunk-LX6GMZIN.js.map} +1 -1
  90. package/dist/{chunk-MPJCUL2B.js → chunk-MQRGWQI5.js} +3 -2
  91. package/dist/{chunk-MPJCUL2B.js.map → chunk-MQRGWQI5.js.map} +1 -1
  92. package/dist/{chunk-7K7WVTFZ.js → chunk-NC32K762.js} +75 -74
  93. package/dist/{chunk-7K7WVTFZ.js.map → chunk-NC32K762.js.map} +1 -1
  94. package/dist/{chunk-ZIETAMAD.js → chunk-NQYTD3JG.js} +3 -2
  95. package/dist/{chunk-ZIETAMAD.js.map → chunk-NQYTD3JG.js.map} +1 -1
  96. package/dist/{chunk-KIFNHFFI.js → chunk-NR4QAM5W.js} +335 -69
  97. package/dist/chunk-NR4QAM5W.js.map +1 -0
  98. package/dist/{chunk-YFTHJRDO.js → chunk-ODRB22QA.js} +3 -2
  99. package/dist/{chunk-YFTHJRDO.js.map → chunk-ODRB22QA.js.map} +1 -1
  100. package/dist/{chunk-HNQLWFHL.js → chunk-OYME74M3.js} +3 -2
  101. package/dist/{chunk-HNQLWFHL.js.map → chunk-OYME74M3.js.map} +1 -1
  102. package/dist/chunk-PS3DALTI.js +17 -0
  103. package/dist/chunk-PS3DALTI.js.map +1 -0
  104. package/dist/{chunk-UKUXNFQP.js → chunk-QU365GZA.js} +3 -2
  105. package/dist/{chunk-UKUXNFQP.js.map → chunk-QU365GZA.js.map} +1 -1
  106. package/dist/{chunk-HIGFQRWM.js → chunk-R52P4KQC.js} +3 -2
  107. package/dist/{chunk-HIGFQRWM.js.map → chunk-R52P4KQC.js.map} +1 -1
  108. package/dist/{chunk-U56N5JCJ.js → chunk-RL3ICBAB.js} +3 -2
  109. package/dist/{chunk-U56N5JCJ.js.map → chunk-RL3ICBAB.js.map} +1 -1
  110. package/dist/{chunk-HUYC4OAL.js → chunk-RQRJ2I2Z.js} +3 -2
  111. package/dist/{chunk-HUYC4OAL.js.map → chunk-RQRJ2I2Z.js.map} +1 -1
  112. package/dist/{chunk-NXET4BFJ.js → chunk-SPGD4QGA.js} +3 -2
  113. package/dist/{chunk-NXET4BFJ.js.map → chunk-SPGD4QGA.js.map} +1 -1
  114. package/dist/{chunk-XVL4FHXA.js → chunk-T46S4VA3.js} +3 -2
  115. package/dist/{chunk-XVL4FHXA.js.map → chunk-T46S4VA3.js.map} +1 -1
  116. package/dist/{chunk-RIXZISMX.js → chunk-V6PEMZCL.js} +3 -2
  117. package/dist/{chunk-RIXZISMX.js.map → chunk-V6PEMZCL.js.map} +1 -1
  118. package/dist/{chunk-FTXUQMGH.js → chunk-VBAPZMPX.js} +2 -1
  119. package/dist/{chunk-FTXUQMGH.js.map → chunk-VBAPZMPX.js.map} +1 -1
  120. package/dist/{chunk-DMF2BPPA.js → chunk-VILLVGBP.js} +3 -2
  121. package/dist/{chunk-DMF2BPPA.js.map → chunk-VILLVGBP.js.map} +1 -1
  122. package/dist/{chunk-NHT3XSX3.js → chunk-XGXOE3DF.js} +3 -2
  123. package/dist/{chunk-NHT3XSX3.js.map → chunk-XGXOE3DF.js.map} +1 -1
  124. package/dist/{chunk-PRQTAIYA.js → chunk-XPEWAHAK.js} +4 -3
  125. package/dist/{chunk-PRQTAIYA.js.map → chunk-XPEWAHAK.js.map} +1 -1
  126. package/dist/{chunk-GLNTGHR6.js → chunk-YKNHKVE6.js} +49 -40
  127. package/dist/chunk-YKNHKVE6.js.map +1 -0
  128. package/dist/{chunk-XD6A3VXB.js → chunk-Z5BMFLZ5.js} +8 -7
  129. package/dist/chunk-Z5BMFLZ5.js.map +1 -0
  130. package/dist/cli/test-command.d.ts +2 -0
  131. package/dist/cli/test-command.d.ts.map +1 -1
  132. package/dist/cli.js +102 -35
  133. package/dist/cli.js.map +1 -1
  134. package/dist/cloud/common.d.ts.map +1 -1
  135. package/dist/{compiler-44UW2FID.js → compiler-UOVKUQHE.js} +4 -3
  136. package/dist/{compiler-44UW2FID.js.map → compiler-UOVKUQHE.js.map} +1 -1
  137. package/dist/config-loader-MX232REU.js +11 -0
  138. package/dist/{console-T6TVZ65G.js → console-OHKVJLW3.js} +39 -6
  139. package/dist/console-OHKVJLW3.js.map +1 -0
  140. package/dist/core/accessibility-audit.d.ts.map +1 -1
  141. package/dist/core/engine.d.ts +1 -1
  142. package/dist/core/engine.d.ts.map +1 -1
  143. package/dist/core/orchestrator.d.ts +1 -0
  144. package/dist/core/orchestrator.d.ts.map +1 -1
  145. package/dist/core/projects.d.ts +10 -6
  146. package/dist/core/projects.d.ts.map +1 -1
  147. package/dist/core/rejections.d.ts +5 -0
  148. package/dist/core/rejections.d.ts.map +1 -0
  149. package/dist/core/screenshot-compare.d.ts +7 -2
  150. package/dist/core/screenshot-compare.d.ts.map +1 -1
  151. package/dist/core/video-recorder.d.ts.map +1 -1
  152. package/dist/{daemon-manager-2SK5PHJR.js → daemon-manager-6CFUXGTR.js} +4 -3
  153. package/dist/discover-AHMM7QLN.js +16 -0
  154. package/dist/{doctor-command-UUQ4RFMK.js → doctor-command-YTT5SMQW.js} +18 -16
  155. package/dist/{doctor-command-UUQ4RFMK.js.map → doctor-command-YTT5SMQW.js.map} +1 -1
  156. package/dist/driver-AN3I4H6O.js +21 -0
  157. package/dist/driver-X4FWTDNU.js +20 -0
  158. package/dist/drivers/cdp-browser.d.ts +36 -2
  159. package/dist/drivers/cdp-browser.d.ts.map +1 -1
  160. package/dist/drivers/cdp-embed.d.ts +104 -0
  161. package/dist/drivers/cdp-embed.d.ts.map +1 -0
  162. package/dist/drivers/electron.d.ts +0 -8
  163. package/dist/drivers/electron.d.ts.map +1 -1
  164. package/dist/drivers/playwright.d.ts +18 -7
  165. package/dist/drivers/playwright.d.ts.map +1 -1
  166. package/dist/drivers/raw-driver.d.ts +36 -3
  167. package/dist/drivers/raw-driver.d.ts.map +1 -1
  168. package/dist/electrobun-OUTYOM5G.js +17 -0
  169. package/dist/electron-XL7H25IQ.js +10 -0
  170. package/dist/{filters-5DCGGJRN.js → filters-6W73R3IV.js} +4 -3
  171. package/dist/gherkin/steps.js +3 -2
  172. package/dist/gherkin/steps.js.map +1 -1
  173. package/dist/github-pr-XZZZ3YE6.js +11 -0
  174. package/dist/{html-KJ2QAGF4.js → html-GDWXFYFL.js} +4 -3
  175. package/dist/{html-KJ2QAGF4.js.map → html-GDWXFYFL.js.map} +1 -1
  176. package/dist/index.d.ts +8 -5
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +237 -122
  179. package/dist/index.js.map +1 -1
  180. package/dist/{init-command-V5VGN3IS.js → init-command-PYZ5X6M5.js} +3 -2
  181. package/dist/{init-command-V5VGN3IS.js.map → init-command-PYZ5X6M5.js.map} +1 -1
  182. package/dist/{init-flow-command-INYUCC6N.js → init-flow-command-SLLEGSRZ.js} +4 -3
  183. package/dist/{init-flow-command-INYUCC6N.js.map → init-flow-command-SLLEGSRZ.js.map} +1 -1
  184. package/dist/installer-3X5SKWVX.js +18 -0
  185. package/dist/{installer-DMTY47SI.js → installer-Q37BOG5G.js} +6 -5
  186. package/dist/{ios-SZ4RBI7Q.js → ios-YFRAK2CL.js} +5 -4
  187. package/dist/{json-67HY4VQK.js → json-QVHG6I3O.js} +3 -2
  188. package/dist/{json-67HY4VQK.js.map → json-QVHG6I3O.js.map} +1 -1
  189. package/dist/{junit-MHD5AXBU.js → junit-G5LNOYUL.js} +3 -2
  190. package/dist/{junit-MHD5AXBU.js.map → junit-G5LNOYUL.js.map} +1 -1
  191. package/dist/local-UWIYOREU.js +40 -0
  192. package/dist/{machine-NOOFRT45.js → machine-VEVBT2GU.js} +4 -3
  193. package/dist/pagesource-GQLIXL5R.js +10 -0
  194. package/dist/pagesource-HKLE3FZN.js +10 -0
  195. package/dist/playwright-KBWUBU5S.js +30 -0
  196. package/dist/provider-HWM3GF54.js +14 -0
  197. package/dist/{redact-OG4M3IEU.js → redact-YWR6GHBX.js} +3 -2
  198. package/dist/{redact-OG4M3IEU.js.map → redact-YWR6GHBX.js.map} +1 -1
  199. package/dist/report/console.d.ts +2 -0
  200. package/dist/report/console.d.ts.map +1 -1
  201. package/dist/report/types.d.ts +2 -0
  202. package/dist/report/types.d.ts.map +1 -1
  203. package/dist/{runner-ABGUVOJG.js → runner-P2BFG4VZ.js} +4 -3
  204. package/dist/runtime/daemon-manager.d.ts.map +1 -1
  205. package/dist/runtime/local.d.ts +17 -0
  206. package/dist/runtime/local.d.ts.map +1 -1
  207. package/dist/runtime/web-server.d.ts +5 -1
  208. package/dist/runtime/web-server.d.ts.map +1 -1
  209. package/dist/schemas/config.d.ts +78 -6
  210. package/dist/schemas/config.d.ts.map +1 -1
  211. package/dist/schemas/selector.d.ts +6 -2
  212. package/dist/schemas/selector.d.ts.map +1 -1
  213. package/dist/screenshot-compare-DNIP2EK4.js +15 -0
  214. package/dist/{server-RTDMJIQZ.js → server-BS3O4WVU.js} +42 -39
  215. package/dist/{server-RTDMJIQZ.js.map → server-BS3O4WVU.js.map} +1 -1
  216. package/dist/server-CWCMC244.js +15 -0
  217. package/dist/session-YWYRRXXR.js +42 -0
  218. package/dist/smart/auto-wait.d.ts.map +1 -1
  219. package/dist/smart/channel-resolver.d.ts +4 -0
  220. package/dist/smart/channel-resolver.d.ts.map +1 -1
  221. package/dist/smart/coordinator.d.ts +12 -2
  222. package/dist/smart/coordinator.d.ts.map +1 -1
  223. package/dist/smart/diagnostics.d.ts.map +1 -1
  224. package/dist/smart/element-matcher.d.ts.map +1 -1
  225. package/dist/{studio-command-PZHMLCKE.js → studio-command-XJDGLNAJ.js} +4 -3
  226. package/dist/{studio-command-PZHMLCKE.js.map → studio-command-XJDGLNAJ.js.map} +1 -1
  227. package/dist/{test-command-FJOP2GYD.js → test-command-3IRGNEPB.js} +518 -88
  228. package/dist/test-command-3IRGNEPB.js.map +1 -0
  229. package/dist/validator-6XP3PGCP.js +18 -0
  230. package/dist/watch-mode-HWZ4XCKH.js +11 -0
  231. package/dist/watch-mode-HWZ4XCKH.js.map +1 -0
  232. package/native/darwin-arm64/libspana_native.dylib +0 -0
  233. package/native/darwin-x64/libspana_native.dylib +0 -0
  234. package/native/linux-arm64/libspana_native.so +0 -0
  235. package/native/linux-x64/libspana_native.so +0 -0
  236. package/native/win32-x64/spana_native.dll +0 -0
  237. package/package.json +15 -6
  238. package/studio-dist/assets/{index-DXGUfzm3.js → index-DAE7R_Zp.js} +1 -1
  239. package/studio-dist/index.html +1 -1
  240. package/dist/accessibility-audit-F5KLUHLS.js.map +0 -1
  241. package/dist/app-C353NGBT.js +0 -13
  242. package/dist/bridge-server-S3DHK7XE.js +0 -12
  243. package/dist/cache-command-OL7HUK2K.js +0 -12
  244. package/dist/chunk-5WPPWTC3.js.map +0 -1
  245. package/dist/chunk-6C2EILMC.js.map +0 -1
  246. package/dist/chunk-7WHQIQPM.js.map +0 -1
  247. package/dist/chunk-A7Z52TDQ.js +0 -97
  248. package/dist/chunk-A7Z52TDQ.js.map +0 -1
  249. package/dist/chunk-CA66JCX2.js.map +0 -1
  250. package/dist/chunk-EA7DZ5TN.js.map +0 -1
  251. package/dist/chunk-FHCOPLYB.js.map +0 -1
  252. package/dist/chunk-GLNTGHR6.js.map +0 -1
  253. package/dist/chunk-HIEOI3WN.js.map +0 -1
  254. package/dist/chunk-K4K2ACT2.js.map +0 -1
  255. package/dist/chunk-KIFNHFFI.js.map +0 -1
  256. package/dist/chunk-UZU7VYKN.js.map +0 -1
  257. package/dist/chunk-WBCAF7SC.js.map +0 -1
  258. package/dist/chunk-XD6A3VXB.js.map +0 -1
  259. package/dist/chunk-ZCSH3QKX.js.map +0 -1
  260. package/dist/config-loader-TSADVSBY.js +0 -10
  261. package/dist/console-T6TVZ65G.js.map +0 -1
  262. package/dist/discover-6ULCTB5T.js +0 -15
  263. package/dist/driver-3HBDKESK.js +0 -19
  264. package/dist/driver-LKXSKNG3.js +0 -19
  265. package/dist/electrobun-HILYDIJ3.js +0 -15
  266. package/dist/electron-SQACDON3.js +0 -9
  267. package/dist/github-pr-RYO6IAKD.js +0 -10
  268. package/dist/installer-KL2NCILK.js +0 -17
  269. package/dist/local-J2NC6YKI.js +0 -30
  270. package/dist/pagesource-KIQ5T5MA.js +0 -9
  271. package/dist/pagesource-KKG7WMFJ.js +0 -9
  272. package/dist/playwright-JMHCABDJ.js +0 -28
  273. package/dist/provider-CBAXZ2VA.js +0 -12
  274. package/dist/screenshot-compare-BJRJHKNQ.js +0 -12
  275. package/dist/server-RHAHCANZ.js +0 -14
  276. package/dist/session-7CWHTQ2E.js +0 -39
  277. package/dist/test-command-FJOP2GYD.js.map +0 -1
  278. package/dist/validator-AJNOFBQM.js +0 -17
  279. package/dist/watch-mode-NR5MHNNL.js +0 -10
  280. /package/dist/{agent-fixture-H6GOUHNX.js.map → accessibility-audit-IWTD2HPR.js.map} +0 -0
  281. /package/dist/{android-C2S4B4TH.js.map → agent-fixture-WQVCNL73.js.map} +0 -0
  282. /package/dist/{app-C353NGBT.js.map → android-TPO53H5Q.js.map} +0 -0
  283. /package/dist/{bridge-server-S3DHK7XE.js.map → app-LGNFQMU7.js.map} +0 -0
  284. /package/dist/{cache-command-OL7HUK2K.js.map → bridge-server-X5W4PCAR.js.map} +0 -0
  285. /package/dist/{config-loader-TSADVSBY.js.map → cache-command-OMV6DPC7.js.map} +0 -0
  286. /package/dist/{daemon-manager-2SK5PHJR.js.map → config-loader-MX232REU.js.map} +0 -0
  287. /package/dist/{discover-6ULCTB5T.js.map → daemon-manager-6CFUXGTR.js.map} +0 -0
  288. /package/dist/{driver-3HBDKESK.js.map → discover-AHMM7QLN.js.map} +0 -0
  289. /package/dist/{driver-LKXSKNG3.js.map → driver-AN3I4H6O.js.map} +0 -0
  290. /package/dist/{electrobun-HILYDIJ3.js.map → driver-X4FWTDNU.js.map} +0 -0
  291. /package/dist/{electron-SQACDON3.js.map → electrobun-OUTYOM5G.js.map} +0 -0
  292. /package/dist/{filters-5DCGGJRN.js.map → electron-XL7H25IQ.js.map} +0 -0
  293. /package/dist/{github-pr-RYO6IAKD.js.map → filters-6W73R3IV.js.map} +0 -0
  294. /package/dist/{installer-DMTY47SI.js.map → github-pr-XZZZ3YE6.js.map} +0 -0
  295. /package/dist/{installer-KL2NCILK.js.map → installer-3X5SKWVX.js.map} +0 -0
  296. /package/dist/{ios-SZ4RBI7Q.js.map → installer-Q37BOG5G.js.map} +0 -0
  297. /package/dist/{local-J2NC6YKI.js.map → ios-YFRAK2CL.js.map} +0 -0
  298. /package/dist/{machine-NOOFRT45.js.map → local-UWIYOREU.js.map} +0 -0
  299. /package/dist/{pagesource-KIQ5T5MA.js.map → machine-VEVBT2GU.js.map} +0 -0
  300. /package/dist/{pagesource-KKG7WMFJ.js.map → pagesource-GQLIXL5R.js.map} +0 -0
  301. /package/dist/{playwright-JMHCABDJ.js.map → pagesource-HKLE3FZN.js.map} +0 -0
  302. /package/dist/{provider-CBAXZ2VA.js.map → playwright-KBWUBU5S.js.map} +0 -0
  303. /package/dist/{runner-ABGUVOJG.js.map → provider-HWM3GF54.js.map} +0 -0
  304. /package/dist/{screenshot-compare-BJRJHKNQ.js.map → runner-P2BFG4VZ.js.map} +0 -0
  305. /package/dist/{server-RHAHCANZ.js.map → screenshot-compare-DNIP2EK4.js.map} +0 -0
  306. /package/dist/{session-7CWHTQ2E.js.map → server-CWCMC244.js.map} +0 -0
  307. /package/dist/{validator-AJNOFBQM.js.map → session-YWYRRXXR.js.map} +0 -0
  308. /package/dist/{watch-mode-NR5MHNNL.js.map → validator-6XP3PGCP.js.map} +0 -0
@@ -1,26 +1,33 @@
1
+ import { createRequire as __spanaCreateRequire } from "node:module"; const require = __spanaCreateRequire(import.meta.url);
1
2
  import {
2
3
  getHealthyWarmDaemon,
3
4
  registerWarmDaemon
4
- } from "./chunk-FHCOPLYB.js";
5
+ } from "./chunk-4TTYSFBG.js";
5
6
  import {
6
7
  resolveNetworkConditions
7
- } from "./chunk-HNQLWFHL.js";
8
+ } from "./chunk-OYME74M3.js";
8
9
  import {
9
10
  CdpDomChannel
10
- } from "./chunk-HIEOI3WN.js";
11
+ } from "./chunk-44U3F2RY.js";
12
+ import {
13
+ handledByLaterAwait,
14
+ ignoreBestEffortFailure
15
+ } from "./chunk-PS3DALTI.js";
11
16
  import {
12
17
  SPANA_INJECTED_RUNTIME_SCRIPT,
13
18
  SPANA_WASM_HOOK_SCRIPT,
14
19
  buildDomFindElementScript,
15
20
  isWasmTrapError,
16
- resolveChromiumGpuArgs
17
- } from "./chunk-CA66JCX2.js";
21
+ resolveChromiumGpuArgs,
22
+ serializeEvaluateArg
23
+ } from "./chunk-7K24Q7V3.js";
18
24
  import {
19
- DriverError
20
- } from "./chunk-A7Z52TDQ.js";
25
+ DriverError,
26
+ Effect_exports
27
+ } from "./chunk-67PLJEY2.js";
21
28
  import {
22
29
  init_esm_shims
23
- } from "./chunk-FTXUQMGH.js";
30
+ } from "./chunk-VBAPZMPX.js";
24
31
 
25
32
  // src/drivers/browser-extensions.ts
26
33
  init_esm_shims();
@@ -123,7 +130,6 @@ import { existsSync as existsSync2, mkdtempSync, readdirSync, readFileSync as re
123
130
  import { copyFile, readFile, writeFile } from "fs/promises";
124
131
  import { homedir, tmpdir } from "os";
125
132
  import { join as join2 } from "path";
126
- import { Effect } from "effect";
127
133
  var INSTANT_ANIMATIONS_CDP_SCRIPT = `
128
134
  (() => {
129
135
  const inject = () => {
@@ -268,9 +274,18 @@ ${tail}` : ""}`
268
274
  function buildDirectChromiumLaunchArgs(options) {
269
275
  const extraArgs = options.args ?? [];
270
276
  const needNoSandbox = options.chromiumSandbox !== true && !extraArgs.includes("--no-sandbox");
277
+ const needDisableSetuidSandbox = process.platform === "linux" && options.chromiumSandbox !== true && !extraArgs.includes("--disable-setuid-sandbox");
278
+ const hasBlinkSettings = extraArgs.some((a) => a.startsWith("--blink-settings="));
279
+ const isHeadless = options.headless !== false;
271
280
  return [
272
- ...options.headless !== false ? ["--headless=new"] : [],
281
+ ...isHeadless ? ["--headless=new"] : [],
273
282
  ...needNoSandbox ? ["--no-sandbox"] : [],
283
+ ...needDisableSetuidSandbox ? ["--disable-setuid-sandbox"] : [],
284
+ ...!hasBlinkSettings ? [
285
+ "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4"
286
+ ] : [],
287
+ ...isHeadless && !extraArgs.includes("--hide-scrollbars") ? ["--hide-scrollbars"] : [],
288
+ ...isHeadless && !extraArgs.includes("--mute-audio") ? ["--mute-audio"] : [],
274
289
  `--remote-debugging-port=${options.remoteDebuggingPort ?? 0}`,
275
290
  "--remote-debugging-address=127.0.0.1",
276
291
  `--user-data-dir=${options.userDataDir}`,
@@ -341,8 +356,8 @@ async function launchDirectCdpBrowser(options = {}) {
341
356
  }
342
357
  execPath = resolveChromiumExecutable(execPath);
343
358
  const rawTmp = tmpdir();
344
- const safeTmpDir = process.platform === "linux" && rawTmp.length > 50 && existsSync2("/tmp") ? "/tmp" : rawTmp;
345
- const userDataDir = mkdtempSync(join2(safeTmpDir, "spana-cdp-profile-"));
359
+ const safeTmpDir = process.platform === "linux" && rawTmp.length > 40 && existsSync2("/tmp") ? "/tmp" : rawTmp;
360
+ const userDataDir = mkdtempSync(join2(safeTmpDir, "spana-cdp-"));
346
361
  const baseChromeArgs = buildDirectChromiumLaunchArgs({
347
362
  userDataDir,
348
363
  remoteDebuggingPort: 0,
@@ -450,24 +465,96 @@ spawn error: ${err.message}`;
450
465
  child.kill("SIGTERM");
451
466
  } catch {
452
467
  }
453
- await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 150))]);
468
+ await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 500))]);
454
469
  if (!exitState.exited) {
455
470
  try {
456
471
  child.kill("SIGKILL");
457
472
  } catch {
458
473
  }
459
- await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 50))]);
474
+ await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 150))]);
460
475
  }
461
476
  }
462
477
  rmSync(userDataDir, { recursive: true, force: true });
463
478
  }
464
479
  };
465
480
  }
481
+ function mapPermissionToCdpGrantName(permission) {
482
+ switch (permission) {
483
+ case "camera":
484
+ return "videoCapture";
485
+ case "microphone":
486
+ return "audioCapture";
487
+ case "clipboard-read":
488
+ return "clipboardReadWrite";
489
+ case "clipboard-write":
490
+ return "clipboardSanitizedWrite";
491
+ case "midi-sysex":
492
+ return "midiSysex";
493
+ case "background-sync":
494
+ return "backgroundSync";
495
+ case "ambient-light-sensor":
496
+ case "accelerometer":
497
+ case "gyroscope":
498
+ case "magnetometer":
499
+ return "sensors";
500
+ case "accessibility-events":
501
+ return "accessibilityEvents";
502
+ case "payment-handler":
503
+ return "paymentHandler";
504
+ case "storage-access":
505
+ return "storageAccess";
506
+ case "top-level-storage-access":
507
+ return "topLevelStorageAccess";
508
+ case "local-fonts":
509
+ return "localFonts";
510
+ case "screen-wake-lock":
511
+ return "wakeLockScreen";
512
+ case "idle-detection":
513
+ return "idleDetection";
514
+ case "window-management":
515
+ return "windowManagement";
516
+ default:
517
+ return permission;
518
+ }
519
+ }
520
+ function mapPermissionToCdpDescriptor(permission) {
521
+ switch (permission) {
522
+ case "videoCapture":
523
+ return { name: "camera" };
524
+ case "audioCapture":
525
+ return { name: "microphone" };
526
+ case "clipboardReadWrite":
527
+ return { name: "clipboard-read" };
528
+ case "clipboardSanitizedWrite":
529
+ return { name: "clipboard-write" };
530
+ case "midi-sysex":
531
+ case "midiSysex":
532
+ return { name: "midi", sysex: true };
533
+ case "backgroundSync":
534
+ return { name: "background-sync" };
535
+ case "accessibilityEvents":
536
+ return { name: "accessibility-events" };
537
+ case "paymentHandler":
538
+ return { name: "payment-handler" };
539
+ case "storageAccess":
540
+ return { name: "storage-access" };
541
+ case "localFonts":
542
+ return { name: "local-fonts" };
543
+ case "wakeLockScreen":
544
+ return { name: "screen-wake-lock" };
545
+ case "idleDetection":
546
+ return { name: "idle-detection" };
547
+ case "windowManagement":
548
+ return { name: "window-management" };
549
+ default:
550
+ return { name: permission };
551
+ }
552
+ }
466
553
  var CDP_DUMP_HIERARCHY_SCRIPT = `(() => {
467
554
  function walk(el) {
468
555
  const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : { x: 0, y: 0, width: 0, height: 0 };
469
556
  const style = window.getComputedStyle ? window.getComputedStyle(el) : { display: "block", visibility: "visible", opacity: "1" };
470
- const visible = rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && parseFloat(style.opacity || "1") !== 0;
557
+ const visible = rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden";
471
558
  const tag = (el.tagName || "").toLowerCase();
472
559
  return {
473
560
  id: el.getAttribute?.("data-testid") || el.getAttribute?.("testID") || el.id || undefined,
@@ -497,6 +584,12 @@ var CDP_SPECIAL_KEYS = {
497
584
  Tab: { code: "Tab", keyCode: 9 },
498
585
  Escape: { code: "Escape", keyCode: 27 },
499
586
  Delete: { code: "Delete", keyCode: 46 },
587
+ Insert: { code: "Insert", keyCode: 45 },
588
+ CapsLock: { code: "CapsLock", keyCode: 20 },
589
+ NumLock: { code: "NumLock", keyCode: 144 },
590
+ ScrollLock: { code: "ScrollLock", keyCode: 145 },
591
+ PrintScreen: { code: "PrintScreen", keyCode: 44 },
592
+ Pause: { code: "Pause", keyCode: 19 },
500
593
  ArrowLeft: { code: "ArrowLeft", keyCode: 37 },
501
594
  ArrowUp: { code: "ArrowUp", keyCode: 38 },
502
595
  ArrowRight: { code: "ArrowRight", keyCode: 39 },
@@ -505,31 +598,110 @@ var CDP_SPECIAL_KEYS = {
505
598
  End: { code: "End", keyCode: 35 },
506
599
  PageUp: { code: "PageUp", keyCode: 33 },
507
600
  PageDown: { code: "PageDown", keyCode: 34 },
508
- Space: { code: "Space", keyCode: 32, text: " " },
509
- " ": { code: "Space", keyCode: 32, text: " " }
601
+ Space: { key: " ", code: "Space", keyCode: 32, text: " " },
602
+ " ": { key: " ", code: "Space", keyCode: 32, text: " " },
603
+ F1: { code: "F1", keyCode: 112 },
604
+ F2: { code: "F2", keyCode: 113 },
605
+ F3: { code: "F3", keyCode: 114 },
606
+ F4: { code: "F4", keyCode: 115 },
607
+ F5: { code: "F5", keyCode: 116 },
608
+ F6: { code: "F6", keyCode: 117 },
609
+ F7: { code: "F7", keyCode: 118 },
610
+ F8: { code: "F8", keyCode: 119 },
611
+ F9: { code: "F9", keyCode: 120 },
612
+ F10: { code: "F10", keyCode: 121 },
613
+ F11: { code: "F11", keyCode: 122 },
614
+ F12: { code: "F12", keyCode: 123 },
615
+ Control: { key: "Control", code: "ControlLeft", keyCode: 17 },
616
+ Shift: { key: "Shift", code: "ShiftLeft", keyCode: 16 },
617
+ Alt: { key: "Alt", code: "AltLeft", keyCode: 18 },
618
+ Meta: { key: "Meta", code: "MetaLeft", keyCode: 91 },
619
+ Backquote: { key: "`", code: "Backquote", keyCode: 192, text: "`" },
620
+ Minus: { key: "-", code: "Minus", keyCode: 189, text: "-" },
621
+ Equal: { key: "=", code: "Equal", keyCode: 187, text: "=" },
622
+ BracketLeft: { key: "[", code: "BracketLeft", keyCode: 219, text: "[" },
623
+ BracketRight: { key: "]", code: "BracketRight", keyCode: 221, text: "]" },
624
+ Backslash: { key: "\\", code: "Backslash", keyCode: 220, text: "\\" },
625
+ Semicolon: { key: ";", code: "Semicolon", keyCode: 186, text: ";" },
626
+ Quote: { key: "'", code: "Quote", keyCode: 222, text: "'" },
627
+ Comma: { key: ",", code: "Comma", keyCode: 188, text: "," },
628
+ Period: { key: ".", code: "Period", keyCode: 190, text: "." },
629
+ Slash: { key: "/", code: "Slash", keyCode: 191, text: "/" }
630
+ };
631
+ var CDP_PUNCTUATION_CHAR_MAP = {
632
+ "!": { code: "Digit1", keyCode: 49 },
633
+ "@": { code: "Digit2", keyCode: 50 },
634
+ "#": { code: "Digit3", keyCode: 51 },
635
+ $: { code: "Digit4", keyCode: 52 },
636
+ "%": { code: "Digit5", keyCode: 53 },
637
+ "^": { code: "Digit6", keyCode: 54 },
638
+ "&": { code: "Digit7", keyCode: 55 },
639
+ "*": { code: "Digit8", keyCode: 56 },
640
+ "(": { code: "Digit9", keyCode: 57 },
641
+ ")": { code: "Digit0", keyCode: 48 },
642
+ "`": { code: "Backquote", keyCode: 192 },
643
+ "~": { code: "Backquote", keyCode: 192 },
644
+ "-": { code: "Minus", keyCode: 189 },
645
+ _: { code: "Minus", keyCode: 189 },
646
+ "=": { code: "Equal", keyCode: 187 },
647
+ "+": { code: "Equal", keyCode: 187 },
648
+ "[": { code: "BracketLeft", keyCode: 219 },
649
+ "{": { code: "BracketLeft", keyCode: 219 },
650
+ "]": { code: "BracketRight", keyCode: 221 },
651
+ "}": { code: "BracketRight", keyCode: 221 },
652
+ "\\": { code: "Backslash", keyCode: 220 },
653
+ "|": { code: "Backslash", keyCode: 220 },
654
+ ";": { code: "Semicolon", keyCode: 186 },
655
+ ":": { code: "Semicolon", keyCode: 186 },
656
+ "'": { code: "Quote", keyCode: 222 },
657
+ '"': { code: "Quote", keyCode: 222 },
658
+ ",": { code: "Comma", keyCode: 188 },
659
+ "<": { code: "Comma", keyCode: 188 },
660
+ ".": { code: "Period", keyCode: 190 },
661
+ ">": { code: "Period", keyCode: 190 },
662
+ "/": { code: "Slash", keyCode: 191 },
663
+ "?": { code: "Slash", keyCode: 191 }
510
664
  };
511
- function parseCdpKeyDescriptor(rawKey) {
665
+ function modifierBitForName(name) {
666
+ const lower = name.toLowerCase();
667
+ if (lower === "alt" || lower === "option") return 1;
668
+ if (lower === "control" || lower === "ctrl") return 2;
669
+ if (lower === "meta" || lower === "cmd" || lower === "command") return 4;
670
+ if (lower === "controlormeta") return process.platform === "darwin" ? 4 : 2;
671
+ if (lower === "shift") return 8;
672
+ return 0;
673
+ }
674
+ function parseCdpKeyDescriptor(rawKey, extraModifiers = 0) {
512
675
  const parts = rawKey.split("+");
513
- let modifiers = 0;
676
+ let modifiers = extraModifiers;
514
677
  let baseKey = rawKey;
515
678
  if (parts.length > 1) {
516
679
  baseKey = parts[parts.length - 1] ?? rawKey;
517
680
  for (let i = 0; i < parts.length - 1; i++) {
518
- const mod = (parts[i] ?? "").toLowerCase();
519
- if (mod === "alt" || mod === "option") modifiers |= 1;
520
- else if (mod === "control" || mod === "ctrl") modifiers |= 2;
521
- else if (mod === "meta" || mod === "cmd" || mod === "command") modifiers |= 4;
522
- else if (mod === "shift") modifiers |= 8;
681
+ modifiers |= modifierBitForName(parts[i] ?? "");
523
682
  }
524
683
  }
684
+ if (baseKey.toLowerCase() === "controlormeta") {
685
+ baseKey = process.platform === "darwin" ? "Meta" : "Control";
686
+ }
687
+ const keyCodeMatch = /^Key([A-Z])$/.exec(baseKey);
688
+ if (keyCodeMatch) {
689
+ const letter = keyCodeMatch[1];
690
+ baseKey = (modifiers & 8) !== 0 ? letter : letter.toLowerCase();
691
+ }
692
+ const digitCodeMatch = /^Digit([0-9])$/.exec(baseKey);
693
+ if (digitCodeMatch) {
694
+ baseKey = digitCodeMatch[1];
695
+ }
525
696
  const special = CDP_SPECIAL_KEYS[baseKey];
526
697
  if (special) {
698
+ const emitText = special.text && (modifiers === 0 || modifiers === 8 || baseKey === "Enter") ? special.text : void 0;
527
699
  return {
528
- key: baseKey === "Space" ? " " : baseKey,
700
+ key: special.key ?? baseKey,
529
701
  code: special.code,
530
702
  windowsVirtualKeyCode: special.keyCode,
531
703
  modifiers,
532
- ...special.text ? { text: special.text } : {}
704
+ ...emitText ? { text: emitText } : {}
533
705
  };
534
706
  }
535
707
  if (baseKey.length === 1) {
@@ -537,6 +709,7 @@ function parseCdpKeyDescriptor(rawKey) {
537
709
  const charCode = upper.charCodeAt(0);
538
710
  const isLetter = charCode >= 65 && charCode <= 90;
539
711
  const isDigit = charCode >= 48 && charCode <= 57;
712
+ const punct = CDP_PUNCTUATION_CHAR_MAP[baseKey];
540
713
  const commands = [];
541
714
  if ((modifiers & (2 | 4)) !== 0) {
542
715
  if (baseKey.toLowerCase() === "a") commands.push("selectAll");
@@ -547,8 +720,8 @@ function parseCdpKeyDescriptor(rawKey) {
547
720
  }
548
721
  return {
549
722
  key: baseKey,
550
- code: isLetter ? `Key${upper}` : isDigit ? `Digit${baseKey}` : "",
551
- windowsVirtualKeyCode: charCode,
723
+ code: isLetter ? `Key${upper}` : isDigit ? `Digit${baseKey}` : punct?.code ?? "",
724
+ windowsVirtualKeyCode: isLetter || isDigit ? charCode : punct?.keyCode ?? 0,
552
725
  modifiers,
553
726
  ...modifiers === 0 || modifiers === 8 ? { text: baseKey } : {},
554
727
  ...commands.length > 0 ? { commands } : {}
@@ -569,16 +742,19 @@ var RESOURCE_BLOCK_PATTERNS = {
569
742
  stylesheet: ["*.css"]
570
743
  };
571
744
  function makeLightweightCdpDriver(options) {
572
- return Effect.gen(function* () {
745
+ return Effect_exports.gen(function* () {
573
746
  const isBrowserWs = options.cdpUrl.includes("/devtools/browser/");
574
747
  const useContexts = Boolean(
575
- options.useBrowserContexts || options.freshContextPerFlow || isBrowserWs
748
+ options.useBrowserContexts || options.freshContextPerFlow || options.contextIsolation !== void 0 || isBrowserWs
749
+ );
750
+ const effectiveFreshContextPerFlow = Boolean(
751
+ options.freshContextPerFlow ?? options.contextIsolation !== void 0
576
752
  );
577
753
  const isWs = options.cdpUrl.startsWith("ws://") || options.cdpUrl.startsWith("wss://");
578
754
  const httpEndpoint = isWs ? options.cdpUrl.replace(/^ws(s?):\/\//, "http$1://").replace(/\/devtools\/.*$/, "") : options.cdpUrl.replace(/\/+$/, "");
579
755
  let connectWsUrl = isWs ? options.cdpUrl : void 0;
580
756
  if (useContexts && !connectWsUrl) {
581
- connectWsUrl = yield* Effect.tryPromise({
757
+ connectWsUrl = yield* Effect_exports.tryPromise({
582
758
  try: () => fetchBrowserWsUrl(httpEndpoint, 5e3),
583
759
  catch: (e) => new DriverError({
584
760
  message: `Failed to resolve browser CDP WebSocket at ${options.cdpUrl}: ${e}`
@@ -592,7 +768,7 @@ function makeLightweightCdpDriver(options) {
592
768
  fetchFn: options.fetchFn,
593
769
  createWebSocket: options.createWebSocket
594
770
  });
595
- yield* Effect.tryPromise({
771
+ yield* Effect_exports.tryPromise({
596
772
  try: () => cdpChannel.connect(),
597
773
  catch: (e) => new DriverError({
598
774
  message: `Failed to connect lightweight CDP browser at ${options.cdpUrl}: ${e}`
@@ -600,12 +776,36 @@ function makeLightweightCdpDriver(options) {
600
776
  });
601
777
  const initialWidth = options.viewport?.width ?? 1280;
602
778
  const initialHeight = options.viewport?.height ?? 720;
779
+ const initialDeviceScaleFactor = options.deviceScaleFactor ?? options.viewport?.deviceScaleFactor ?? 1;
780
+ const initialMobile = Boolean(
781
+ options.isMobile ?? options.mobile ?? options.viewport?.isMobile ?? options.viewport?.mobile ?? false
782
+ );
783
+ const initialHasTouch = Boolean(
784
+ options.hasTouch ?? options.viewport?.hasTouch ?? initialMobile
785
+ );
603
786
  let width = initialWidth;
604
787
  let height = initialHeight;
605
- let emulationMutated = false;
606
- let viewportMutated = false;
788
+ let currentDeviceScaleFactor = initialDeviceScaleFactor;
789
+ let currentMobile = initialMobile;
790
+ let currentHasTouch = initialHasTouch;
791
+ let activeUserAgent = options.emulation?.userAgent;
792
+ let activeLocale = options.emulation?.locale;
793
+ const activeHttpCredentials = options.httpCredentials;
794
+ let mainFrameId = null;
795
+ let lastNavigationStatus = null;
796
+ const authAttemptedRequestIds = /* @__PURE__ */ new Set();
797
+ let hasDeviceMetricsDirty = false;
798
+ let hasTouchEmulationDirty = false;
799
+ let hasUserAgentDirty = false;
800
+ let hasLocaleDirty = false;
801
+ let hasEmulatedMediaDirty = false;
802
+ let hasTimezoneDirty = false;
803
+ let hasNetworkConditionsDirty = false;
804
+ let hasSubframeNavigation = false;
805
+ let slotNeedsHealthCheck = false;
607
806
  let geolocationMutated = false;
608
807
  let permissionsMutated = false;
808
+ let slotHasCustomStorageState = false;
609
809
  let isAtBlank = true;
610
810
  const label = options.engineLabel ?? "cdp";
611
811
  const contextIsolation = options.contextIsolation ?? "hot-cache";
@@ -655,6 +855,9 @@ function makeLightweightCdpDriver(options) {
655
855
  }
656
856
  };
657
857
  const cleanupFlowScopedHooks = async () => {
858
+ if (flowInitScripts.length === 0 && clockInitScript === null && flowExposedFunctions.size === 0 && flowExposedBindingNames.size === 0 && flowInitScriptIds.size === 0 && clockInitScriptIds.size === 0 && flowExposedScriptIds.size === 0) {
859
+ return;
860
+ }
658
861
  flowInitScripts.length = 0;
659
862
  clockInitScript = null;
660
863
  flowExposedFunctions.clear();
@@ -677,10 +880,21 @@ function makeLightweightCdpDriver(options) {
677
880
  };
678
881
  let currentNetworkConditions;
679
882
  let cachedUserAgent;
680
- let fetchInterceptEnabled = false;
883
+ let defaultCleanUserAgent;
884
+ const hasExplicitUserAgent = Boolean(
885
+ options.emulation?.userAgent || options.sanitizeHeadlessUserAgent === false
886
+ );
887
+ const sanitizeHeadlessUserAgent = (ua) => hasExplicitUserAgent ? ua : ua.replaceAll(/HeadlessChrome\//gi, "Chrome/");
888
+ const fetchEnabledSessions = /* @__PURE__ */ new Set();
889
+ let heldModifiers = 0;
890
+ let pressedMouseButtons = 0;
891
+ let lastMouseX = 0;
892
+ let lastMouseY = 0;
681
893
  let activeResponseWatchers = 0;
682
894
  let nextTabSeq = 1;
683
895
  let downloadDir;
896
+ const downloadConfiguredContexts = /* @__PURE__ */ new Set();
897
+ const navigationTimeoutMs = options.navigationTimeout ?? 3e4;
684
898
  const popupWaiters = [];
685
899
  const completedDownloads = [];
686
900
  const downloadWaiters = [];
@@ -739,24 +953,46 @@ function makeLightweightCdpDriver(options) {
739
953
  };
740
954
  const useInjectedRuntime = options.useInjectedRuntime ?? !options.createWebSocket;
741
955
  cdpChannel.enableInjectedRuntime(useInjectedRuntime);
742
- const applyLocaleOverride = async (sessionId, locale) => {
743
- await cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale }, sessionId).catch(() => {
744
- });
956
+ const buildAcceptLanguage = (locale) => {
957
+ if (!locale) return void 0;
958
+ return locale.includes("-") ? `${locale},${locale.split("-")[0]};q=0.9` : locale;
959
+ };
960
+ const resolveEffectiveUserAgent = async (sessionId, explicitUserAgent) => {
961
+ if (explicitUserAgent) return explicitUserAgent;
962
+ if (activeUserAgent) return activeUserAgent;
963
+ if (options.emulation?.userAgent) return options.emulation.userAgent;
964
+ if (defaultCleanUserAgent) return defaultCleanUserAgent;
745
965
  if (!cachedUserAgent) {
746
966
  const ua = await cdpChannel.evaluateOnSession(sessionId, "navigator.userAgent").catch(() => "");
747
- if (ua) cachedUserAgent = ua;
967
+ if (ua) cachedUserAgent = sanitizeHeadlessUserAgent(ua);
748
968
  }
749
- const acceptLanguage = locale.includes("-") ? `${locale},${locale.split("-")[0]};q=0.9` : locale;
969
+ return cachedUserAgent || "Mozilla/5.0";
970
+ };
971
+ const applyLocaleOverride = async (sessionId, locale, explicitUserAgent) => {
972
+ await cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale }, sessionId).catch(() => {
973
+ });
974
+ const acceptLanguage = buildAcceptLanguage(locale);
975
+ const effectiveUa = await resolveEffectiveUserAgent(sessionId, explicitUserAgent);
750
976
  await cdpChannel.sendCommand(
751
977
  "Emulation.setUserAgentOverride",
752
978
  {
753
- userAgent: cachedUserAgent || "Mozilla/5.0",
754
- acceptLanguage
979
+ userAgent: effectiveUa,
980
+ ...acceptLanguage ? { acceptLanguage } : {}
755
981
  },
756
982
  sessionId
757
983
  ).catch(() => {
758
984
  });
759
985
  };
986
+ const buildFetchEnableParams = () => {
987
+ const needsAllSchemes = routeRules.some(
988
+ (r) => typeof r.matcher === "string" ? /^(?:file|data|blob):/i.test(r.matcher) : /file:|data:|blob:/i.test(r.matcher.source)
989
+ );
990
+ const patterns = needsAllSchemes ? [{ urlPattern: "*" }] : [{ urlPattern: "http://*" }, { urlPattern: "https://*" }];
991
+ return {
992
+ patterns,
993
+ ...activeHttpCredentials ? { handleAuthRequests: true } : {}
994
+ };
995
+ };
760
996
  const applyNetworkConditionsToSession = async (sessionId, conditions) => {
761
997
  const resolved = resolveNetworkConditions(conditions);
762
998
  await cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
@@ -797,6 +1033,11 @@ function makeLightweightCdpDriver(options) {
797
1033
  };
798
1034
  const configureSession = async (sessionId, storageStatePath, includeFlowState = false) => {
799
1035
  const state = await loadStorageStateFile(storageStatePath);
1036
+ const targetWidth = includeFlowState ? width : initialWidth;
1037
+ const targetHeight = includeFlowState ? height : initialHeight;
1038
+ const targetDpr = includeFlowState ? currentDeviceScaleFactor : initialDeviceScaleFactor;
1039
+ const targetMobile = includeFlowState ? currentMobile : initialMobile;
1040
+ const targetHasTouch = includeFlowState ? currentHasTouch : initialHasTouch;
800
1041
  await Promise.all([
801
1042
  cdpChannel.sendCommand("Page.enable", {}, sessionId).catch(() => {
802
1043
  }),
@@ -805,6 +1046,9 @@ function makeLightweightCdpDriver(options) {
805
1046
  // Enable Network in the initial parallel batch (0 extra RTTs) so waitForResponse / app.cdp() never race fast localhost loads.
806
1047
  cdpChannel.sendCommand("Network.enable", {}, sessionId).catch(() => {
807
1048
  }),
1049
+ // Emulate focused page on headless Linux so :focus / focus-visible / hover states match desktop Chrome.
1050
+ cdpChannel.sendCommand("Emulation.setFocusEmulationEnabled", { enabled: true }, sessionId).catch(() => {
1051
+ }),
808
1052
  ...useInjectedRuntime ? [
809
1053
  cdpChannel.sendCommand(
810
1054
  "Page.addScriptToEvaluateOnNewDocument",
@@ -829,10 +1073,31 @@ function makeLightweightCdpDriver(options) {
829
1073
  }),
830
1074
  cdpChannel.sendCommand(
831
1075
  "Emulation.setDeviceMetricsOverride",
832
- { width, height, deviceScaleFactor: 1, mobile: false },
1076
+ {
1077
+ width: targetWidth,
1078
+ height: targetHeight,
1079
+ deviceScaleFactor: targetDpr,
1080
+ mobile: targetMobile
1081
+ },
833
1082
  sessionId
834
1083
  ).catch(() => {
835
- })
1084
+ }),
1085
+ ...targetHasTouch ? [
1086
+ cdpChannel.sendCommand(
1087
+ "Emulation.setTouchEmulationEnabled",
1088
+ { enabled: true, maxTouchPoints: 5 },
1089
+ sessionId
1090
+ ).catch(() => {
1091
+ })
1092
+ ] : [],
1093
+ ...!options.emulation?.userAgent && !options.emulation?.locale && defaultCleanUserAgent ? [
1094
+ cdpChannel.sendCommand(
1095
+ "Emulation.setUserAgentOverride",
1096
+ { userAgent: defaultCleanUserAgent },
1097
+ sessionId
1098
+ ).catch(() => {
1099
+ })
1100
+ ] : []
836
1101
  ]);
837
1102
  if (options.instantAnimations) {
838
1103
  await cdpChannel.sendCommand(
@@ -862,6 +1127,18 @@ function makeLightweightCdpDriver(options) {
862
1127
  for (const fnName of flowExposedFunctions.keys()) {
863
1128
  await installExposeFunctionOnSession(sessionId, fnName);
864
1129
  }
1130
+ if (routeRules.length > 0 || activeHttpCredentials) {
1131
+ fetchEnabledSessions.add(sessionId);
1132
+ await cdpChannel.sendCommand("Fetch.enable", buildFetchEnableParams(), sessionId).catch(() => {
1133
+ });
1134
+ }
1135
+ if (currentNetworkConditions) {
1136
+ await applyNetworkConditionsToSession(sessionId, currentNetworkConditions);
1137
+ }
1138
+ } else if (activeHttpCredentials) {
1139
+ fetchEnabledSessions.add(sessionId);
1140
+ await cdpChannel.sendCommand("Fetch.enable", buildFetchEnableParams(), sessionId).catch(() => {
1141
+ });
865
1142
  }
866
1143
  if (options.blockResources && options.blockResources.length > 0) {
867
1144
  const urls = options.blockResources.flatMap((t) => RESOURCE_BLOCK_PATTERNS[t] ?? []);
@@ -880,27 +1157,24 @@ function makeLightweightCdpDriver(options) {
880
1157
  "Page.addScriptToEvaluateOnNewDocument",
881
1158
  {
882
1159
  source: `(() => {
883
- const origins = ${originsJson};
884
- const hit = origins.find((o) => o.origin === window.location.origin);
885
- if (hit && Array.isArray(hit.localStorage)) {
886
- for (const item of hit.localStorage) {
887
- try { window.localStorage.setItem(item.name, item.value); } catch {}
1160
+ try {
1161
+ const seedKey = "__spana_storage_seeded__:" + window.location.origin;
1162
+ if (window.sessionStorage.getItem(seedKey)) return;
1163
+ const origins = ${originsJson};
1164
+ const hit = origins.find((o) => o.origin === window.location.origin);
1165
+ if (hit && Array.isArray(hit.localStorage)) {
1166
+ for (const item of hit.localStorage) {
1167
+ try { window.localStorage.setItem(item.name, item.value); } catch {}
1168
+ }
1169
+ window.sessionStorage.setItem(seedKey, "1");
888
1170
  }
889
- }
1171
+ } catch {}
890
1172
  })();`
891
1173
  },
892
1174
  sessionId
893
1175
  ).catch(() => {
894
1176
  });
895
1177
  }
896
- if (routeRules.length > 0) {
897
- fetchInterceptEnabled = true;
898
- await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId).catch(() => {
899
- });
900
- }
901
- if (currentNetworkConditions) {
902
- await applyNetworkConditionsToSession(sessionId, currentNetworkConditions);
903
- }
904
1178
  if (options.emulation) {
905
1179
  const emuFeatures = [];
906
1180
  if (options.emulation.colorScheme !== void 0) {
@@ -922,6 +1196,19 @@ function makeLightweightCdpDriver(options) {
922
1196
  if (options.emulation.locale) {
923
1197
  await applyLocaleOverride(sessionId, options.emulation.locale);
924
1198
  }
1199
+ if (options.emulation.userAgent) {
1200
+ const locale = options.emulation.locale;
1201
+ const acceptLanguage = locale ? locale.includes("-") ? `${locale},${locale.split("-")[0]};q=0.9` : locale : void 0;
1202
+ await cdpChannel.sendCommand(
1203
+ "Emulation.setUserAgentOverride",
1204
+ {
1205
+ userAgent: options.emulation.userAgent,
1206
+ ...acceptLanguage ? { acceptLanguage } : {}
1207
+ },
1208
+ sessionId
1209
+ ).catch(() => {
1210
+ });
1211
+ }
925
1212
  if (options.emulation.timezoneId) {
926
1213
  await cdpChannel.sendCommand(
927
1214
  "Emulation.setTimezoneOverride",
@@ -948,7 +1235,12 @@ function makeLightweightCdpDriver(options) {
948
1235
  );
949
1236
  const targetRes = await cdpChannel.sendCommand(
950
1237
  "Target.createTarget",
951
- { url: "about:blank", browserContextId: ctxRes.browserContextId, width, height },
1238
+ {
1239
+ url: "about:blank",
1240
+ browserContextId: ctxRes.browserContextId,
1241
+ width: initialWidth,
1242
+ height: initialHeight
1243
+ },
952
1244
  null
953
1245
  );
954
1246
  const attachRes = await cdpChannel.sendCommand(
@@ -970,6 +1262,7 @@ function makeLightweightCdpDriver(options) {
970
1262
  };
971
1263
  };
972
1264
  const disposeSlotInBackground = (slot) => {
1265
+ downloadConfiguredContexts.delete(slot.browserContextId);
973
1266
  const p = new Promise((r) => setTimeout(r, 120)).then(
974
1267
  () => cdpChannel.sendCommand(
975
1268
  "Target.disposeBrowserContext",
@@ -984,7 +1277,7 @@ function makeLightweightCdpDriver(options) {
984
1277
  backgroundDisposals.push(p);
985
1278
  };
986
1279
  const schedulePrefetch = () => {
987
- if (!useContexts || !options.freshContextPerFlow || contextIsolation === "hot-cache" || prefetchedSlotPromise) {
1280
+ if (!useContexts || !effectiveFreshContextPerFlow || contextIsolation === "hot-cache" || prefetchedSlotPromise) {
988
1281
  return;
989
1282
  }
990
1283
  prefetchedSlotPromise = createContextSlot(options.storageState);
@@ -994,13 +1287,117 @@ function makeLightweightCdpDriver(options) {
994
1287
  };
995
1288
  const workerSessions = /* @__PURE__ */ new Map();
996
1289
  const wasmTraps = [];
1290
+ const handlingPopupTargets = /* @__PURE__ */ new Set();
1291
+ const setupPopupSession = async (targetId, childSid, waitingForDebugger) => {
1292
+ if (!activeSlot) {
1293
+ if (waitingForDebugger) {
1294
+ await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
1295
+ });
1296
+ }
1297
+ return;
1298
+ }
1299
+ const newTabId = `tab-${nextTabSeq++}`;
1300
+ if (!activeSlot.tabs.some((t) => t.targetId === targetId)) {
1301
+ activeSlot.tabs.push({ tabId: newTabId, targetId, sessionId: childSid });
1302
+ }
1303
+ const popupUa = activeUserAgent || options.emulation?.userAgent || defaultCleanUserAgent;
1304
+ const popupAcceptLang = buildAcceptLanguage(activeLocale || options.emulation?.locale);
1305
+ const setupCalls = [
1306
+ // Enable Network FIRST unconditionally so fast popup fetch/XHR bodies are buffered before requestWillBeSent
1307
+ cdpChannel.sendCommand("Network.enable", {}, childSid).catch(() => {
1308
+ }),
1309
+ cdpChannel.sendCommand("Page.enable", {}, childSid).catch(() => {
1310
+ }),
1311
+ cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
1312
+ }),
1313
+ cdpChannel.sendCommand("Emulation.setFocusEmulationEnabled", { enabled: true }, childSid).catch(() => {
1314
+ }),
1315
+ ...popupUa ? [
1316
+ cdpChannel.sendCommand(
1317
+ "Emulation.setUserAgentOverride",
1318
+ {
1319
+ userAgent: popupUa,
1320
+ ...popupAcceptLang ? { acceptLanguage: popupAcceptLang } : {}
1321
+ },
1322
+ childSid
1323
+ ).catch(() => {
1324
+ })
1325
+ ] : []
1326
+ ];
1327
+ if (currentNetworkConditions) {
1328
+ setupCalls.push(applyNetworkConditionsToSession(childSid, currentNetworkConditions));
1329
+ }
1330
+ if (routeRules.length > 0 || activeHttpCredentials) {
1331
+ fetchEnabledSessions.add(childSid);
1332
+ setupCalls.push(
1333
+ cdpChannel.sendCommand("Fetch.enable", buildFetchEnableParams(), childSid).catch(() => {
1334
+ })
1335
+ );
1336
+ }
1337
+ if (useInjectedRuntime) {
1338
+ setupCalls.push(
1339
+ cdpChannel.sendCommand(
1340
+ "Page.addScriptToEvaluateOnNewDocument",
1341
+ { source: SPANA_INJECTED_RUNTIME_SCRIPT },
1342
+ childSid
1343
+ ).catch(() => {
1344
+ })
1345
+ );
1346
+ }
1347
+ if (readyInitScript) {
1348
+ setupCalls.push(
1349
+ cdpChannel.sendCommand(
1350
+ "Page.addScriptToEvaluateOnNewDocument",
1351
+ { source: readyInitScript },
1352
+ childSid
1353
+ ).catch(() => {
1354
+ })
1355
+ );
1356
+ }
1357
+ for (const scriptSource of flowInitScripts) {
1358
+ setupCalls.push(
1359
+ cdpChannel.sendCommand(
1360
+ "Page.addScriptToEvaluateOnNewDocument",
1361
+ { source: scriptSource },
1362
+ childSid
1363
+ ).then((res) => recordScriptId(flowInitScriptIds, childSid, res)).catch(() => {
1364
+ })
1365
+ );
1366
+ }
1367
+ if (clockInitScript) {
1368
+ setupCalls.push(
1369
+ cdpChannel.sendCommand(
1370
+ "Page.addScriptToEvaluateOnNewDocument",
1371
+ { source: clockInitScript },
1372
+ childSid
1373
+ ).then((res) => recordScriptId(clockInitScriptIds, childSid, res)).catch(() => {
1374
+ })
1375
+ );
1376
+ }
1377
+ for (const fnName of flowExposedFunctions.keys()) {
1378
+ setupCalls.push(installExposeFunctionOnSession(childSid, fnName).catch(() => {
1379
+ }));
1380
+ }
1381
+ await Promise.all(setupCalls);
1382
+ if (waitingForDebugger) {
1383
+ await cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
1384
+ });
1385
+ }
1386
+ if (popupWaiters.length > 0) {
1387
+ const waiter = popupWaiters.shift();
1388
+ if (waiter) waiter.resolve(newTabId);
1389
+ }
1390
+ };
997
1391
  cdpChannel.onEvent("Target.targetCreated", (params) => {
998
1392
  const targetInfo = params?.targetInfo;
999
1393
  if (targetInfo?.type !== "page" || !targetInfo.targetId || !targetInfo.openerId || !activeSlot || targetInfo.browserContextId !== activeSlot.browserContextId) {
1000
1394
  return;
1001
1395
  }
1002
1396
  const targetId = String(targetInfo.targetId);
1003
- if (activeSlot.tabs.some((t) => t.targetId === targetId)) return;
1397
+ if (handlingPopupTargets.has(targetId) || activeSlot.tabs.some((t) => t.targetId === targetId)) {
1398
+ return;
1399
+ }
1400
+ handlingPopupTargets.add(targetId);
1004
1401
  void (async () => {
1005
1402
  try {
1006
1403
  const attachRes = await cdpChannel.sendCommand(
@@ -1009,79 +1406,8 @@ function makeLightweightCdpDriver(options) {
1009
1406
  null
1010
1407
  );
1011
1408
  const childSid = attachRes?.sessionId;
1012
- if (!childSid || !activeSlot) return;
1013
- const newTabId = `tab-${nextTabSeq++}`;
1014
- if (!activeSlot.tabs.some((t) => t.targetId === targetId)) {
1015
- activeSlot.tabs.push({ tabId: newTabId, targetId, sessionId: childSid });
1016
- }
1017
- const setupCalls = [
1018
- cdpChannel.sendCommand("Page.enable", {}, childSid).catch(() => {
1019
- }),
1020
- cdpChannel.sendCommand("Runtime.enable", {}, childSid).catch(() => {
1021
- })
1022
- ];
1023
- if (activeResponseWatchers > 0 || requestListeners.size > 0) {
1024
- setupCalls.push(cdpChannel.sendCommand("Network.enable", {}, childSid).catch(() => {
1025
- }));
1026
- }
1027
- if (currentNetworkConditions) {
1028
- setupCalls.push(applyNetworkConditionsToSession(childSid, currentNetworkConditions));
1029
- }
1030
- if (fetchInterceptEnabled) {
1031
- setupCalls.push(
1032
- cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, childSid).catch(() => {
1033
- })
1034
- );
1035
- }
1036
- if (useInjectedRuntime) {
1037
- setupCalls.push(
1038
- cdpChannel.sendCommand(
1039
- "Page.addScriptToEvaluateOnNewDocument",
1040
- { source: SPANA_INJECTED_RUNTIME_SCRIPT },
1041
- childSid
1042
- ).catch(() => {
1043
- })
1044
- );
1045
- }
1046
- if (readyInitScript) {
1047
- setupCalls.push(
1048
- cdpChannel.sendCommand(
1049
- "Page.addScriptToEvaluateOnNewDocument",
1050
- { source: readyInitScript },
1051
- childSid
1052
- ).catch(() => {
1053
- })
1054
- );
1055
- }
1056
- for (const scriptSource of flowInitScripts) {
1057
- setupCalls.push(
1058
- cdpChannel.sendCommand(
1059
- "Page.addScriptToEvaluateOnNewDocument",
1060
- { source: scriptSource },
1061
- childSid
1062
- ).then((res) => recordScriptId(flowInitScriptIds, childSid, res)).catch(() => {
1063
- })
1064
- );
1065
- }
1066
- if (clockInitScript) {
1067
- setupCalls.push(
1068
- cdpChannel.sendCommand(
1069
- "Page.addScriptToEvaluateOnNewDocument",
1070
- { source: clockInitScript },
1071
- childSid
1072
- ).then((res) => recordScriptId(clockInitScriptIds, childSid, res)).catch(() => {
1073
- })
1074
- );
1075
- }
1076
- for (const fnName of flowExposedFunctions.keys()) {
1077
- setupCalls.push(installExposeFunctionOnSession(childSid, fnName).catch(() => {
1078
- }));
1079
- }
1080
- await Promise.all(setupCalls);
1081
- if (popupWaiters.length > 0) {
1082
- const waiter = popupWaiters.shift();
1083
- if (waiter) waiter.resolve(newTabId);
1084
- }
1409
+ if (!childSid) return;
1410
+ await setupPopupSession(targetId, childSid, false);
1085
1411
  } catch {
1086
1412
  }
1087
1413
  })();
@@ -1090,6 +1416,21 @@ function makeLightweightCdpDriver(options) {
1090
1416
  const targetInfo = params?.targetInfo;
1091
1417
  const childSid = params?.sessionId;
1092
1418
  const waiting = Boolean(params?.waitingForDebugger);
1419
+ if (targetInfo?.type === "page" && typeof childSid === "string") {
1420
+ const targetId = typeof targetInfo.targetId === "string" ? targetInfo.targetId : "";
1421
+ const isOurPopup = Boolean(
1422
+ targetId && targetInfo.openerId && activeSlot && targetInfo.browserContextId === activeSlot.browserContextId
1423
+ );
1424
+ if (isOurPopup && !handlingPopupTargets.has(targetId)) {
1425
+ handlingPopupTargets.add(targetId);
1426
+ void setupPopupSession(targetId, childSid, waiting).catch(ignoreBestEffortFailure);
1427
+ return;
1428
+ }
1429
+ if (waiting) {
1430
+ void cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(ignoreBestEffortFailure);
1431
+ }
1432
+ return;
1433
+ }
1093
1434
  if ((targetInfo?.type === "worker" || targetInfo?.type === "service_worker") && typeof childSid === "string") {
1094
1435
  workerSessions.set(childSid, typeof targetInfo.url === "string" ? targetInfo.url : "");
1095
1436
  void (async () => {
@@ -1140,13 +1481,27 @@ function makeLightweightCdpDriver(options) {
1140
1481
  }
1141
1482
  })();
1142
1483
  } else if (waiting && typeof childSid === "string") {
1143
- void cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(() => {
1144
- });
1484
+ void cdpChannel.sendCommand("Runtime.runIfWaitingForDebugger", {}, childSid).catch(ignoreBestEffortFailure);
1485
+ }
1486
+ });
1487
+ cdpChannel.onEvent("Target.targetInfoChanged", (params) => {
1488
+ const targetInfo = params?.targetInfo;
1489
+ if (!targetInfo?.targetId || typeof targetInfo.url !== "string") return;
1490
+ cdpChannel.updateChildSessionByTargetId(String(targetInfo.targetId), {
1491
+ url: targetInfo.url
1492
+ });
1493
+ try {
1494
+ const parsed = new URL(targetInfo.url);
1495
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1496
+ observedOrigins.add(parsed.origin);
1497
+ }
1498
+ } catch {
1145
1499
  }
1146
1500
  });
1147
1501
  cdpChannel.onEvent("Target.detachedFromTarget", (params) => {
1148
1502
  if (typeof params?.sessionId === "string") {
1149
1503
  cdpChannel.removeChildSession(params.sessionId);
1504
+ fetchEnabledSessions.delete(params.sessionId);
1150
1505
  if (activeSlot) {
1151
1506
  const wasActive = activeSlot.sessionId === params.sessionId;
1152
1507
  activeSlot.tabs = activeSlot.tabs.filter((t) => t.sessionId !== params.sessionId);
@@ -1155,10 +1510,22 @@ function makeLightweightCdpDriver(options) {
1155
1510
  activeSlot.targetId = fallback.targetId;
1156
1511
  activeSlot.sessionId = fallback.sessionId;
1157
1512
  cdpChannel.setSessionId(fallback.sessionId);
1513
+ } else if (wasActive) {
1514
+ slotNeedsHealthCheck = true;
1158
1515
  }
1159
1516
  }
1160
1517
  }
1161
1518
  });
1519
+ cdpChannel.onEvent("Target.targetDestroyed", (params) => {
1520
+ if (activeSlot && typeof params?.targetId === "string" && params.targetId === activeSlot.targetId) {
1521
+ slotNeedsHealthCheck = true;
1522
+ }
1523
+ });
1524
+ cdpChannel.onEvent("Target.targetCrashed", (params) => {
1525
+ if (activeSlot && typeof params?.targetId === "string" && params.targetId === activeSlot.targetId) {
1526
+ slotNeedsHealthCheck = true;
1527
+ }
1528
+ });
1162
1529
  cdpChannel.onEvent("Page.javascriptDialogOpening", (params, sid) => {
1163
1530
  const targetSid = sid ?? null;
1164
1531
  const dialogType = String(params?.type ?? "alert");
@@ -1167,8 +1534,7 @@ function makeLightweightCdpDriver(options) {
1167
1534
  const activeHandler = dialogHandler;
1168
1535
  if (!activeHandler) {
1169
1536
  const accept = dialogType === "beforeunload";
1170
- void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, targetSid).catch(() => {
1171
- });
1537
+ void cdpChannel.sendCommand("Page.handleJavaScriptDialog", { accept }, targetSid).catch(ignoreBestEffortFailure);
1172
1538
  return;
1173
1539
  }
1174
1540
  let handled = false;
@@ -1202,27 +1568,57 @@ function makeLightweightCdpDriver(options) {
1202
1568
  "Page.handleJavaScriptDialog",
1203
1569
  { accept: dialogType === "beforeunload" },
1204
1570
  targetSid
1205
- ).catch(() => {
1206
- });
1571
+ ).catch(ignoreBestEffortFailure);
1207
1572
  }
1208
1573
  });
1209
1574
  });
1210
1575
  cdpChannel.setFrameOffsetResolver(async (child) => {
1211
- if (!child.targetId) return { x: 0, y: 0 };
1576
+ if (!child.targetId) return { x: 0, y: 0, scaleX: 1, scaleY: 1 };
1212
1577
  try {
1213
1578
  await cdpChannel.sendCommand("DOM.enable");
1214
1579
  const owner = await cdpChannel.sendCommand("DOM.getFrameOwner", {
1215
1580
  frameId: child.targetId
1216
1581
  });
1217
1582
  const boxParams = owner.backendNodeId ? { backendNodeId: owner.backendNodeId } : { nodeId: owner.nodeId };
1583
+ const resolved = await cdpChannel.sendCommand("DOM.resolveNode", boxParams).catch(() => null);
1584
+ if (resolved?.object?.objectId) {
1585
+ const objectId = resolved.object.objectId;
1586
+ try {
1587
+ const callRes = await cdpChannel.sendCommand("Runtime.callFunctionOn", {
1588
+ objectId,
1589
+ functionDeclaration: `function() {
1590
+ var r = this.getBoundingClientRect();
1591
+ var win = (this.ownerDocument && this.ownerDocument.defaultView) || window;
1592
+ var cs = win && win.getComputedStyle ? win.getComputedStyle(this) : null;
1593
+ var bLeft = cs ? (parseFloat(cs.borderLeftWidth) || 0) : 0;
1594
+ var bTop = cs ? (parseFloat(cs.borderTopWidth) || 0) : 0;
1595
+ var bRight = cs ? (parseFloat(cs.borderRightWidth) || 0) : 0;
1596
+ var bBottom = cs ? (parseFloat(cs.borderBottomWidth) || 0) : 0;
1597
+ var layoutW = this.offsetWidth || (this.clientWidth + bLeft + bRight);
1598
+ var layoutH = this.offsetHeight || (this.clientHeight + bTop + bBottom);
1599
+ var sx = layoutW > 0 ? (r.width / layoutW) : 1;
1600
+ var sy = layoutH > 0 ? (r.height / layoutH) : 1;
1601
+ if (!isFinite(sx) || sx <= 0) sx = 1;
1602
+ if (!isFinite(sy) || sy <= 0) sy = 1;
1603
+ return { x: r.left + bLeft * sx, y: r.top + bTop * sy, scaleX: sx, scaleY: sy };
1604
+ }`,
1605
+ returnByValue: true
1606
+ });
1607
+ if (callRes?.result?.value) {
1608
+ return callRes.result.value;
1609
+ }
1610
+ } finally {
1611
+ void cdpChannel.sendCommand("Runtime.releaseObject", { objectId }).catch(ignoreBestEffortFailure);
1612
+ }
1613
+ }
1218
1614
  const box = await cdpChannel.sendCommand("DOM.getBoxModel", boxParams);
1219
1615
  const quad = box?.model?.content ?? box?.model?.border;
1220
1616
  if (Array.isArray(quad) && quad.length >= 2) {
1221
- return { x: quad[0] ?? 0, y: quad[1] ?? 0 };
1617
+ return { x: quad[0] ?? 0, y: quad[1] ?? 0, scaleX: 1, scaleY: 1 };
1222
1618
  }
1223
1619
  } catch {
1224
1620
  }
1225
- return { x: 0, y: 0 };
1621
+ return { x: 0, y: 0, scaleX: 1, scaleY: 1 };
1226
1622
  });
1227
1623
  cdpChannel.onEvent("Runtime.consoleAPICalled", (params, sid) => {
1228
1624
  const isWorker = typeof sid === "string" && workerSessions.has(sid);
@@ -1264,12 +1660,35 @@ function makeLightweightCdpDriver(options) {
1264
1660
  };
1265
1661
  cdpChannel.onEvent("Page.frameNavigated", (params, sid) => {
1266
1662
  if (!params?.frame?.parentId) {
1663
+ if ((!activeSlot || !sid || sid === activeSlot.sessionId) && typeof params?.frame?.id === "string") {
1664
+ mainFrameId = params.frame.id;
1665
+ }
1267
1666
  recordNavUrl(params?.frame?.url, sid);
1667
+ } else {
1668
+ hasSubframeNavigation = true;
1669
+ if (typeof params?.frame?.url === "string") {
1670
+ try {
1671
+ const parsed = new URL(params.frame.url);
1672
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1673
+ observedOrigins.add(parsed.origin);
1674
+ }
1675
+ } catch {
1676
+ }
1677
+ }
1268
1678
  }
1269
1679
  });
1270
1680
  cdpChannel.onEvent("Page.navigatedWithinDocument", (params, sid) => {
1271
1681
  recordNavUrl(params?.url, sid);
1272
1682
  });
1683
+ cdpChannel.onEvent("Network.responseReceived", (params, sid) => {
1684
+ if (activeSlot && sid && sid !== activeSlot.sessionId) return;
1685
+ if (params?.type !== "Document") return;
1686
+ if (mainFrameId && params?.frameId && params.frameId !== mainFrameId) return;
1687
+ const status = params?.response?.status;
1688
+ if (typeof status === "number" && Number.isFinite(status)) {
1689
+ lastNavigationStatus = status;
1690
+ }
1691
+ });
1273
1692
  cdpChannel.onEvent("Runtime.bindingCalled", (params, sid) => {
1274
1693
  const payloadRaw = params?.payload;
1275
1694
  if (typeof payloadRaw !== "string") return;
@@ -1342,16 +1761,58 @@ function makeLightweightCdpDriver(options) {
1342
1761
  }
1343
1762
  }
1344
1763
  });
1764
+ cdpChannel.onEvent("Fetch.authRequired", (params, sid) => {
1765
+ if (!activeHttpCredentials) return;
1766
+ const sessionKey = sid ?? null;
1767
+ if (!fetchEnabledSessions.has(sessionKey)) return;
1768
+ const reqId = params?.requestId;
1769
+ if (!reqId) return;
1770
+ if (authAttemptedRequestIds.has(reqId)) {
1771
+ authAttemptedRequestIds.delete(reqId);
1772
+ void cdpChannel.sendCommand(
1773
+ "Fetch.continueWithAuth",
1774
+ {
1775
+ requestId: reqId,
1776
+ authChallengeResponse: { response: "CancelAuth" }
1777
+ },
1778
+ sessionKey
1779
+ ).catch(ignoreBestEffortFailure);
1780
+ return;
1781
+ }
1782
+ authAttemptedRequestIds.add(reqId);
1783
+ if (authAttemptedRequestIds.size > 200) {
1784
+ const oldest = authAttemptedRequestIds.values().next().value;
1785
+ if (oldest !== void 0) authAttemptedRequestIds.delete(oldest);
1786
+ }
1787
+ void cdpChannel.sendCommand(
1788
+ "Fetch.continueWithAuth",
1789
+ {
1790
+ requestId: reqId,
1791
+ authChallengeResponse: {
1792
+ response: "ProvideCredentials",
1793
+ username: activeHttpCredentials.username,
1794
+ password: activeHttpCredentials.password
1795
+ }
1796
+ },
1797
+ sessionKey
1798
+ ).catch(ignoreBestEffortFailure);
1799
+ });
1345
1800
  cdpChannel.onEvent("Fetch.requestPaused", (params, sid) => {
1346
- if (!fetchInterceptEnabled) return;
1801
+ const sessionKey = sid ?? null;
1802
+ if (!fetchEnabledSessions.has(sessionKey)) return;
1347
1803
  const reqId = params?.requestId;
1348
1804
  const reqObj = params?.request ?? {};
1349
1805
  const url = String(reqObj.url ?? "");
1350
1806
  if (!reqId) return;
1351
- const rule = routeRules.find((r) => matchUrl(r.matcher, url));
1352
- if (!rule) {
1353
- void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
1354
- });
1807
+ const matchingRules = [];
1808
+ for (let ri = routeRules.length - 1; ri >= 0; ri--) {
1809
+ const candidate = routeRules[ri];
1810
+ if (matchUrl(candidate.matcher, url)) {
1811
+ matchingRules.push(candidate);
1812
+ }
1813
+ }
1814
+ if (matchingRules.length === 0) {
1815
+ void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sessionKey).catch(ignoreBestEffortFailure);
1355
1816
  return;
1356
1817
  }
1357
1818
  const fulfillWith = async (resp) => {
@@ -1374,141 +1835,244 @@ function makeLightweightCdpDriver(options) {
1374
1835
  responseHeaders,
1375
1836
  body: Buffer.from(bodyStr, "utf8").toString("base64")
1376
1837
  },
1377
- sid ?? null
1838
+ sessionKey
1378
1839
  );
1379
1840
  };
1380
- if (rule.kind === "handler" && rule.handler) {
1381
- const rawHeaders = reqObj.headers ?? {};
1382
- const headers = {};
1383
- for (const [k, v] of Object.entries(rawHeaders)) {
1384
- headers[k.toLowerCase()] = String(v);
1385
- }
1386
- const postDataStr = typeof reqObj.postData === "string" ? reqObj.postData : null;
1387
- const reqInfo = {
1388
- url,
1389
- method: String(reqObj.method ?? "GET"),
1390
- headers,
1391
- resourceType: typeof params?.resourceType === "string" ? params.resourceType.toLowerCase() : void 0,
1392
- postData: () => postDataStr,
1393
- postDataJSON: () => {
1394
- if (!postDataStr) return null;
1395
- try {
1396
- return JSON.parse(postDataStr);
1397
- } catch {
1398
- return null;
1399
- }
1400
- }
1401
- };
1402
- let handled = false;
1403
- const routeObj = {
1404
- request: () => reqInfo,
1405
- continue: async (overrides) => {
1406
- if (handled) return;
1407
- handled = true;
1408
- await cdpChannel.sendCommand(
1409
- "Fetch.continueRequest",
1410
- {
1411
- requestId: reqId,
1412
- ...overrides?.url ? { url: overrides.url } : {},
1413
- ...overrides?.method ? { method: overrides.method } : {},
1414
- ...overrides?.headers ? {
1415
- headers: Object.entries(overrides.headers).map(([name, value]) => ({
1416
- name,
1417
- value
1418
- }))
1419
- } : {},
1420
- ...overrides?.postData !== void 0 ? { postData: Buffer.from(overrides.postData, "utf8").toString("base64") } : {}
1421
- },
1422
- sid ?? null
1423
- );
1424
- },
1425
- abort: async (errorCode) => {
1426
- if (handled) return;
1427
- handled = true;
1428
- await cdpChannel.sendCommand(
1429
- "Fetch.failRequest",
1430
- { requestId: reqId, errorReason: errorCode ?? "Failed" },
1431
- sid ?? null
1432
- );
1433
- },
1434
- fulfill: async (response) => {
1435
- if (handled) return;
1436
- handled = true;
1437
- await fulfillWith(response);
1438
- },
1439
- fetch: async (overrides) => {
1440
- const targetUrl = overrides?.url ?? url;
1441
- const fetchHeaders = { ...headers, ...overrides?.headers };
1442
- const fetchMethod = overrides?.method ?? reqInfo.method;
1443
- const body = overrides?.postData !== void 0 ? overrides.postData : fetchMethod !== "GET" && fetchMethod !== "HEAD" ? postDataStr ?? void 0 : void 0;
1444
- const res = await fetch(targetUrl, {
1445
- method: fetchMethod,
1446
- headers: fetchHeaders,
1447
- ...body !== void 0 ? { body } : {}
1448
- });
1449
- const resText = await res.text();
1450
- const outHeaders = {};
1451
- res.headers.forEach((v, k) => {
1452
- outHeaders[k.toLowerCase()] = v;
1453
- });
1454
- return {
1455
- url: res.url || targetUrl,
1456
- status: res.status,
1457
- statusText: res.statusText,
1458
- headers: outHeaders,
1459
- method: fetchMethod,
1460
- body: async () => resText,
1461
- json: async () => JSON.parse(resText)
1462
- };
1463
- }
1464
- };
1465
- void Promise.resolve(rule.handler(routeObj)).catch(() => {
1466
- }).finally(() => {
1467
- if (!handled) {
1468
- handled = true;
1469
- void cdpChannel.sendCommand("Fetch.continueRequest", { requestId: reqId }, sid ?? null).catch(() => {
1470
- });
1471
- }
1472
- });
1473
- return;
1841
+ let curUrl = url;
1842
+ let curMethod = String(reqObj.method ?? "GET");
1843
+ const rawHeaders = reqObj.headers ?? {};
1844
+ let curHeaders = {};
1845
+ for (const [k, v] of Object.entries(rawHeaders)) {
1846
+ curHeaders[k.toLowerCase()] = String(v);
1474
1847
  }
1475
- if (rule.kind === "block") {
1848
+ let curPostData = typeof reqObj.postData === "string" ? reqObj.postData : null;
1849
+ let hasOverrides = false;
1850
+ if (curMethod.toUpperCase() === "OPTIONS" && Boolean(curHeaders["access-control-request-method"]) && matchingRules[0]?.kind !== "block") {
1851
+ const reqOrigin = curHeaders["origin"];
1852
+ const allowOrigin = reqOrigin && reqOrigin !== "null" ? reqOrigin : "*";
1853
+ const reqMethod = curHeaders["access-control-request-method"] || "GET, POST, PUT, PATCH, DELETE, OPTIONS";
1854
+ const reqHdrs = curHeaders["access-control-request-headers"] || "*";
1855
+ const preflightHeaders = [
1856
+ { name: "Access-Control-Allow-Origin", value: allowOrigin },
1857
+ {
1858
+ name: "Access-Control-Allow-Methods",
1859
+ value: `${reqMethod}, GET, POST, PUT, PATCH, DELETE, OPTIONS`
1860
+ },
1861
+ { name: "Access-Control-Allow-Headers", value: reqHdrs },
1862
+ ...allowOrigin !== "*" ? [{ name: "Access-Control-Allow-Credentials", value: "true" }] : []
1863
+ ];
1476
1864
  void cdpChannel.sendCommand(
1477
- "Fetch.failRequest",
1478
- { requestId: reqId, errorReason: "BlockedByClient" },
1479
- sid ?? null
1480
- ).catch(() => {
1481
- });
1865
+ "Fetch.fulfillRequest",
1866
+ {
1867
+ requestId: reqId,
1868
+ responseCode: 204,
1869
+ responsePhrase: "No Content",
1870
+ responseHeaders: preflightHeaders,
1871
+ body: ""
1872
+ },
1873
+ sessionKey
1874
+ ).catch(ignoreBestEffortFailure);
1482
1875
  return;
1483
1876
  }
1484
- void fulfillWith(rule.response ?? {}).catch(() => {
1485
- });
1486
- });
1487
- if (useContexts) {
1488
- yield* Effect.tryPromise({
1489
- try: () => cdpChannel.sendCommand(
1490
- "Target.setDiscoverTargets",
1877
+ const continueRequest = async (overrides) => {
1878
+ const finalUrl = overrides?.url ?? (hasOverrides ? curUrl : void 0);
1879
+ const finalMethod = overrides?.method ?? (hasOverrides ? curMethod : void 0);
1880
+ const finalHeaders = overrides?.headers ?? (hasOverrides ? curHeaders : void 0);
1881
+ const finalPostData = overrides?.postData !== void 0 ? overrides.postData : hasOverrides && curPostData !== null ? curPostData : void 0;
1882
+ await cdpChannel.sendCommand(
1883
+ "Fetch.continueRequest",
1491
1884
  {
1492
- discover: true,
1493
- filter: [{ type: "page" }]
1885
+ requestId: reqId,
1886
+ ...finalUrl ? { url: finalUrl } : {},
1887
+ ...finalMethod ? { method: finalMethod } : {},
1888
+ ...finalHeaders ? {
1889
+ headers: Object.entries(finalHeaders).map(([name, value]) => ({
1890
+ name,
1891
+ value
1892
+ }))
1893
+ } : {},
1894
+ ...finalPostData !== void 0 ? { postData: Buffer.from(finalPostData, "utf8").toString("base64") } : {}
1494
1895
  },
1495
- null
1496
- ).catch(() => {
1497
- }),
1498
- catch: () => new DriverError({ message: "Failed to enable Target.setDiscoverTargets" })
1499
- }).pipe(Effect.catch(() => Effect.void));
1500
- activeSlot = yield* Effect.tryPromise({
1501
- try: () => createContextSlot(options.storageState),
1502
- catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
1503
- });
1504
- cdpChannel.setSessionId(activeSlot.sessionId);
1505
- activeAuthenticatorId = activeSlot.authenticatorId;
1506
- }
1507
- const resolveUrlAsync = async (rawUrl) => {
1508
- if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" || rawUrl.startsWith("data:") || rawUrl.startsWith("file:")) {
1509
- return rawUrl;
1510
- }
1511
- if (options.baseUrl && options.baseUrl !== "about:blank") {
1896
+ sessionKey
1897
+ );
1898
+ };
1899
+ const dispatchRuleAt = async (idx) => {
1900
+ if (idx >= matchingRules.length) {
1901
+ await continueRequest().catch(() => {
1902
+ });
1903
+ return;
1904
+ }
1905
+ const rule = matchingRules[idx];
1906
+ if (rule.kind === "block") {
1907
+ await cdpChannel.sendCommand(
1908
+ "Fetch.failRequest",
1909
+ { requestId: reqId, errorReason: "BlockedByClient" },
1910
+ sessionKey
1911
+ ).catch(() => {
1912
+ });
1913
+ return;
1914
+ }
1915
+ if (rule.kind === "mock") {
1916
+ await fulfillWith(rule.response ?? {}).catch(() => {
1917
+ });
1918
+ return;
1919
+ }
1920
+ if (rule.kind === "handler" && rule.handler) {
1921
+ const reqInfo = {
1922
+ url: curUrl,
1923
+ method: curMethod,
1924
+ headers: { ...curHeaders },
1925
+ resourceType: typeof params?.resourceType === "string" ? params.resourceType.toLowerCase() : void 0,
1926
+ postData: () => curPostData,
1927
+ postDataJSON: () => {
1928
+ if (!curPostData) return null;
1929
+ try {
1930
+ return JSON.parse(curPostData);
1931
+ } catch {
1932
+ return null;
1933
+ }
1934
+ }
1935
+ };
1936
+ let handled = false;
1937
+ let fellBack = false;
1938
+ const routeObj = {
1939
+ request: () => reqInfo,
1940
+ continue: async (overrides) => {
1941
+ if (handled) return;
1942
+ handled = true;
1943
+ await continueRequest(overrides);
1944
+ },
1945
+ fallback: async (overrides) => {
1946
+ if (handled) return;
1947
+ handled = true;
1948
+ fellBack = true;
1949
+ if (overrides) {
1950
+ hasOverrides = true;
1951
+ if (overrides.url) curUrl = overrides.url;
1952
+ if (overrides.method) curMethod = overrides.method;
1953
+ if (overrides.headers) curHeaders = { ...curHeaders, ...overrides.headers };
1954
+ if (overrides.postData !== void 0) curPostData = overrides.postData;
1955
+ }
1956
+ await dispatchRuleAt(idx + 1);
1957
+ },
1958
+ abort: async (errorCode) => {
1959
+ if (handled) return;
1960
+ handled = true;
1961
+ await cdpChannel.sendCommand(
1962
+ "Fetch.failRequest",
1963
+ { requestId: reqId, errorReason: errorCode ?? "Failed" },
1964
+ sessionKey
1965
+ );
1966
+ },
1967
+ fulfill: async (response) => {
1968
+ if (handled) return;
1969
+ handled = true;
1970
+ await fulfillWith(response);
1971
+ },
1972
+ fetch: async (overrides) => {
1973
+ const targetUrl = overrides?.url ?? curUrl;
1974
+ const fetchHeaders = { ...curHeaders, ...overrides?.headers };
1975
+ const fetchMethod = overrides?.method ?? curMethod;
1976
+ const body = overrides?.postData !== void 0 ? overrides.postData : fetchMethod !== "GET" && fetchMethod !== "HEAD" ? curPostData ?? void 0 : void 0;
1977
+ const res = await fetch(targetUrl, {
1978
+ method: fetchMethod,
1979
+ headers: fetchHeaders,
1980
+ ...body !== void 0 ? { body } : {}
1981
+ });
1982
+ const resText = await res.text();
1983
+ const outHeaders = {};
1984
+ res.headers.forEach((v, k) => {
1985
+ outHeaders[k.toLowerCase()] = v;
1986
+ });
1987
+ return {
1988
+ url: res.url || targetUrl,
1989
+ status: res.status,
1990
+ statusText: res.statusText,
1991
+ headers: outHeaders,
1992
+ method: fetchMethod,
1993
+ body: async () => resText,
1994
+ json: async () => JSON.parse(resText)
1995
+ };
1996
+ }
1997
+ };
1998
+ try {
1999
+ await rule.handler(routeObj);
2000
+ } catch {
2001
+ } finally {
2002
+ if (!handled && !fellBack) {
2003
+ handled = true;
2004
+ await continueRequest().catch(() => {
2005
+ });
2006
+ }
2007
+ }
2008
+ }
2009
+ };
2010
+ void dispatchRuleAt(0);
2011
+ });
2012
+ if (!hasExplicitUserAgent) {
2013
+ const browserVer = yield* Effect_exports.tryPromise({
2014
+ try: () => cdpChannel.sendCommand("Browser.getVersion", {}, null, 2e3),
2015
+ catch: () => null
2016
+ }).pipe(Effect_exports.catch(() => Effect_exports.succeed(null)));
2017
+ const rawUa = browserVer?.userAgent;
2018
+ if (rawUa && /HeadlessChrome\//i.test(rawUa)) {
2019
+ defaultCleanUserAgent = rawUa.replaceAll(/HeadlessChrome\//gi, "Chrome/");
2020
+ cachedUserAgent = defaultCleanUserAgent;
2021
+ }
2022
+ }
2023
+ if (useContexts) {
2024
+ yield* Effect_exports.tryPromise({
2025
+ try: () => Promise.all([
2026
+ cdpChannel.sendCommand(
2027
+ "Target.setDiscoverTargets",
2028
+ {
2029
+ discover: true,
2030
+ filter: [{ type: "page" }, { type: "iframe" }]
2031
+ },
2032
+ null
2033
+ ).catch(() => {
2034
+ }),
2035
+ // Auto-attach popup pages paused at birth (`waitForDebuggerOnStart: true`) on top-level
2036
+ // drivers so Network.enable, clean UA, routes, and init scripts install before byte 0.
2037
+ // Skip on ephemeral child contexts (`_markClosedOnKill`) so closing a child context's
2038
+ // WebSocket never detaches from the parent context's page (preserves WebAuthn — 2.14).
2039
+ ...!options._markClosedOnKill ? [
2040
+ cdpChannel.sendCommand(
2041
+ "Target.setAutoAttach",
2042
+ {
2043
+ autoAttach: true,
2044
+ waitForDebuggerOnStart: true,
2045
+ flatten: true,
2046
+ filter: [{ type: "page", exclude: false }]
2047
+ },
2048
+ null
2049
+ ).catch(() => {
2050
+ })
2051
+ ] : []
2052
+ ]),
2053
+ catch: () => new DriverError({ message: "Failed to enable Target.setDiscoverTargets" })
2054
+ }).pipe(Effect_exports.catch(() => Effect_exports.void));
2055
+ activeSlot = yield* Effect_exports.tryPromise({
2056
+ try: () => createContextSlot(options.storageState),
2057
+ catch: (e) => new DriverError({ message: `Failed to create direct CDP browser context: ${e}` })
2058
+ });
2059
+ cdpChannel.setSessionId(activeSlot.sessionId);
2060
+ activeAuthenticatorId = activeSlot.authenticatorId;
2061
+ } else if (defaultCleanUserAgent) {
2062
+ yield* Effect_exports.tryPromise({
2063
+ try: () => cdpChannel.sendCommand(
2064
+ "Emulation.setUserAgentOverride",
2065
+ { userAgent: defaultCleanUserAgent },
2066
+ null
2067
+ ),
2068
+ catch: () => null
2069
+ }).pipe(Effect_exports.catch(() => Effect_exports.void));
2070
+ }
2071
+ const resolveUrlAsync = async (rawUrl) => {
2072
+ if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://") || rawUrl === "about:blank" || rawUrl.startsWith("data:") || rawUrl.startsWith("file:")) {
2073
+ return rawUrl;
2074
+ }
2075
+ if (options.baseUrl && options.baseUrl !== "about:blank") {
1512
2076
  try {
1513
2077
  return new URL(rawUrl, options.baseUrl).toString();
1514
2078
  } catch {
@@ -1526,48 +2090,154 @@ function makeLightweightCdpDriver(options) {
1526
2090
  }
1527
2091
  return rawUrl;
1528
2092
  };
2093
+ const ensureDownloadBehaviorForActiveContext = async () => {
2094
+ if (!downloadDir) {
2095
+ const dlBaseDir = process.platform === "linux" && tmpdir().length > 40 ? "/tmp" : tmpdir();
2096
+ downloadDir = mkdtempSync(join2(dlBaseDir, "spana-cdp-dl-"));
2097
+ }
2098
+ const ctxId = activeSlot?.browserContextId;
2099
+ const ctxKey = ctxId ?? "__default__";
2100
+ if (downloadConfiguredContexts.has(ctxKey)) return;
2101
+ await cdpChannel.sendCommand(
2102
+ "Browser.setDownloadBehavior",
2103
+ {
2104
+ behavior: "allowAndName",
2105
+ downloadPath: downloadDir,
2106
+ eventsEnabled: true,
2107
+ ...ctxId ? { browserContextId: ctxId } : {}
2108
+ },
2109
+ null
2110
+ );
2111
+ downloadConfiguredContexts.add(ctxKey);
2112
+ };
1529
2113
  const navigate = async (rawUrl) => {
1530
2114
  const target = await resolveUrlAsync(rawUrl);
2115
+ lastNavigationStatus = null;
1531
2116
  if (!useContexts) {
1532
2117
  await cdpChannel.sendCommand("Page.enable").catch(() => {
1533
2118
  });
1534
- await cdpChannel.sendCommand("Page.navigate", { url: target });
2119
+ const navRes = await cdpChannel.sendCommand(
2120
+ "Page.navigate",
2121
+ { url: target },
2122
+ void 0,
2123
+ navigationTimeoutMs
2124
+ );
2125
+ if (navRes?.frameId) mainFrameId = navRes.frameId;
1535
2126
  return;
1536
2127
  }
1537
2128
  const waitUntil = options.waitUntil ?? "domcontentloaded";
1538
2129
  const targetSid = activeSlot?.sessionId;
1539
2130
  if (target === "about:blank") {
1540
2131
  if (isAtBlank) return;
1541
- await cdpChannel.sendCommand("Page.navigate", { url: target }, void 0, 4e3).catch(() => {
2132
+ await cdpChannel.sendCommand(
2133
+ "Page.navigate",
2134
+ { url: target },
2135
+ void 0,
2136
+ Math.min(4e3, navigationTimeoutMs)
2137
+ ).catch(() => {
1542
2138
  });
1543
2139
  isAtBlank = true;
1544
2140
  return;
1545
2141
  }
1546
2142
  isAtBlank = false;
1547
2143
  if (waitUntil === "commit") {
1548
- await cdpChannel.sendCommand("Page.navigate", { url: target });
2144
+ const commitRes = await cdpChannel.sendCommand(
2145
+ "Page.navigate",
2146
+ { url: target },
2147
+ void 0,
2148
+ navigationTimeoutMs
2149
+ );
2150
+ if (commitRes?.frameId) mainFrameId = commitRes.frameId;
2151
+ if (commitRes?.errorText && commitRes.errorText !== "net::ERR_ABORTED") {
2152
+ throw new Error(`Navigation to "${target}" failed: ${commitRes.errorText}`);
2153
+ }
1549
2154
  return;
1550
2155
  }
1551
2156
  const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
1552
- const waiter = cdpChannel.waitForEvent(
2157
+ let targetFrameCommitted = false;
2158
+ let expectedLoaderId;
2159
+ const seenLoaderIds = /* @__PURE__ */ new Set();
2160
+ const unsubNavCommit = cdpChannel.onEvent("Page.frameNavigated", (params, sid) => {
2161
+ if (targetSid && sid && sid !== targetSid) return;
2162
+ if (params?.frame?.parentId) return;
2163
+ const loaderId = typeof params?.frame?.loaderId === "string" ? params.frame.loaderId : void 0;
2164
+ if (loaderId) seenLoaderIds.add(loaderId);
2165
+ const frameUrl = typeof params?.frame?.url === "string" ? params.frame.url : "";
2166
+ if (expectedLoaderId) {
2167
+ if (loaderId === expectedLoaderId || frameUrl && frameUrl !== "about:blank") {
2168
+ targetFrameCommitted = true;
2169
+ }
2170
+ } else if (frameUrl !== "about:blank") {
2171
+ targetFrameCommitted = true;
2172
+ }
2173
+ });
2174
+ const navStart = Date.now();
2175
+ const waiter = cdpChannel.waitForEventCancellable(
1553
2176
  eventName,
1554
- 15e3,
1555
- (_p, sid) => !targetSid || !sid || sid === targetSid
2177
+ navigationTimeoutMs,
2178
+ (_p, sid) => (!targetSid || !sid || sid === targetSid) && targetFrameCommitted
1556
2179
  );
1557
- await cdpChannel.sendCommand("Page.navigate", { url: target });
1558
- await waiter.catch(() => {
1559
- });
2180
+ waiter.promise.catch(handledByLaterAwait);
2181
+ try {
2182
+ const navRes = await cdpChannel.sendCommand(
2183
+ "Page.navigate",
2184
+ { url: target },
2185
+ void 0,
2186
+ navigationTimeoutMs
2187
+ );
2188
+ if (navRes?.frameId) mainFrameId = navRes.frameId;
2189
+ if (navRes?.errorText && navRes.errorText !== "net::ERR_ABORTED") {
2190
+ throw new Error(`Navigation to "${target}" failed: ${navRes.errorText}`);
2191
+ }
2192
+ if (navRes?.loaderId) {
2193
+ expectedLoaderId = navRes.loaderId;
2194
+ if (seenLoaderIds.has(navRes.loaderId)) {
2195
+ targetFrameCommitted = true;
2196
+ }
2197
+ try {
2198
+ await waiter.promise;
2199
+ } catch (waitErr) {
2200
+ const elapsed = Date.now() - navStart;
2201
+ throw new Error(
2202
+ `Navigation to "${target}" timed out waiting for ${waitUntil} after ${elapsed}ms (navigationTimeout: ${navigationTimeoutMs}ms): ${waitErr instanceof Error ? waitErr.message : String(waitErr)}`,
2203
+ { cause: waitErr }
2204
+ );
2205
+ }
2206
+ }
2207
+ } finally {
2208
+ unsubNavCommit();
2209
+ waiter.cancel();
2210
+ }
1560
2211
  schedulePrefetch();
1561
2212
  };
1562
2213
  const ensureFetchIntercept = async () => {
1563
- if (fetchInterceptEnabled) return;
1564
- fetchInterceptEnabled = true;
1565
- await cdpChannel.sendCommand("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
2214
+ const sessions = activeSlot ? Array.from(/* @__PURE__ */ new Set([activeSlot.sessionId, ...activeSlot.tabs.map((t) => t.sessionId)])) : [null];
2215
+ const enableParams = buildFetchEnableParams();
2216
+ for (const sid of sessions) fetchEnabledSessions.add(sid);
2217
+ await Promise.all(
2218
+ sessions.map(
2219
+ (sid) => cdpChannel.sendCommand("Fetch.enable", enableParams, sid).catch(() => {
2220
+ fetchEnabledSessions.delete(sid);
2221
+ })
2222
+ )
2223
+ );
2224
+ };
2225
+ const disableAllFetchInterception = async () => {
2226
+ if (activeHttpCredentials) {
2227
+ return;
2228
+ }
2229
+ if (fetchEnabledSessions.size === 0) return;
2230
+ const sessions = Array.from(fetchEnabledSessions);
2231
+ fetchEnabledSessions.clear();
2232
+ await Promise.all(
2233
+ sessions.map((sid) => cdpChannel.sendCommand("Fetch.disable", {}, sid).catch(() => {
2234
+ }))
2235
+ );
1566
2236
  };
1567
2237
  let coverageSession;
1568
2238
  const service = {
1569
2239
  domChannel: cdpChannel,
1570
- startJSCoverage: () => Effect.tryPromise({
2240
+ startJSCoverage: () => Effect_exports.tryPromise({
1571
2241
  try: async () => {
1572
2242
  const session = activeSlot?.sessionId ?? null;
1573
2243
  await cdpChannel.sendCommand("Profiler.enable", {}, session);
@@ -1586,7 +2256,7 @@ function makeLightweightCdpDriver(options) {
1586
2256
  },
1587
2257
  catch: (error) => new DriverError({ message: `CDP JavaScript coverage is unavailable: ${error}` })
1588
2258
  }),
1589
- stopJSCoverage: () => Effect.tryPromise({
2259
+ stopJSCoverage: () => Effect_exports.tryPromise({
1590
2260
  try: async () => {
1591
2261
  const session = coverageSession;
1592
2262
  coverageSession = void 0;
@@ -1607,7 +2277,7 @@ function makeLightweightCdpDriver(options) {
1607
2277
  },
1608
2278
  catch: (error) => new DriverError({ message: `CDP JavaScript coverage collection failed: ${error}` })
1609
2279
  }),
1610
- beginFlow: (_flowName) => Effect.tryPromise({
2280
+ beginFlow: (_flowName) => Effect_exports.tryPromise({
1611
2281
  try: async () => {
1612
2282
  const ensureVirtualAuthenticatorForSlot = async (slot, clearExisting) => {
1613
2283
  if (!options.virtualAuthenticator) {
@@ -1723,73 +2393,112 @@ function makeLightweightCdpDriver(options) {
1723
2393
  jsErrors.length = 0;
1724
2394
  wasmTraps.length = 0;
1725
2395
  navigationUrls.length = 0;
2396
+ lastNavigationStatus = null;
2397
+ authAttemptedRequestIds.clear();
1726
2398
  dialogHandler = null;
1727
2399
  routeRules.length = 0;
1728
2400
  currentNetworkConditions = void 0;
2401
+ heldModifiers = 0;
2402
+ pressedMouseButtons = 0;
2403
+ lastMouseX = 0;
2404
+ lastMouseY = 0;
1729
2405
  width = initialWidth;
1730
2406
  height = initialHeight;
2407
+ currentDeviceScaleFactor = initialDeviceScaleFactor;
2408
+ currentMobile = initialMobile;
2409
+ currentHasTouch = initialHasTouch;
2410
+ activeUserAgent = options.emulation?.userAgent;
2411
+ activeLocale = options.emulation?.locale;
2412
+ const hadSubframeNavigation = hasSubframeNavigation;
2413
+ hasSubframeNavigation = false;
2414
+ const clearAllDirtyFlags = () => {
2415
+ hasDeviceMetricsDirty = false;
2416
+ hasTouchEmulationDirty = false;
2417
+ hasUserAgentDirty = false;
2418
+ hasLocaleDirty = false;
2419
+ hasEmulatedMediaDirty = false;
2420
+ hasTimezoneDirty = false;
2421
+ hasNetworkConditionsDirty = false;
2422
+ permissionsMutated = false;
2423
+ geolocationMutated = false;
2424
+ slotNeedsHealthCheck = false;
2425
+ };
1731
2426
  await cleanupFlowScopedHooks();
1732
- if (useContexts && options.freshContextPerFlow && hasRunFirstFlow) {
1733
- if (contextIsolation === "hot-cache" && activeSlot) {
1734
- const slotWasHealthy = await ensureActiveSlotHealthy();
2427
+ if (useContexts && effectiveFreshContextPerFlow && hasRunFirstFlow) {
2428
+ if (contextIsolation === "hot-cache" && activeSlot && !slotHasCustomStorageState) {
2429
+ const slotWasHealthy = slotNeedsHealthCheck || activeSlot.tabs.length === 0 ? await ensureActiveSlotHealthy() : true;
2430
+ slotNeedsHealthCheck = false;
1735
2431
  if (slotWasHealthy && activeSlot) {
1736
- const frameIdsToQuery = [];
1737
- const frameTreeRes = await cdpChannel.sendCommand("Page.getFrameTree", {}, activeSlot.sessionId, 1500).catch(() => null);
1738
- const collectFrameOrigins = (node) => {
1739
- if (!node) return;
1740
- const u = node.frame?.url;
1741
- if (typeof node.frame?.id === "string") {
1742
- frameIdsToQuery.push({ frameId: node.frame.id, sid: activeSlot.sessionId });
1743
- }
1744
- if (typeof u === "string") {
1745
- try {
1746
- const parsed = new URL(u);
1747
- if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1748
- visitedOrigins.add(parsed.origin);
2432
+ if (hadSubframeNavigation || activeChildSessions.length > 0) {
2433
+ const frameIdsToQuery = [];
2434
+ const frameTreeRes = await cdpChannel.sendCommand("Page.getFrameTree", {}, activeSlot.sessionId, 1500).catch(() => null);
2435
+ const collectFrameOrigins = (node) => {
2436
+ if (!node) return;
2437
+ const u = node.frame?.url;
2438
+ if (typeof node.frame?.id === "string") {
2439
+ frameIdsToQuery.push({
2440
+ frameId: node.frame.id,
2441
+ sid: activeSlot.sessionId
2442
+ });
2443
+ }
2444
+ if (typeof u === "string") {
2445
+ try {
2446
+ const parsed = new URL(u);
2447
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
2448
+ visitedOrigins.add(parsed.origin);
2449
+ }
2450
+ } catch {
1749
2451
  }
1750
- } catch {
1751
2452
  }
1752
- }
1753
- if (Array.isArray(node.childFrames)) {
1754
- for (const child of node.childFrames) collectFrameOrigins(child);
1755
- }
1756
- };
1757
- collectFrameOrigins(frameTreeRes?.frameTree);
1758
- for (const child of activeChildSessions) {
1759
- if (child.targetId) {
1760
- frameIdsToQuery.push({ frameId: child.targetId, sid: child.sessionId });
1761
- }
1762
- if (child.url) {
1763
- try {
1764
- const parsed = new URL(child.url);
1765
- if (parsed.protocol === "http:" || parsed.protocol === "https:") {
1766
- visitedOrigins.add(parsed.origin);
2453
+ if (Array.isArray(node.childFrames)) {
2454
+ for (const child of node.childFrames) collectFrameOrigins(child);
2455
+ }
2456
+ };
2457
+ collectFrameOrigins(frameTreeRes?.frameTree);
2458
+ for (const child of activeChildSessions) {
2459
+ if (child.targetId) {
2460
+ frameIdsToQuery.push({ frameId: child.targetId, sid: child.sessionId });
2461
+ }
2462
+ if (child.url) {
2463
+ try {
2464
+ const parsed = new URL(child.url);
2465
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
2466
+ visitedOrigins.add(parsed.origin);
2467
+ }
2468
+ } catch {
1767
2469
  }
1768
- } catch {
2470
+ }
2471
+ }
2472
+ if (frameIdsToQuery.length > 0) {
2473
+ const skResults = await Promise.all(
2474
+ frameIdsToQuery.map(
2475
+ ({ frameId, sid }) => cdpChannel.sendCommand("Storage.getStorageKeyForFrame", { frameId }, sid, 1e3).catch(() => null)
2476
+ )
2477
+ );
2478
+ for (const res of skResults) {
2479
+ const sk = res?.storageKey;
2480
+ if (sk) visitedStorageKeys.add(sk);
1769
2481
  }
1770
2482
  }
1771
2483
  }
1772
- if (frameIdsToQuery.length > 0) {
1773
- const skResults = await Promise.all(
1774
- frameIdsToQuery.map(
1775
- ({ frameId, sid }) => cdpChannel.sendCommand("Storage.getStorageKeyForFrame", { frameId }, sid, 1e3).catch(() => null)
2484
+ if (activeChildSessions.length > 0) {
2485
+ await Promise.all(
2486
+ activeChildSessions.map(
2487
+ (child) => cdpChannel.sendCommand(
2488
+ "Runtime.evaluate",
2489
+ {
2490
+ expression: "try { localStorage.clear(); sessionStorage.clear(); } catch {}",
2491
+ returnByValue: true
2492
+ },
2493
+ child.sessionId,
2494
+ 500
2495
+ ).catch(() => {
2496
+ })
1776
2497
  )
1777
2498
  );
1778
- for (const res of skResults) {
1779
- const sk = res?.storageKey;
1780
- if (sk) visitedStorageKeys.add(sk);
1781
- }
1782
2499
  }
1783
2500
  const preResetOps = [];
1784
- for (const child of activeChildSessions) {
1785
- preResetOps.push(
1786
- cdpChannel.evaluateOnSession(
1787
- child.sessionId,
1788
- "try { localStorage.clear(); sessionStorage.clear(); } catch {}"
1789
- ).catch(() => {
1790
- })
1791
- );
1792
- }
2501
+ let blankNavFailed = false;
1793
2502
  if (activeSlot.tabs.length > 1) {
1794
2503
  const primaryTab = activeSlot.tabs[0];
1795
2504
  const extraTabs = activeSlot.tabs.slice(1);
@@ -1822,35 +2531,78 @@ function makeLightweightCdpDriver(options) {
1822
2531
  } catch {}
1823
2532
  })()`
1824
2533
  ).catch(() => {
1825
- }).then(
1826
- () => cdpChannel.sendCommand("Page.navigate", { url: "about:blank" }, void 0, 4e3).catch(() => {
1827
- })
1828
- ).then(() => {
1829
- isAtBlank = true;
2534
+ }).then(async () => {
2535
+ const targetSid = activeSlot?.sessionId;
2536
+ const blankWaiter = cdpChannel.waitForEventCancellable(
2537
+ "Page.domContentEventFired",
2538
+ 1500,
2539
+ (_p, sid) => !targetSid || !sid || sid === targetSid
2540
+ );
2541
+ blankWaiter.promise.catch(handledByLaterAwait);
2542
+ try {
2543
+ await cdpChannel.sendCommand(
2544
+ "Page.navigate",
2545
+ { url: "about:blank" },
2546
+ void 0,
2547
+ 4e3
2548
+ );
2549
+ await blankWaiter.promise.catch(() => {
2550
+ });
2551
+ isAtBlank = true;
2552
+ } catch {
2553
+ blankNavFailed = true;
2554
+ } finally {
2555
+ blankWaiter.cancel();
2556
+ }
1830
2557
  })
1831
2558
  );
1832
2559
  }
1833
2560
  if (preResetOps.length > 0) {
1834
2561
  await Promise.all(preResetOps);
1835
2562
  }
2563
+ if (blankNavFailed) {
2564
+ const recovered = await ensureActiveSlotHealthy();
2565
+ if (!recovered) {
2566
+ cdpChannel.clearChildSessions();
2567
+ await disableAllFetchInterception();
2568
+ clearAllDirtyFlags();
2569
+ if (activeSlot && options.virtualAuthenticator) {
2570
+ await ensureVirtualAuthenticatorForSlot(activeSlot, true);
2571
+ } else if (activeSlot) {
2572
+ activeAuthenticatorId = activeSlot.authenticatorId;
2573
+ }
2574
+ hasRunFirstFlow = true;
2575
+ return;
2576
+ }
2577
+ }
1836
2578
  cdpChannel.clearChildSessions();
1837
2579
  const resetOps = [
1838
- cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
2580
+ cdpChannel.sendCommand("Network.clearBrowserCookies", {}, void 0, 2e3).catch(() => {
1839
2581
  })
1840
2582
  ];
1841
2583
  const storageTypes = "cookies,local_storage,session_storage,indexeddb,cache_storage,service_workers,file_systems";
1842
2584
  for (const origin of visitedOrigins) {
1843
2585
  resetOps.push(
1844
- cdpChannel.sendCommand("Storage.clearDataForOrigin", { origin, storageTypes }).catch(() => {
2586
+ cdpChannel.sendCommand(
2587
+ "Storage.clearDataForOrigin",
2588
+ { origin, storageTypes },
2589
+ void 0,
2590
+ 2e3
2591
+ ).catch(() => {
1845
2592
  })
1846
2593
  );
1847
2594
  }
1848
2595
  for (const storageKey of visitedStorageKeys) {
1849
2596
  resetOps.push(
1850
- cdpChannel.sendCommand("Storage.clearDataForStorageKey", {
1851
- storageKey,
1852
- storageTypes
1853
- }).catch(() => {
2597
+ cdpChannel.sendCommand(
2598
+ "Storage.clearDataForStorageKey",
2599
+ {
2600
+ storageKey,
2601
+ storageTypes
2602
+ },
2603
+ void 0,
2604
+ 2e3
2605
+ ).catch(() => {
1854
2606
  })
1855
2607
  );
1856
2608
  }
@@ -1872,34 +2624,80 @@ function makeLightweightCdpDriver(options) {
1872
2624
  })
1873
2625
  );
1874
2626
  }
1875
- if (fetchInterceptEnabled) {
1876
- fetchInterceptEnabled = false;
1877
- resetOps.push(cdpChannel.sendCommand("Fetch.disable").catch(() => {
1878
- }));
2627
+ if (fetchEnabledSessions.size > 0 && !activeHttpCredentials) {
2628
+ resetOps.push(disableAllFetchInterception());
1879
2629
  }
1880
- if (viewportMutated) {
1881
- viewportMutated = false;
2630
+ if (hasDeviceMetricsDirty || hasTouchEmulationDirty) {
2631
+ const needsTouchReset = hasTouchEmulationDirty;
2632
+ hasDeviceMetricsDirty = false;
2633
+ hasTouchEmulationDirty = false;
2634
+ width = initialWidth;
2635
+ height = initialHeight;
2636
+ currentDeviceScaleFactor = initialDeviceScaleFactor;
2637
+ currentMobile = initialMobile;
2638
+ currentHasTouch = initialHasTouch;
2639
+ if (needsTouchReset) {
2640
+ resetOps.push(
2641
+ (async () => {
2642
+ await cdpChannel.sendCommand("Emulation.clearDeviceMetricsOverride", {}).catch(() => {
2643
+ });
2644
+ await cdpChannel.sendCommand("Emulation.setTouchEmulationEnabled", {
2645
+ enabled: initialHasTouch,
2646
+ ...initialHasTouch ? { maxTouchPoints: 5 } : {}
2647
+ }).catch(() => {
2648
+ });
2649
+ if (!initialHasTouch && !initialMobile) {
2650
+ await cdpChannel.sendCommand("Emulation.setEmitTouchEventsForMouse", {
2651
+ enabled: false,
2652
+ configuration: "desktop"
2653
+ }).catch(() => {
2654
+ });
2655
+ }
2656
+ await cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
2657
+ width: initialWidth,
2658
+ height: initialHeight,
2659
+ deviceScaleFactor: initialDeviceScaleFactor,
2660
+ mobile: initialMobile
2661
+ }).catch(() => {
2662
+ });
2663
+ })()
2664
+ );
2665
+ } else {
2666
+ resetOps.push(
2667
+ cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
2668
+ width: initialWidth,
2669
+ height: initialHeight,
2670
+ deviceScaleFactor: initialDeviceScaleFactor,
2671
+ mobile: initialMobile
2672
+ }).catch(() => {
2673
+ })
2674
+ );
2675
+ }
2676
+ }
2677
+ if (hasLocaleDirty) {
2678
+ hasLocaleDirty = false;
2679
+ activeLocale = options.emulation?.locale;
2680
+ const defaultLocale = options.emulation?.locale ?? "";
1882
2681
  resetOps.push(
1883
- cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
1884
- width: initialWidth,
1885
- height: initialHeight,
1886
- deviceScaleFactor: 1,
1887
- mobile: false
1888
- }).catch(() => {
2682
+ cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: defaultLocale }).catch(() => {
1889
2683
  })
1890
2684
  );
1891
2685
  }
1892
- if (emulationMutated) {
1893
- emulationMutated = false;
2686
+ if (hasUserAgentDirty) {
2687
+ hasUserAgentDirty = false;
2688
+ activeUserAgent = options.emulation?.userAgent;
1894
2689
  const defaultLocale = options.emulation?.locale ?? "";
1895
2690
  resetOps.push(
1896
- cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: defaultLocale }).catch(() => {
1897
- }),
1898
2691
  cdpChannel.sendCommand("Emulation.setUserAgentOverride", {
1899
- userAgent: cachedUserAgent || "Mozilla/5.0",
1900
- acceptLanguage: defaultLocale ? defaultLocale.includes("-") ? `${defaultLocale},${defaultLocale.split("-")[0]};q=0.9` : defaultLocale : ""
2692
+ userAgent: options.emulation?.userAgent || defaultCleanUserAgent || cachedUserAgent || "Mozilla/5.0",
2693
+ acceptLanguage: buildAcceptLanguage(defaultLocale) ?? ""
1901
2694
  }).catch(() => {
1902
- }),
2695
+ })
2696
+ );
2697
+ }
2698
+ if (hasEmulatedMediaDirty) {
2699
+ hasEmulatedMediaDirty = false;
2700
+ resetOps.push(
1903
2701
  cdpChannel.sendCommand("Emulation.setEmulatedMedia", {
1904
2702
  media: "",
1905
2703
  features: [
@@ -1913,128 +2711,209 @@ function makeLightweightCdpDriver(options) {
1913
2711
  }
1914
2712
  ]
1915
2713
  }).catch(() => {
1916
- }),
2714
+ })
2715
+ );
2716
+ }
2717
+ if (hasTimezoneDirty) {
2718
+ hasTimezoneDirty = false;
2719
+ resetOps.push(
1917
2720
  cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
1918
2721
  timezoneId: options.emulation?.timezoneId ?? ""
1919
2722
  }).catch(() => {
1920
2723
  })
1921
2724
  );
1922
2725
  }
1923
- resetOps.push(
1924
- cdpChannel.sendCommand("Network.emulateNetworkConditions", {
1925
- offline: false,
1926
- latency: 0,
1927
- downloadThroughput: -1,
1928
- uploadThroughput: -1
1929
- }).catch(() => {
1930
- })
1931
- );
2726
+ if (hasNetworkConditionsDirty) {
2727
+ hasNetworkConditionsDirty = false;
2728
+ resetOps.push(
2729
+ cdpChannel.sendCommand("Network.emulateNetworkConditions", {
2730
+ offline: false,
2731
+ latency: 0,
2732
+ downloadThroughput: -1,
2733
+ uploadThroughput: -1
2734
+ }).catch(() => {
2735
+ })
2736
+ );
2737
+ }
1932
2738
  await Promise.all(resetOps);
1933
- const state = await loadStorageStateFile(options.storageState);
1934
- if (state?.cookies && state.cookies.length > 0) {
1935
- await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
1936
- });
2739
+ if (options.storageState) {
2740
+ const state = await loadStorageStateFile(options.storageState);
2741
+ if (state?.cookies && state.cookies.length > 0) {
2742
+ await cdpChannel.sendCommand("Network.setCookies", { cookies: state.cookies }).catch(() => {
2743
+ });
2744
+ }
1937
2745
  }
1938
2746
  } else {
1939
2747
  cdpChannel.clearChildSessions();
1940
- fetchInterceptEnabled = false;
1941
- emulationMutated = false;
1942
- viewportMutated = false;
1943
- permissionsMutated = false;
1944
- geolocationMutated = false;
2748
+ await disableAllFetchInterception();
2749
+ clearAllDirtyFlags();
1945
2750
  }
1946
- if (activeSlot) {
2751
+ if (activeSlot && options.virtualAuthenticator) {
1947
2752
  await ensureVirtualAuthenticatorForSlot(activeSlot, true);
2753
+ } else if (activeSlot) {
2754
+ activeAuthenticatorId = activeSlot.authenticatorId;
1948
2755
  }
1949
2756
  } else {
1950
2757
  cdpChannel.clearChildSessions();
1951
- fetchInterceptEnabled = false;
1952
- emulationMutated = false;
1953
- viewportMutated = false;
1954
- permissionsMutated = false;
1955
- geolocationMutated = false;
2758
+ await disableAllFetchInterception();
2759
+ clearAllDirtyFlags();
2760
+ width = initialWidth;
2761
+ height = initialHeight;
2762
+ currentDeviceScaleFactor = initialDeviceScaleFactor;
2763
+ currentMobile = initialMobile;
2764
+ currentHasTouch = initialHasTouch;
2765
+ activeUserAgent = options.emulation?.userAgent;
2766
+ activeLocale = options.emulation?.locale;
2767
+ slotHasCustomStorageState = false;
1956
2768
  isAtBlank = true;
1957
2769
  const previousSlot = activeSlot;
1958
2770
  const pending = prefetchedSlotPromise;
1959
2771
  prefetchedSlotPromise = void 0;
1960
2772
  activeSlot = pending ? await pending : await createContextSlot(options.storageState);
1961
2773
  cdpChannel.setSessionId(activeSlot.sessionId);
1962
- await ensureVirtualAuthenticatorForSlot(activeSlot, false);
2774
+ if (options.virtualAuthenticator) {
2775
+ await ensureVirtualAuthenticatorForSlot(activeSlot, false);
2776
+ } else {
2777
+ activeAuthenticatorId = activeSlot.authenticatorId;
2778
+ }
1963
2779
  if (previousSlot) {
1964
2780
  disposeSlotInBackground(previousSlot);
1965
2781
  }
1966
2782
  }
1967
2783
  } else if (activeSlot) {
1968
2784
  cdpChannel.clearChildSessions();
1969
- await ensureActiveSlotHealthy();
1970
- if (activeSlot) {
2785
+ await disableAllFetchInterception();
2786
+ if (slotNeedsHealthCheck || activeSlot.tabs.length === 0) {
2787
+ await ensureActiveSlotHealthy();
2788
+ slotNeedsHealthCheck = false;
2789
+ }
2790
+ if (activeSlot && options.virtualAuthenticator) {
1971
2791
  await ensureVirtualAuthenticatorForSlot(activeSlot, false);
2792
+ } else if (activeSlot) {
2793
+ activeAuthenticatorId = activeSlot.authenticatorId;
1972
2794
  }
1973
2795
  }
1974
2796
  hasRunFirstFlow = true;
1975
2797
  },
1976
2798
  catch: (e) => new DriverError({ message: `CDP beginFlow failed: ${e}` })
1977
2799
  }),
1978
- dumpHierarchy: () => Effect.tryPromise({
2800
+ dumpHierarchy: () => Effect_exports.tryPromise({
1979
2801
  try: async () => {
1980
2802
  const raw = await cdpChannel.evaluate(CDP_DUMP_HIERARCHY_SCRIPT);
1981
2803
  return raw ?? "{}";
1982
2804
  },
1983
2805
  catch: (e) => new DriverError({ message: `CDP dumpHierarchy failed: ${e}` })
1984
2806
  }),
1985
- tapAtCoordinate: (x, y) => Effect.tryPromise({
2807
+ tapAtCoordinate: (x, y) => Effect_exports.tryPromise({
1986
2808
  try: async () => {
2809
+ lastMouseX = x;
2810
+ lastMouseY = y;
1987
2811
  await Promise.all([
1988
2812
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1989
2813
  type: "mouseMoved",
1990
2814
  x,
1991
- y
2815
+ y,
2816
+ modifiers: heldModifiers,
2817
+ pointerType: "mouse"
1992
2818
  }),
1993
2819
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
1994
2820
  type: "mousePressed",
1995
2821
  x,
1996
2822
  y,
1997
2823
  button: "left",
1998
- clickCount: 1
2824
+ buttons: 1,
2825
+ clickCount: 1,
2826
+ modifiers: heldModifiers,
2827
+ pointerType: "mouse"
1999
2828
  }),
2000
2829
  cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2001
2830
  type: "mouseReleased",
2002
2831
  x,
2003
2832
  y,
2004
2833
  button: "left",
2005
- clickCount: 1
2834
+ buttons: 0,
2835
+ clickCount: 1,
2836
+ modifiers: heldModifiers,
2837
+ pointerType: "mouse"
2006
2838
  })
2007
2839
  ]);
2008
2840
  },
2009
2841
  catch: (e) => new DriverError({ message: `CDP tap failed at (${x}, ${y}): ${e}` })
2010
2842
  }),
2011
- doubleTapAtCoordinate: (x, y) => Effect.tryPromise({
2843
+ doubleTapAtCoordinate: (x, y) => Effect_exports.tryPromise({
2012
2844
  try: async () => {
2845
+ lastMouseX = x;
2846
+ lastMouseY = y;
2847
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2848
+ type: "mouseMoved",
2849
+ x,
2850
+ y,
2851
+ modifiers: heldModifiers,
2852
+ pointerType: "mouse"
2853
+ });
2854
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2855
+ type: "mousePressed",
2856
+ x,
2857
+ y,
2858
+ button: "left",
2859
+ buttons: 1,
2860
+ clickCount: 1,
2861
+ modifiers: heldModifiers,
2862
+ pointerType: "mouse"
2863
+ });
2864
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2865
+ type: "mouseReleased",
2866
+ x,
2867
+ y,
2868
+ button: "left",
2869
+ buttons: 0,
2870
+ clickCount: 1,
2871
+ modifiers: heldModifiers,
2872
+ pointerType: "mouse"
2873
+ });
2013
2874
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2014
2875
  type: "mousePressed",
2015
2876
  x,
2016
2877
  y,
2017
2878
  button: "left",
2018
- clickCount: 2
2879
+ buttons: 1,
2880
+ clickCount: 2,
2881
+ modifiers: heldModifiers,
2882
+ pointerType: "mouse"
2019
2883
  });
2020
2884
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2021
2885
  type: "mouseReleased",
2022
2886
  x,
2023
2887
  y,
2024
2888
  button: "left",
2025
- clickCount: 2
2889
+ buttons: 0,
2890
+ clickCount: 2,
2891
+ modifiers: heldModifiers,
2892
+ pointerType: "mouse"
2026
2893
  });
2027
2894
  },
2028
2895
  catch: (e) => new DriverError({ message: `CDP doubleTap failed: ${e}` })
2029
2896
  }),
2030
- longPressAtCoordinate: (x, y, duration) => Effect.tryPromise({
2897
+ longPressAtCoordinate: (x, y, duration) => Effect_exports.tryPromise({
2031
2898
  try: async () => {
2899
+ lastMouseX = x;
2900
+ lastMouseY = y;
2901
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2902
+ type: "mouseMoved",
2903
+ x,
2904
+ y,
2905
+ modifiers: heldModifiers,
2906
+ pointerType: "mouse"
2907
+ });
2032
2908
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2033
2909
  type: "mousePressed",
2034
2910
  x,
2035
2911
  y,
2036
2912
  button: "left",
2037
- clickCount: 1
2913
+ buttons: 1,
2914
+ clickCount: 1,
2915
+ modifiers: heldModifiers,
2916
+ pointerType: "mouse"
2038
2917
  });
2039
2918
  await new Promise((r) => setTimeout(r, duration));
2040
2919
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -2042,12 +2921,15 @@ function makeLightweightCdpDriver(options) {
2042
2921
  x,
2043
2922
  y,
2044
2923
  button: "left",
2045
- clickCount: 1
2924
+ buttons: 0,
2925
+ clickCount: 1,
2926
+ modifiers: heldModifiers,
2927
+ pointerType: "mouse"
2046
2928
  });
2047
2929
  },
2048
2930
  catch: (e) => new DriverError({ message: `CDP longPress failed: ${e}` })
2049
2931
  }),
2050
- swipe: (startX, startY, endX, endY, duration = 300) => Effect.tryPromise({
2932
+ swipe: (startX, startY, endX, endY, duration = 300) => Effect_exports.tryPromise({
2051
2933
  try: async () => {
2052
2934
  const totalSteps = Math.max(4, Math.min(20, Math.round((duration || 300) / 20)));
2053
2935
  const stepDelayMs = duration > 0 ? Math.max(0, Math.floor(duration / totalSteps)) : 0;
@@ -2088,39 +2970,54 @@ function makeLightweightCdpDriver(options) {
2088
2970
  },
2089
2971
  catch: (e) => new DriverError({ message: `CDP swipe failed: ${e}` })
2090
2972
  }),
2091
- inputText: (text) => Effect.tryPromise({
2973
+ inputText: (text) => Effect_exports.tryPromise({
2092
2974
  try: async () => {
2093
2975
  await cdpChannel.sendCommand("Input.insertText", { text });
2094
2976
  },
2095
2977
  catch: (e) => new DriverError({ message: `CDP inputText failed: ${e}` })
2096
2978
  }),
2097
- typeText: (text, opts) => Effect.tryPromise({
2979
+ typeText: (text, opts) => Effect_exports.tryPromise({
2098
2980
  try: async () => {
2099
2981
  const delay = opts?.delay ?? 0;
2100
2982
  for (const ch of Array.from(text)) {
2101
- const desc = parseCdpKeyDescriptor(ch);
2102
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2103
- type: "keyDown",
2104
- key: desc.key,
2105
- ...desc.code ? { code: desc.code } : {},
2106
- ...desc.windowsVirtualKeyCode ? {
2107
- windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
2108
- nativeVirtualKeyCode: desc.windowsVirtualKeyCode
2109
- } : {},
2110
- modifiers: desc.modifiers,
2111
- text: ch,
2112
- unmodifiedText: ch
2113
- });
2114
- await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2115
- type: "keyUp",
2116
- key: desc.key,
2117
- ...desc.code ? { code: desc.code } : {},
2118
- ...desc.windowsVirtualKeyCode ? {
2119
- windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
2120
- nativeVirtualKeyCode: desc.windowsVirtualKeyCode
2121
- } : {},
2122
- modifiers: desc.modifiers
2123
- });
2983
+ const cp = ch.codePointAt(0) ?? 0;
2984
+ if (cp > 126) {
2985
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2986
+ type: "keyDown",
2987
+ key: ch,
2988
+ modifiers: 0
2989
+ });
2990
+ await cdpChannel.sendCommand("Input.insertText", { text: ch });
2991
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2992
+ type: "keyUp",
2993
+ key: ch,
2994
+ modifiers: 0
2995
+ });
2996
+ } else {
2997
+ const desc = parseCdpKeyDescriptor(ch);
2998
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2999
+ type: "keyDown",
3000
+ key: desc.key,
3001
+ ...desc.code ? { code: desc.code } : {},
3002
+ ...desc.windowsVirtualKeyCode ? {
3003
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
3004
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
3005
+ } : {},
3006
+ modifiers: desc.modifiers,
3007
+ text: ch,
3008
+ unmodifiedText: ch
3009
+ });
3010
+ await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
3011
+ type: "keyUp",
3012
+ key: desc.key,
3013
+ ...desc.code ? { code: desc.code } : {},
3014
+ ...desc.windowsVirtualKeyCode ? {
3015
+ windowsVirtualKeyCode: desc.windowsVirtualKeyCode,
3016
+ nativeVirtualKeyCode: desc.windowsVirtualKeyCode
3017
+ } : {},
3018
+ modifiers: desc.modifiers
3019
+ });
3020
+ }
2124
3021
  if (delay > 0) {
2125
3022
  await new Promise((r) => setTimeout(r, delay));
2126
3023
  }
@@ -2128,9 +3025,9 @@ function makeLightweightCdpDriver(options) {
2128
3025
  },
2129
3026
  catch: (e) => new DriverError({ message: `CDP typeText failed: ${e}` })
2130
3027
  }),
2131
- pressKey: (key) => Effect.tryPromise({
3028
+ pressKey: (key) => Effect_exports.tryPromise({
2132
3029
  try: async () => {
2133
- const desc = parseCdpKeyDescriptor(key);
3030
+ const desc = parseCdpKeyDescriptor(key, heldModifiers);
2134
3031
  await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2135
3032
  type: desc.text ? "keyDown" : "rawKeyDown",
2136
3033
  key: desc.key,
@@ -2156,9 +3053,11 @@ function makeLightweightCdpDriver(options) {
2156
3053
  },
2157
3054
  catch: (e) => new DriverError({ message: `CDP pressKey failed: ${e}` })
2158
3055
  }),
2159
- keyDown: (key) => Effect.tryPromise({
3056
+ keyDown: (key) => Effect_exports.tryPromise({
2160
3057
  try: async () => {
2161
- const desc = parseCdpKeyDescriptor(key);
3058
+ const modBit = modifierBitForName(key);
3059
+ if (modBit) heldModifiers |= modBit;
3060
+ const desc = parseCdpKeyDescriptor(key, heldModifiers);
2162
3061
  await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2163
3062
  type: desc.text ? "keyDown" : "rawKeyDown",
2164
3063
  key: desc.key,
@@ -2173,9 +3072,11 @@ function makeLightweightCdpDriver(options) {
2173
3072
  },
2174
3073
  catch: (e) => new DriverError({ message: `CDP keyDown failed: ${e}` })
2175
3074
  }),
2176
- keyUp: (key) => Effect.tryPromise({
3075
+ keyUp: (key) => Effect_exports.tryPromise({
2177
3076
  try: async () => {
2178
- const desc = parseCdpKeyDescriptor(key);
3077
+ const modBit = modifierBitForName(key);
3078
+ if (modBit) heldModifiers &= ~modBit;
3079
+ const desc = parseCdpKeyDescriptor(key, heldModifiers);
2179
3080
  await cdpChannel.sendCommand("Input.dispatchKeyEvent", {
2180
3081
  type: "keyUp",
2181
3082
  key: desc.key,
@@ -2189,54 +3090,80 @@ function makeLightweightCdpDriver(options) {
2189
3090
  },
2190
3091
  catch: (e) => new DriverError({ message: `CDP keyUp failed: ${e}` })
2191
3092
  }),
2192
- mouseDown: (x, y, opts) => Effect.tryPromise({
3093
+ mouseDown: (x, y, opts) => Effect_exports.tryPromise({
2193
3094
  try: async () => {
2194
- const button = opts?.button ?? "left";
2195
- await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2196
- type: "mouseMoved",
2197
- x,
2198
- y
2199
- });
3095
+ const resolvedOpts = typeof x === "object" && x !== null ? x : opts;
3096
+ const targetX = typeof x === "number" && Number.isFinite(x) ? x : lastMouseX;
3097
+ const targetY = typeof y === "number" && Number.isFinite(y) ? y : lastMouseY;
3098
+ const button = resolvedOpts?.button ?? "left";
3099
+ const mask = button === "left" ? 1 : button === "right" ? 2 : 4;
3100
+ pressedMouseButtons |= mask;
3101
+ lastMouseX = targetX;
3102
+ lastMouseY = targetY;
3103
+ if (typeof x === "number" && typeof y === "number") {
3104
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
3105
+ type: "mouseMoved",
3106
+ x: targetX,
3107
+ y: targetY,
3108
+ modifiers: heldModifiers,
3109
+ pointerType: "mouse"
3110
+ });
3111
+ }
2200
3112
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2201
3113
  type: "mousePressed",
2202
- x,
2203
- y,
3114
+ x: targetX,
3115
+ y: targetY,
2204
3116
  button,
2205
- buttons: button === "left" ? 1 : button === "right" ? 2 : 4,
2206
- clickCount: 1
3117
+ buttons: pressedMouseButtons,
3118
+ clickCount: 1,
3119
+ modifiers: heldModifiers,
3120
+ pointerType: "mouse"
2207
3121
  });
2208
3122
  },
2209
3123
  catch: (e) => new DriverError({ message: `CDP mouseDown failed: ${e}` })
2210
3124
  }),
2211
- mouseUp: (x, y, opts) => Effect.tryPromise({
3125
+ mouseUp: (x, y, opts) => Effect_exports.tryPromise({
2212
3126
  try: async () => {
2213
- const button = opts?.button ?? "left";
3127
+ const resolvedOpts = typeof x === "object" && x !== null ? x : opts;
3128
+ const targetX = typeof x === "number" && Number.isFinite(x) ? x : lastMouseX;
3129
+ const targetY = typeof y === "number" && Number.isFinite(y) ? y : lastMouseY;
3130
+ const button = resolvedOpts?.button ?? "left";
3131
+ const mask = button === "left" ? 1 : button === "right" ? 2 : 4;
3132
+ pressedMouseButtons &= ~mask;
3133
+ lastMouseX = targetX;
3134
+ lastMouseY = targetY;
2214
3135
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2215
3136
  type: "mouseReleased",
2216
- x,
2217
- y,
3137
+ x: targetX,
3138
+ y: targetY,
2218
3139
  button,
2219
- buttons: 0,
2220
- clickCount: 1
3140
+ buttons: pressedMouseButtons,
3141
+ clickCount: 1,
3142
+ modifiers: heldModifiers,
3143
+ pointerType: "mouse"
2221
3144
  });
2222
3145
  },
2223
3146
  catch: (e) => new DriverError({ message: `CDP mouseUp failed: ${e}` })
2224
3147
  }),
2225
- mouseWheel: (x, y, deltaX, deltaY) => Effect.tryPromise({
3148
+ mouseWheel: (x, y, deltaX, deltaY) => Effect_exports.tryPromise({
2226
3149
  try: async () => {
3150
+ lastMouseX = x;
3151
+ lastMouseY = y;
2227
3152
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2228
3153
  type: "mouseWheel",
2229
3154
  x,
2230
3155
  y,
2231
3156
  deltaX,
2232
- deltaY
3157
+ deltaY,
3158
+ modifiers: heldModifiers,
3159
+ pointerType: "mouse"
2233
3160
  });
2234
3161
  },
2235
3162
  catch: (e) => new DriverError({
2236
3163
  message: `CDP mouseWheel (${deltaX}, ${deltaY}) failed at (${x}, ${y}): ${e}`
2237
3164
  })
2238
3165
  }),
2239
- getWasmTraps: () => Effect.tryPromise({
3166
+ getWasmTraps: () => Effect_exports.tryPromise({
2240
3167
  try: async () => {
2241
3168
  const pageTraps = await cdpChannel.evaluate(
2242
3169
  `(() => (globalThis.__spanaWasm ? globalThis.__spanaWasm.getMetrics().traps : []))()`
@@ -2254,7 +3181,7 @@ function makeLightweightCdpDriver(options) {
2254
3181
  },
2255
3182
  catch: (e) => new DriverError({ message: `CDP getWasmTraps failed: ${e}` })
2256
3183
  }),
2257
- getWasmMetrics: () => Effect.tryPromise({
3184
+ getWasmMetrics: () => Effect_exports.tryPromise({
2258
3185
  try: async () => {
2259
3186
  const raw = await cdpChannel.evaluate(
2260
3187
  `(() => globalThis.__spanaWasm ? globalThis.__spanaWasm.getMetrics() : {
@@ -2292,33 +3219,66 @@ function makeLightweightCdpDriver(options) {
2292
3219
  },
2293
3220
  catch: (e) => new DriverError({ message: `CDP getWasmMetrics failed: ${e}` })
2294
3221
  }),
2295
- hoverAtCoordinate: (x, y) => Effect.tryPromise({
3222
+ hoverAtCoordinate: (x, y, opts) => Effect_exports.tryPromise({
2296
3223
  try: async () => {
2297
- await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
2298
- type: "mouseMoved",
2299
- x,
2300
- y
2301
- });
3224
+ const steps = Math.max(1, Math.round(opts?.steps ?? 1));
3225
+ const startX = lastMouseX;
3226
+ const startY = lastMouseY;
3227
+ const activeButton = pressedMouseButtons & 1 ? "left" : pressedMouseButtons & 2 ? "right" : pressedMouseButtons & 4 ? "middle" : "none";
3228
+ for (let i = 1; i <= steps; i++) {
3229
+ const t = i / steps;
3230
+ const cx = steps === 1 ? x : startX + (x - startX) * t;
3231
+ const cy = steps === 1 ? y : startY + (y - startY) * t;
3232
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
3233
+ type: "mouseMoved",
3234
+ x: cx,
3235
+ y: cy,
3236
+ ...activeButton !== "none" ? { button: activeButton } : {},
3237
+ ...pressedMouseButtons ? { buttons: pressedMouseButtons } : {},
3238
+ modifiers: heldModifiers,
3239
+ pointerType: "mouse"
3240
+ });
3241
+ if (steps > 1 && pressedMouseButtons) {
3242
+ await new Promise((r) => setTimeout(r, 8));
3243
+ }
3244
+ }
3245
+ lastMouseX = x;
3246
+ lastMouseY = y;
2302
3247
  },
2303
3248
  catch: (e) => new DriverError({ message: `CDP hover failed at (${x}, ${y}): ${e}` })
2304
3249
  }),
2305
- reload: (reloadOpts) => Effect.tryPromise({
3250
+ reload: (reloadOpts) => Effect_exports.tryPromise({
2306
3251
  try: async () => {
2307
3252
  const waitUntil = reloadOpts?.waitUntil ?? options.waitUntil ?? "domcontentloaded";
2308
3253
  const targetSid = activeSlot?.sessionId;
3254
+ if (waitUntil === "commit") {
3255
+ await cdpChannel.sendCommand("Page.reload", {}, void 0, navigationTimeoutMs);
3256
+ return;
3257
+ }
2309
3258
  const eventName = waitUntil === "domcontentloaded" ? "Page.domContentEventFired" : "Page.loadEventFired";
2310
- const waiter = cdpChannel.waitForEvent(
3259
+ const waiter = cdpChannel.waitForEventCancellable(
2311
3260
  eventName,
2312
- 15e3,
3261
+ navigationTimeoutMs,
2313
3262
  (_p, sid) => !targetSid || !sid || sid === targetSid
2314
3263
  );
2315
- await cdpChannel.sendCommand("Page.reload", {});
2316
- await waiter.catch(() => {
2317
- });
3264
+ waiter.promise.catch(handledByLaterAwait);
3265
+ try {
3266
+ await cdpChannel.sendCommand("Page.reload", {}, void 0, navigationTimeoutMs);
3267
+ try {
3268
+ await waiter.promise;
3269
+ } catch (waitErr) {
3270
+ throw new Error(
3271
+ `Page reload timed out waiting for ${waitUntil} after ${navigationTimeoutMs}ms: ${waitErr instanceof Error ? waitErr.message : String(waitErr)}`,
3272
+ { cause: waitErr }
3273
+ );
3274
+ }
3275
+ } finally {
3276
+ waiter.cancel();
3277
+ }
2318
3278
  },
2319
3279
  catch: (e) => new DriverError({ message: `CDP reload failed: ${e}` })
2320
3280
  }),
2321
- getUrl: () => Effect.tryPromise({
3281
+ getUrl: () => Effect_exports.tryPromise({
2322
3282
  try: async () => {
2323
3283
  const url = await cdpChannel.evaluate(
2324
3284
  "typeof window !== 'undefined' && window.location ? String(window.location.href || '') : ''"
@@ -2328,9 +3288,10 @@ function makeLightweightCdpDriver(options) {
2328
3288
  catch: (e) => new DriverError({ message: `CDP getUrl failed: ${e}` })
2329
3289
  }),
2330
3290
  getNavigationUrls: () => [...navigationUrls],
2331
- waitForLoadState: (state = "load", waitOpts) => Effect.tryPromise({
3291
+ getLastNavigationStatus: () => lastNavigationStatus,
3292
+ waitForLoadState: (state = "load", waitOpts) => Effect_exports.tryPromise({
2332
3293
  try: async () => {
2333
- const timeoutMs = waitOpts?.timeout ?? 15e3;
3294
+ const timeoutMs = waitOpts?.timeout ?? navigationTimeoutMs;
2334
3295
  const targetSid = activeSlot?.sessionId;
2335
3296
  if (state === "domcontentloaded") {
2336
3297
  const ready = await cdpChannel.evaluate("document.readyState").catch(() => "");
@@ -2394,51 +3355,99 @@ function makeLightweightCdpDriver(options) {
2394
3355
  },
2395
3356
  catch: (e) => new DriverError({ message: `CDP waitForLoadState failed: ${e}` })
2396
3357
  }),
2397
- waitForPopup: (triggerFn, waitOpts) => Effect.tryPromise({
3358
+ waitForPopup: (triggerFn, waitOpts) => Effect_exports.tryPromise({
2398
3359
  try: async () => {
2399
3360
  const timeoutMs = waitOpts?.timeout ?? 15e3;
3361
+ let timer;
3362
+ let entry;
3363
+ const cleanup = () => {
3364
+ if (timer !== void 0) {
3365
+ clearTimeout(timer);
3366
+ timer = void 0;
3367
+ }
3368
+ if (entry) {
3369
+ const idx = popupWaiters.indexOf(entry);
3370
+ if (idx >= 0) popupWaiters.splice(idx, 1);
3371
+ entry = void 0;
3372
+ }
3373
+ };
2400
3374
  const popupPromise = new Promise((resolve2, reject) => {
2401
- const timer = setTimeout(() => {
3375
+ timer = setTimeout(() => {
3376
+ cleanup();
2402
3377
  reject(new Error(`Timed out waiting for popup after ${timeoutMs}ms`));
2403
3378
  }, timeoutMs);
2404
- popupWaiters.push({
3379
+ entry = {
2405
3380
  resolve: (tabId) => {
2406
- clearTimeout(timer);
3381
+ cleanup();
2407
3382
  resolve2(tabId);
2408
3383
  },
2409
3384
  reject: (err) => {
2410
- clearTimeout(timer);
3385
+ cleanup();
2411
3386
  reject(err);
2412
3387
  }
2413
- });
3388
+ };
3389
+ popupWaiters.push(entry);
2414
3390
  });
2415
- await triggerFn();
2416
- return await popupPromise;
3391
+ popupPromise.catch(handledByLaterAwait);
3392
+ try {
3393
+ await triggerFn();
3394
+ return await popupPromise;
3395
+ } finally {
3396
+ cleanup();
3397
+ }
2417
3398
  },
2418
3399
  catch: (e) => new DriverError({ message: `CDP waitForPopup failed: ${e}` })
2419
3400
  }),
2420
- hideKeyboard: () => Effect.void,
2421
- takeScreenshot: () => Effect.tryPromise({
3401
+ hideKeyboard: () => Effect_exports.void,
3402
+ takeScreenshot: () => Effect_exports.tryPromise({
2422
3403
  try: async () => {
2423
- const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
2424
- format: "png"
2425
- });
2426
- return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
3404
+ let lastErr;
3405
+ for (let attempt = 0; attempt < 3; attempt++) {
3406
+ try {
3407
+ const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
3408
+ format: "png"
3409
+ });
3410
+ return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
3411
+ } catch (err) {
3412
+ lastErr = err;
3413
+ const msg = err instanceof Error ? err.message : String(err);
3414
+ if (attempt < 2 && (msg.includes("Not attached to an active page") || msg.includes("Unable to capture screenshot"))) {
3415
+ await new Promise((r) => setTimeout(r, 60));
3416
+ continue;
3417
+ }
3418
+ throw err;
3419
+ }
3420
+ }
3421
+ throw lastErr;
2427
3422
  },
2428
3423
  catch: (e) => new DriverError({ message: `CDP screenshot failed: ${e}` })
2429
3424
  }),
2430
- takeFullPageScreenshot: () => Effect.tryPromise({
3425
+ takeFullPageScreenshot: () => Effect_exports.tryPromise({
2431
3426
  try: async () => {
2432
- const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
2433
- format: "png",
2434
- captureBeyondViewport: true,
2435
- fromSurface: true
2436
- });
2437
- return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
3427
+ let lastErr;
3428
+ for (let attempt = 0; attempt < 3; attempt++) {
3429
+ try {
3430
+ const res = await cdpChannel.sendCommand("Page.captureScreenshot", {
3431
+ format: "png",
3432
+ captureBeyondViewport: true,
3433
+ fromSurface: true
3434
+ });
3435
+ return new Uint8Array(Buffer.from(res?.data ?? "", "base64"));
3436
+ } catch (err) {
3437
+ lastErr = err;
3438
+ const msg = err instanceof Error ? err.message : String(err);
3439
+ if (attempt < 2 && (msg.includes("Not attached to an active page") || msg.includes("Unable to capture screenshot"))) {
3440
+ await new Promise((r) => setTimeout(r, 60));
3441
+ continue;
3442
+ }
3443
+ throw err;
3444
+ }
3445
+ }
3446
+ throw lastErr;
2438
3447
  },
2439
3448
  catch: (e) => new DriverError({ message: `CDP fullPage screenshot failed: ${e}` })
2440
3449
  }),
2441
- setGeolocation: (point) => Effect.tryPromise({
3450
+ setGeolocation: (point) => Effect_exports.tryPromise({
2442
3451
  try: async () => {
2443
3452
  geolocationMutated = true;
2444
3453
  await cdpChannel.sendCommand("Emulation.setGeolocationOverride", {
@@ -2449,30 +3458,28 @@ function makeLightweightCdpDriver(options) {
2449
3458
  },
2450
3459
  catch: (e) => new DriverError({ message: `CDP setGeolocation failed: ${e}` })
2451
3460
  }),
2452
- setPermission: (_appId, permission, state, permOpts) => Effect.tryPromise({
3461
+ setPermission: (_appId, permission, state, permOpts) => Effect_exports.tryPromise({
2453
3462
  try: async () => {
2454
3463
  permissionsMutated = true;
2455
- const cdpName = permission === "clipboard-read" ? "clipboardReadWrite" : permission === "clipboard-write" ? "clipboardSanitizedWrite" : permission === "midi-sysex" ? "midi" : permission;
2456
3464
  const origin = permOpts?.origin;
2457
3465
  const ctxId = activeSlot?.browserContextId;
2458
3466
  if (state === "grant") {
3467
+ const grantName = mapPermissionToCdpGrantName(permission);
2459
3468
  await cdpChannel.sendCommand(
2460
3469
  "Browser.grantPermissions",
2461
3470
  {
2462
- permissions: [cdpName],
3471
+ permissions: [grantName],
2463
3472
  ...origin ? { origin } : {},
2464
3473
  ...ctxId ? { browserContextId: ctxId } : {}
2465
3474
  },
2466
3475
  null
2467
3476
  );
2468
3477
  } else {
3478
+ const descriptor = mapPermissionToCdpDescriptor(permission);
2469
3479
  await cdpChannel.sendCommand(
2470
3480
  "Browser.setPermission",
2471
3481
  {
2472
- permission: {
2473
- name: cdpName,
2474
- ...permission === "midi-sysex" ? { sysex: true } : {}
2475
- },
3482
+ permission: descriptor,
2476
3483
  setting: "denied",
2477
3484
  ...origin ? { origin } : {},
2478
3485
  ...ctxId ? { browserContextId: ctxId } : {}
@@ -2483,7 +3490,7 @@ function makeLightweightCdpDriver(options) {
2483
3490
  },
2484
3491
  catch: (e) => new DriverError({ message: `CDP setPermission failed: ${e}` })
2485
3492
  }),
2486
- getDeviceInfo: () => Effect.succeed({
3493
+ getDeviceInfo: () => Effect_exports.succeed({
2487
3494
  platform: "web",
2488
3495
  deviceId: `${label}:${options.cdpUrl}`,
2489
3496
  name: `${label} (CDP-direct)`,
@@ -2492,7 +3499,7 @@ function makeLightweightCdpDriver(options) {
2492
3499
  screenHeight: height,
2493
3500
  driverType: "cdp"
2494
3501
  }),
2495
- launchApp: (url, opts) => Effect.tryPromise({
3502
+ launchApp: (url, opts) => Effect_exports.tryPromise({
2496
3503
  try: async () => {
2497
3504
  if (opts?.clearState) {
2498
3505
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
@@ -2505,11 +3512,11 @@ function makeLightweightCdpDriver(options) {
2505
3512
  },
2506
3513
  catch: (e) => new DriverError({ message: `CDP launchApp failed: ${e}` })
2507
3514
  }),
2508
- stopApp: () => Effect.tryPromise({
3515
+ stopApp: () => Effect_exports.tryPromise({
2509
3516
  try: () => navigate("about:blank"),
2510
3517
  catch: (e) => new DriverError({ message: `CDP stopApp failed: ${e}` })
2511
3518
  }),
2512
- killApp: () => Effect.tryPromise({
3519
+ killApp: () => Effect_exports.tryPromise({
2513
3520
  try: async () => {
2514
3521
  prefetchedSlotPromise = void 0;
2515
3522
  const slotToDispose = activeSlot;
@@ -2532,6 +3539,7 @@ function makeLightweightCdpDriver(options) {
2532
3539
  }
2533
3540
  downloadDir = void 0;
2534
3541
  }
3542
+ downloadConfiguredContexts.clear();
2535
3543
  for (const dir of uploadTempDirs.splice(0)) {
2536
3544
  try {
2537
3545
  rmSync(dir, { recursive: true, force: true });
@@ -2545,7 +3553,7 @@ function makeLightweightCdpDriver(options) {
2545
3553
  },
2546
3554
  catch: (e) => new DriverError({ message: `CDP disconnect failed: ${e}` })
2547
3555
  }),
2548
- clearAppState: () => Effect.tryPromise({
3556
+ clearAppState: () => Effect_exports.tryPromise({
2549
3557
  try: async () => {
2550
3558
  await cdpChannel.sendCommand("Network.clearBrowserCookies").catch(() => {
2551
3559
  });
@@ -2555,11 +3563,11 @@ function makeLightweightCdpDriver(options) {
2555
3563
  },
2556
3564
  catch: (e) => new DriverError({ message: `CDP clearAppState failed: ${e}` })
2557
3565
  }),
2558
- openLink: (url) => Effect.tryPromise({
3566
+ openLink: (url) => Effect_exports.tryPromise({
2559
3567
  try: () => navigate(url),
2560
3568
  catch: (e) => new DriverError({ message: `CDP openLink failed: ${e}` })
2561
3569
  }),
2562
- back: () => Effect.tryPromise({
3570
+ back: () => Effect_exports.tryPromise({
2563
3571
  try: async () => {
2564
3572
  const targetSid = activeSlot?.sessionId;
2565
3573
  const history = await cdpChannel.sendCommand("Page.getNavigationHistory", {}).catch(() => null);
@@ -2567,23 +3575,46 @@ function makeLightweightCdpDriver(options) {
2567
3575
  const targetEntry = history.entries[history.currentIndex - 1];
2568
3576
  if (!targetEntry) return;
2569
3577
  const eventName = (options.waitUntil ?? "domcontentloaded") === "load" ? "Page.loadEventFired" : "Page.domContentEventFired";
2570
- const waiter = Promise.race([
2571
- cdpChannel.waitForEvent(
2572
- eventName,
2573
- 1e4,
2574
- (_p, sid) => !targetSid || !sid || sid === targetSid
2575
- ),
2576
- cdpChannel.waitForEvent(
2577
- "Page.navigatedWithinDocument",
2578
- 1e4,
2579
- (_p, sid) => !targetSid || !sid || sid === targetSid
2580
- )
2581
- ]);
2582
- await cdpChannel.sendCommand("Page.navigateToHistoryEntry", {
2583
- entryId: targetEntry.id
2584
- });
2585
- await waiter.catch(() => {
2586
- });
3578
+ const w1 = cdpChannel.waitForEventCancellable(
3579
+ eventName,
3580
+ navigationTimeoutMs,
3581
+ (_p, sid) => !targetSid || !sid || sid === targetSid
3582
+ );
3583
+ const w2 = cdpChannel.waitForEventCancellable(
3584
+ "Page.navigatedWithinDocument",
3585
+ navigationTimeoutMs,
3586
+ (_p, sid) => !targetSid || !sid || sid === targetSid
3587
+ );
3588
+ const w3 = cdpChannel.waitForEventCancellable(
3589
+ "Page.frameNavigated",
3590
+ navigationTimeoutMs,
3591
+ (p, sid) => (!targetSid || !sid || sid === targetSid) && !p?.frame?.parentId && p?.type === "BackForwardCacheRestore"
3592
+ );
3593
+ w1.promise.catch(handledByLaterAwait);
3594
+ w2.promise.catch(handledByLaterAwait);
3595
+ w3.promise.catch(handledByLaterAwait);
3596
+ const waiter = Promise.race([w1.promise, w2.promise, w3.promise]);
3597
+ waiter.catch(handledByLaterAwait);
3598
+ try {
3599
+ await cdpChannel.sendCommand(
3600
+ "Page.navigateToHistoryEntry",
3601
+ { entryId: targetEntry.id },
3602
+ void 0,
3603
+ navigationTimeoutMs
3604
+ );
3605
+ try {
3606
+ await waiter;
3607
+ } catch (waitErr) {
3608
+ throw new Error(
3609
+ `History back navigation timed out after ${navigationTimeoutMs}ms: ${waitErr instanceof Error ? waitErr.message : String(waitErr)}`,
3610
+ { cause: waitErr }
3611
+ );
3612
+ }
3613
+ } finally {
3614
+ w1.cancel();
3615
+ w2.cancel();
3616
+ w3.cancel();
3617
+ }
2587
3618
  await cdpChannel.evaluateFast(
2588
3619
  `new Promise((resolve) => {
2589
3620
  let done = false;
@@ -2601,7 +3632,7 @@ function makeLightweightCdpDriver(options) {
2601
3632
  },
2602
3633
  catch: (e) => new DriverError({ message: `CDP back failed: ${e}` })
2603
3634
  }),
2604
- forward: () => Effect.tryPromise({
3635
+ forward: () => Effect_exports.tryPromise({
2605
3636
  try: async () => {
2606
3637
  const targetSid = activeSlot?.sessionId;
2607
3638
  const history = await cdpChannel.sendCommand("Page.getNavigationHistory", {}).catch(() => null);
@@ -2609,23 +3640,46 @@ function makeLightweightCdpDriver(options) {
2609
3640
  const targetEntry = history.entries[history.currentIndex + 1];
2610
3641
  if (!targetEntry) return;
2611
3642
  const eventName = (options.waitUntil ?? "domcontentloaded") === "load" ? "Page.loadEventFired" : "Page.domContentEventFired";
2612
- const waiter = Promise.race([
2613
- cdpChannel.waitForEvent(
2614
- eventName,
2615
- 1e4,
2616
- (_p, sid) => !targetSid || !sid || sid === targetSid
2617
- ),
2618
- cdpChannel.waitForEvent(
2619
- "Page.navigatedWithinDocument",
2620
- 1e4,
2621
- (_p, sid) => !targetSid || !sid || sid === targetSid
2622
- )
2623
- ]);
2624
- await cdpChannel.sendCommand("Page.navigateToHistoryEntry", {
2625
- entryId: targetEntry.id
2626
- });
2627
- await waiter.catch(() => {
2628
- });
3643
+ const w1 = cdpChannel.waitForEventCancellable(
3644
+ eventName,
3645
+ navigationTimeoutMs,
3646
+ (_p, sid) => !targetSid || !sid || sid === targetSid
3647
+ );
3648
+ const w2 = cdpChannel.waitForEventCancellable(
3649
+ "Page.navigatedWithinDocument",
3650
+ navigationTimeoutMs,
3651
+ (_p, sid) => !targetSid || !sid || sid === targetSid
3652
+ );
3653
+ const w3 = cdpChannel.waitForEventCancellable(
3654
+ "Page.frameNavigated",
3655
+ navigationTimeoutMs,
3656
+ (p, sid) => (!targetSid || !sid || sid === targetSid) && !p?.frame?.parentId && p?.type === "BackForwardCacheRestore"
3657
+ );
3658
+ w1.promise.catch(handledByLaterAwait);
3659
+ w2.promise.catch(handledByLaterAwait);
3660
+ w3.promise.catch(handledByLaterAwait);
3661
+ const waiter = Promise.race([w1.promise, w2.promise, w3.promise]);
3662
+ waiter.catch(handledByLaterAwait);
3663
+ try {
3664
+ await cdpChannel.sendCommand(
3665
+ "Page.navigateToHistoryEntry",
3666
+ { entryId: targetEntry.id },
3667
+ void 0,
3668
+ navigationTimeoutMs
3669
+ );
3670
+ try {
3671
+ await waiter;
3672
+ } catch (waitErr) {
3673
+ throw new Error(
3674
+ `History forward navigation timed out after ${navigationTimeoutMs}ms: ${waitErr instanceof Error ? waitErr.message : String(waitErr)}`,
3675
+ { cause: waitErr }
3676
+ );
3677
+ }
3678
+ } finally {
3679
+ w1.cancel();
3680
+ w2.cancel();
3681
+ w3.cancel();
3682
+ }
2629
3683
  await cdpChannel.evaluateFast(
2630
3684
  `new Promise((resolve) => {
2631
3685
  let done = false;
@@ -2643,21 +3697,29 @@ function makeLightweightCdpDriver(options) {
2643
3697
  },
2644
3698
  catch: (e) => new DriverError({ message: `CDP forward failed: ${e}` })
2645
3699
  }),
2646
- evaluate: (fn, ...args) => Effect.tryPromise({
3700
+ evaluate: (fn, ...args) => Effect_exports.tryPromise({
2647
3701
  try: async () => {
2648
- if (typeof fn === "string") {
2649
- return await cdpChannel.evaluateOnce(fn);
3702
+ const expr = typeof fn === "string" ? fn : `(${fn.toString()})(${args.map((a) => serializeEvaluateArg(a)).join(", ")})`;
3703
+ try {
3704
+ return await cdpChannel.evaluateOnce(expr);
3705
+ } catch (firstErr) {
3706
+ const msg = firstErr instanceof Error ? firstErr.message : String(firstErr);
3707
+ if (/Cannot find context with specified id/i.test(msg)) {
3708
+ await new Promise((r) => setTimeout(r, 60));
3709
+ return await cdpChannel.evaluateOnce(expr);
3710
+ }
3711
+ throw firstErr;
2650
3712
  }
2651
- const serializedArgs = args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ");
2652
- return await cdpChannel.evaluateOnce(`(${fn.toString()})(${serializedArgs})`);
2653
3713
  },
2654
3714
  catch: (e) => new DriverError({ message: `CDP evaluate failed: ${e}` })
2655
3715
  }),
2656
- addInitScript: (script, ...args) => Effect.tryPromise({
3716
+ addInitScript: (script, ...args) => Effect_exports.tryPromise({
2657
3717
  try: async () => {
2658
- const source = typeof script === "string" ? script : `(${script.toString()})(${args.map((a) => a === void 0 ? "undefined" : JSON.stringify(a)).join(", ")});`;
3718
+ const source = typeof script === "string" ? script : `(${script.toString()})(${args.map((a) => serializeEvaluateArg(a)).join(", ")});`;
2659
3719
  flowInitScripts.push(source);
2660
- const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
3720
+ const sessions = activeSlot ? Array.from(
3721
+ /* @__PURE__ */ new Set([activeSlot.sessionId, ...activeSlot.tabs.map((t) => t.sessionId)])
3722
+ ) : [null];
2661
3723
  await Promise.all(
2662
3724
  sessions.map(
2663
3725
  (sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source }, sid).then((res) => recordScriptId(flowInitScriptIds, sid, res)).catch(() => {
@@ -2667,12 +3729,14 @@ function makeLightweightCdpDriver(options) {
2667
3729
  },
2668
3730
  catch: (e) => new DriverError({ message: `CDP addInitScript failed: ${e}` })
2669
3731
  }),
2670
- setClockInitScript: (script) => Effect.tryPromise({
3732
+ setClockInitScript: (script) => Effect_exports.tryPromise({
2671
3733
  try: async () => {
2672
3734
  await removeTrackedScripts(clockInitScriptIds);
2673
3735
  clockInitScript = script;
2674
3736
  if (!script) return;
2675
- const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
3737
+ const sessions = activeSlot ? Array.from(
3738
+ /* @__PURE__ */ new Set([activeSlot.sessionId, ...activeSlot.tabs.map((t) => t.sessionId)])
3739
+ ) : [null];
2676
3740
  await Promise.all(
2677
3741
  sessions.map(
2678
3742
  (sid) => cdpChannel.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: script }, sid).then((res) => recordScriptId(clockInitScriptIds, sid, res)).catch(() => {
@@ -2682,7 +3746,7 @@ function makeLightweightCdpDriver(options) {
2682
3746
  },
2683
3747
  catch: (e) => new DriverError({ message: `CDP setClockInitScript failed: ${e}` })
2684
3748
  }),
2685
- exposeFunction: (name, fn) => Effect.tryPromise({
3749
+ exposeFunction: (name, fn) => Effect_exports.tryPromise({
2686
3750
  try: async () => {
2687
3751
  flowExposedFunctions.set(name, fn);
2688
3752
  const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
@@ -2709,39 +3773,50 @@ function makeLightweightCdpDriver(options) {
2709
3773
  return activeSlot?.browserContextId;
2710
3774
  }
2711
3775
  }),
2712
- route: (matcher, handler) => Effect.tryPromise({
3776
+ route: (matcher, handler) => Effect_exports.tryPromise({
2713
3777
  try: async () => {
2714
3778
  routeRules.push({ kind: "handler", matcher, handler });
2715
3779
  await ensureFetchIntercept();
2716
3780
  },
2717
3781
  catch: (e) => new DriverError({ message: `CDP route failed: ${e}` })
2718
3782
  }),
2719
- mockNetwork: (matcher, response) => Effect.tryPromise({
3783
+ unroute: (matcher, handler) => Effect_exports.tryPromise({
3784
+ try: async () => {
3785
+ const matchersEqual = (a, b) => a instanceof RegExp && b instanceof RegExp ? a.source === b.source && a.flags === b.flags : a === b;
3786
+ for (let i = routeRules.length - 1; i >= 0; i--) {
3787
+ const r = routeRules[i];
3788
+ if (matchersEqual(r.matcher, matcher) && (!handler || r.handler === handler)) {
3789
+ routeRules.splice(i, 1);
3790
+ }
3791
+ }
3792
+ if (routeRules.length === 0) {
3793
+ await disableAllFetchInterception();
3794
+ }
3795
+ },
3796
+ catch: (e) => new DriverError({ message: `CDP unroute failed: ${e}` })
3797
+ }),
3798
+ mockNetwork: (matcher, response) => Effect_exports.tryPromise({
2720
3799
  try: async () => {
2721
3800
  routeRules.push({ kind: "mock", matcher, response });
2722
3801
  await ensureFetchIntercept();
2723
3802
  },
2724
3803
  catch: (e) => new DriverError({ message: `CDP mockNetwork failed: ${e}` })
2725
3804
  }),
2726
- blockNetwork: (matcher) => Effect.tryPromise({
3805
+ blockNetwork: (matcher) => Effect_exports.tryPromise({
2727
3806
  try: async () => {
2728
3807
  routeRules.push({ kind: "block", matcher });
2729
3808
  await ensureFetchIntercept();
2730
3809
  },
2731
3810
  catch: (e) => new DriverError({ message: `CDP blockNetwork failed: ${e}` })
2732
3811
  }),
2733
- clearNetworkMocks: () => Effect.tryPromise({
3812
+ clearNetworkMocks: () => Effect_exports.tryPromise({
2734
3813
  try: async () => {
2735
3814
  routeRules.length = 0;
2736
- if (fetchInterceptEnabled) {
2737
- fetchInterceptEnabled = false;
2738
- await cdpChannel.sendCommand("Fetch.disable").catch(() => {
2739
- });
2740
- }
3815
+ await disableAllFetchInterception();
2741
3816
  },
2742
3817
  catch: (e) => new DriverError({ message: `CDP clearNetworkMocks failed: ${e}` })
2743
3818
  }),
2744
- saveCookies: (path) => Effect.tryPromise({
3819
+ saveCookies: (path) => Effect_exports.tryPromise({
2745
3820
  try: async () => {
2746
3821
  const cookies = await (async () => {
2747
3822
  if (activeSlot?.browserContextId) {
@@ -2759,7 +3834,7 @@ function makeLightweightCdpDriver(options) {
2759
3834
  },
2760
3835
  catch: (e) => new DriverError({ message: `CDP saveCookies failed: ${e}` })
2761
3836
  }),
2762
- loadCookies: (path) => Effect.tryPromise({
3837
+ loadCookies: (path) => Effect_exports.tryPromise({
2763
3838
  try: async () => {
2764
3839
  const cookies = JSON.parse(await readFile(path, "utf8"));
2765
3840
  if (Array.isArray(cookies)) {
@@ -2768,7 +3843,7 @@ function makeLightweightCdpDriver(options) {
2768
3843
  },
2769
3844
  catch: (e) => new DriverError({ message: `CDP loadCookies failed: ${e}` })
2770
3845
  }),
2771
- getCookies: (urls) => Effect.tryPromise({
3846
+ getCookies: (urls) => Effect_exports.tryPromise({
2772
3847
  try: async () => {
2773
3848
  if (urls && urls.length > 0) {
2774
3849
  const res2 = await cdpChannel.sendCommand("Network.getCookies", { urls });
@@ -2789,20 +3864,20 @@ function makeLightweightCdpDriver(options) {
2789
3864
  },
2790
3865
  catch: (e) => new DriverError({ message: `CDP getCookies failed: ${e}` })
2791
3866
  }),
2792
- setCookies: (cookies) => Effect.tryPromise({
3867
+ setCookies: (cookies) => Effect_exports.tryPromise({
2793
3868
  try: async () => {
2794
3869
  if (cookies.length === 0) return;
2795
3870
  await cdpChannel.sendCommand("Network.setCookies", { cookies });
2796
3871
  },
2797
3872
  catch: (e) => new DriverError({ message: `CDP setCookies failed: ${e}` })
2798
3873
  }),
2799
- clearCookies: () => Effect.tryPromise({
3874
+ clearCookies: () => Effect_exports.tryPromise({
2800
3875
  try: async () => {
2801
3876
  await cdpChannel.sendCommand("Network.clearBrowserCookies");
2802
3877
  },
2803
3878
  catch: (e) => new DriverError({ message: `CDP clearCookies failed: ${e}` })
2804
3879
  }),
2805
- waitForResponse: (matcher, waitOpts) => Effect.tryPromise({
3880
+ waitForResponse: (matcher, waitOpts) => Effect_exports.tryPromise({
2806
3881
  try: async () => {
2807
3882
  const timeoutMs = waitOpts?.timeout ?? 15e3;
2808
3883
  const slotSessions = () => {
@@ -2860,15 +3935,28 @@ function makeLightweightCdpDriver(options) {
2860
3935
  headers,
2861
3936
  method: explicitMethod ?? requestMethods.get(`${sid ?? ""}:${requestId}`),
2862
3937
  body: async () => {
2863
- const bodyRes = await cdpChannel.sendCommand(
2864
- "Network.getResponseBody",
2865
- { requestId },
2866
- responseSid
2867
- );
2868
- if (bodyRes?.base64Encoded && bodyRes.body) {
2869
- return Buffer.from(bodyRes.body, "base64").toString("utf8");
3938
+ let lastErr;
3939
+ for (let attempt = 0; attempt < 60; attempt++) {
3940
+ try {
3941
+ const bodyRes = await cdpChannel.sendCommand(
3942
+ "Network.getResponseBody",
3943
+ { requestId },
3944
+ responseSid
3945
+ );
3946
+ if (bodyRes?.base64Encoded && bodyRes.body) {
3947
+ return Buffer.from(bodyRes.body, "base64").toString("utf8");
3948
+ }
3949
+ return bodyRes?.body ?? "";
3950
+ } catch (err) {
3951
+ lastErr = err;
3952
+ const msg = err instanceof Error ? err.message : String(err);
3953
+ if (!/No resource with given identifier|No data found/i.test(msg) || attempt >= 59) {
3954
+ throw err;
3955
+ }
3956
+ await new Promise((r) => setTimeout(r, 25));
3957
+ }
2870
3958
  }
2871
- return bodyRes?.body ?? "";
3959
+ throw lastErr;
2872
3960
  },
2873
3961
  json: async () => {
2874
3962
  const text = await info.body();
@@ -2907,14 +3995,13 @@ function makeLightweightCdpDriver(options) {
2907
3995
  requestListeners.add(listener);
2908
3996
  const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
2909
3997
  for (const sid of sessions) {
2910
- void cdpChannel.sendCommand("Network.enable", {}, sid).catch(() => {
2911
- });
3998
+ void cdpChannel.sendCommand("Network.enable", {}, sid).catch(ignoreBestEffortFailure);
2912
3999
  }
2913
4000
  return () => {
2914
4001
  requestListeners.delete(listener);
2915
4002
  };
2916
4003
  },
2917
- waitForRequest: (matcher, waitOpts) => Effect.tryPromise({
4004
+ waitForRequest: (matcher, waitOpts) => Effect_exports.tryPromise({
2918
4005
  try: async () => {
2919
4006
  const timeoutMs = waitOpts?.timeout ?? 15e3;
2920
4007
  const sessions = activeSlot ? activeSlot.tabs.map((t) => t.sessionId) : [null];
@@ -2948,9 +4035,14 @@ function makeLightweightCdpDriver(options) {
2948
4035
  },
2949
4036
  catch: (e) => new DriverError({ message: `CDP waitForRequest failed: ${e}` })
2950
4037
  }),
2951
- createIsolatedContext: (ctxOpts) => Effect.tryPromise({
4038
+ createIsolatedContext: (ctxOpts) => Effect_exports.tryPromise({
2952
4039
  try: async () => {
2953
- const childDriver = await Effect.runPromise(
4040
+ const childEmulation = ctxOpts?.locale || ctxOpts?.userAgent ? {
4041
+ ...options.emulation,
4042
+ ...ctxOpts.locale ? { locale: ctxOpts.locale } : {},
4043
+ ...ctxOpts.userAgent ? { userAgent: ctxOpts.userAgent } : {}
4044
+ } : options.emulation;
4045
+ const childDriver = await Effect_exports.runPromise(
2954
4046
  makeLightweightCdpDriver({
2955
4047
  ...options,
2956
4048
  cdpUrl: connectWsUrl ?? options.cdpUrl,
@@ -2958,23 +4050,28 @@ function makeLightweightCdpDriver(options) {
2958
4050
  freshContextPerFlow: false,
2959
4051
  _markClosedOnKill: true,
2960
4052
  ...ctxOpts?.viewport ? { viewport: ctxOpts.viewport } : {},
2961
- ...ctxOpts?.locale ? { emulation: { ...options.emulation, locale: ctxOpts.locale } } : {}
4053
+ ...ctxOpts?.deviceScaleFactor !== void 0 ? { deviceScaleFactor: ctxOpts.deviceScaleFactor } : {},
4054
+ ...ctxOpts?.mobile !== void 0 ? { mobile: ctxOpts.mobile } : {},
4055
+ ...ctxOpts?.isMobile !== void 0 ? { isMobile: ctxOpts.isMobile } : {},
4056
+ ...ctxOpts?.hasTouch !== void 0 ? { hasTouch: ctxOpts.hasTouch } : {},
4057
+ ...ctxOpts?.httpCredentials ? { httpCredentials: ctxOpts.httpCredentials } : {},
4058
+ ...childEmulation ? { emulation: childEmulation } : {}
2962
4059
  })
2963
4060
  );
2964
4061
  if (ctxOpts?.url) {
2965
- await Effect.runPromise(childDriver.openLink(ctxOpts.url));
4062
+ await Effect_exports.runPromise(childDriver.openLink(ctxOpts.url));
2966
4063
  }
2967
4064
  return {
2968
4065
  driver: childDriver,
2969
4066
  close: async () => {
2970
- await Effect.runPromise(childDriver.killApp("isolated-context")).catch(() => {
4067
+ await Effect_exports.runPromise(childDriver.killApp("isolated-context")).catch(() => {
2971
4068
  });
2972
4069
  }
2973
4070
  };
2974
4071
  },
2975
4072
  catch: (e) => new DriverError({ message: `CDP createIsolatedContext failed: ${e}` })
2976
4073
  }),
2977
- saveAuthState: (path) => Effect.tryPromise({
4074
+ saveAuthState: (path) => Effect_exports.tryPromise({
2978
4075
  try: async () => {
2979
4076
  const cookies = await (async () => {
2980
4077
  if (activeSlot?.browserContextId) {
@@ -3008,11 +4105,12 @@ function makeLightweightCdpDriver(options) {
3008
4105
  },
3009
4106
  catch: (e) => new DriverError({ message: `CDP saveAuthState failed: ${e}` })
3010
4107
  }),
3011
- loadAuthState: (path) => Effect.tryPromise({
4108
+ loadAuthState: (path) => Effect_exports.tryPromise({
3012
4109
  try: async () => {
3013
4110
  if (useContexts) {
3014
4111
  const previousSlot = activeSlot;
3015
4112
  activeSlot = await createContextSlot(path);
4113
+ slotHasCustomStorageState = true;
3016
4114
  cdpChannel.setSessionId(activeSlot.sessionId);
3017
4115
  activeAuthenticatorId = activeSlot.authenticatorId;
3018
4116
  if (previousSlot) disposeSlotInBackground(previousSlot);
@@ -3025,7 +4123,7 @@ function makeLightweightCdpDriver(options) {
3025
4123
  },
3026
4124
  catch: (e) => new DriverError({ message: `CDP loadAuthState failed: ${e}` })
3027
4125
  }),
3028
- enableVirtualAuthenticator: (opts) => Effect.tryPromise({
4126
+ enableVirtualAuthenticator: (opts) => Effect_exports.tryPromise({
3029
4127
  try: async () => {
3030
4128
  activeAuthenticatorId = await attachVirtualAuthenticatorForSession(
3031
4129
  activeSlot?.sessionId ?? null,
@@ -3036,7 +4134,7 @@ function makeLightweightCdpDriver(options) {
3036
4134
  },
3037
4135
  catch: (e) => new DriverError({ message: `CDP enableVirtualAuthenticator failed: ${e}` })
3038
4136
  }),
3039
- removeVirtualAuthenticator: (authenticatorId) => Effect.tryPromise({
4137
+ removeVirtualAuthenticator: (authenticatorId) => Effect_exports.tryPromise({
3040
4138
  try: async () => {
3041
4139
  const id = authenticatorId ?? activeAuthenticatorId;
3042
4140
  if (!id) return;
@@ -3050,7 +4148,7 @@ function makeLightweightCdpDriver(options) {
3050
4148
  },
3051
4149
  catch: (e) => new DriverError({ message: `CDP removeVirtualAuthenticator failed: ${e}` })
3052
4150
  }),
3053
- getVirtualCredentials: (authenticatorId) => Effect.tryPromise({
4151
+ getVirtualCredentials: (authenticatorId) => Effect_exports.tryPromise({
3054
4152
  try: async () => {
3055
4153
  const id = authenticatorId ?? activeAuthenticatorId;
3056
4154
  if (!id) return [];
@@ -3061,7 +4159,7 @@ function makeLightweightCdpDriver(options) {
3061
4159
  },
3062
4160
  catch: (e) => new DriverError({ message: `CDP getVirtualCredentials failed: ${e}` })
3063
4161
  }),
3064
- addVirtualCredential: (credential, authenticatorId) => Effect.tryPromise({
4162
+ addVirtualCredential: (credential, authenticatorId) => Effect_exports.tryPromise({
3065
4163
  try: async () => {
3066
4164
  let id = authenticatorId ?? activeAuthenticatorId;
3067
4165
  if (!id) {
@@ -3083,7 +4181,7 @@ function makeLightweightCdpDriver(options) {
3083
4181
  },
3084
4182
  catch: (e) => new DriverError({ message: `CDP addVirtualCredential failed: ${e}` })
3085
4183
  }),
3086
- clearVirtualCredentials: (authenticatorId) => Effect.tryPromise({
4184
+ clearVirtualCredentials: (authenticatorId) => Effect_exports.tryPromise({
3087
4185
  try: async () => {
3088
4186
  const id = authenticatorId ?? activeAuthenticatorId;
3089
4187
  if (!id) return;
@@ -3091,10 +4189,11 @@ function makeLightweightCdpDriver(options) {
3091
4189
  },
3092
4190
  catch: (e) => new DriverError({ message: `CDP clearVirtualCredentials failed: ${e}` })
3093
4191
  }),
3094
- getConsoleLogs: () => Effect.succeed([...consoleLogs]),
3095
- getJSErrors: () => Effect.succeed([...jsErrors]),
3096
- setNetworkConditions: (conditions) => Effect.tryPromise({
4192
+ getConsoleLogs: () => Effect_exports.succeed([...consoleLogs]),
4193
+ getJSErrors: () => Effect_exports.succeed([...jsErrors]),
4194
+ setNetworkConditions: (conditions) => Effect_exports.tryPromise({
3097
4195
  try: async () => {
4196
+ hasNetworkConditionsDirty = true;
3098
4197
  currentNetworkConditions = { ...conditions };
3099
4198
  const sessions = activeSlot ? Array.from(
3100
4199
  /* @__PURE__ */ new Set([activeSlot.sessionId, ...activeSlot.tabs.map((t) => t.sessionId)])
@@ -3105,7 +4204,7 @@ function makeLightweightCdpDriver(options) {
3105
4204
  },
3106
4205
  catch: (e) => new DriverError({ message: `CDP setNetworkConditions failed: ${e}` })
3107
4206
  }),
3108
- uploadFile: (selector, filePath) => Effect.tryPromise({
4207
+ uploadFile: (selector, filePath) => Effect_exports.tryPromise({
3109
4208
  try: async () => {
3110
4209
  const rawItems = Array.isArray(filePath) ? filePath : [filePath];
3111
4210
  const hasInMemoryPayload = rawItems.some((item) => typeof item !== "string");
@@ -3186,21 +4285,9 @@ function makeLightweightCdpDriver(options) {
3186
4285
  },
3187
4286
  catch: (e) => new DriverError({ message: `CDP uploadFile failed: ${e}` })
3188
4287
  }),
3189
- downloadFile: (destPath) => Effect.tryPromise({
4288
+ downloadFile: (destPath) => Effect_exports.tryPromise({
3190
4289
  try: async () => {
3191
- if (!downloadDir) {
3192
- downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
3193
- await cdpChannel.sendCommand(
3194
- "Browser.setDownloadBehavior",
3195
- {
3196
- behavior: "allowAndName",
3197
- downloadPath: downloadDir,
3198
- eventsEnabled: true,
3199
- ...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
3200
- },
3201
- null
3202
- );
3203
- }
4290
+ await ensureDownloadBehaviorForActiveContext();
3204
4291
  const downloaded = completedDownloads.shift() ?? await new Promise((resolve2, reject) => {
3205
4292
  const timer = setTimeout(() => {
3206
4293
  reject(new Error("Timed out waiting for CDP file download"));
@@ -3220,38 +4307,68 @@ function makeLightweightCdpDriver(options) {
3220
4307
  },
3221
4308
  catch: (e) => new DriverError({ message: `CDP downloadFile failed: ${e}` })
3222
4309
  }),
3223
- dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect.tryPromise({
4310
+ dragAndDrop: (fromX, fromY, toX, toY, steps = 10) => Effect_exports.tryPromise({
3224
4311
  try: async () => {
3225
- const didHtml5Drag = await cdpChannel.evaluate(
3226
- `(async (fx, fy, tx, ty) => {
4312
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
4313
+ type: "mouseMoved",
4314
+ x: fromX,
4315
+ y: fromY,
4316
+ modifiers: heldModifiers,
4317
+ pointerType: "mouse"
4318
+ });
4319
+ const hasDraggableSource = await cdpChannel.evaluate(
4320
+ `((fx, fy) => {
4321
+ const hit = document.elementFromPoint(fx, fy);
4322
+ return Boolean(hit && hit.closest && hit.closest('[draggable="true"]'));
4323
+ })(${fromX}, ${fromY})`
4324
+ ).catch(() => false);
4325
+ if (hasDraggableSource) {
4326
+ await cdpChannel.evaluate(
4327
+ `((fx, fy) => {
3227
4328
  const hit = document.elementFromPoint(fx, fy);
3228
4329
  const src = hit && hit.closest ? hit.closest('[draggable="true"]') : null;
3229
4330
  if (!src) return false;
3230
- const dst = document.elementFromPoint(tx, ty) || document.body;
3231
4331
  const dt = new DataTransfer();
4332
+ window.__spanaDragState = { src, dt };
3232
4333
  src.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, clientX: fx, clientY: fy, dataTransfer: dt }));
4334
+ return true;
4335
+ })(${fromX}, ${fromY})`
4336
+ );
4337
+ await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
4338
+ type: "mouseMoved",
4339
+ x: toX,
4340
+ y: toY,
4341
+ modifiers: heldModifiers,
4342
+ pointerType: "mouse"
4343
+ });
4344
+ await cdpChannel.evaluate(
4345
+ `(async (tx, ty) => {
3233
4346
  await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
3234
- dst.dispatchEvent(new DragEvent("dragenter", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: dt }));
3235
- dst.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: dt }));
3236
- dst.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: dt }));
3237
- src.dispatchEvent(new DragEvent("dragend", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: dt }));
4347
+ const st = window.__spanaDragState;
4348
+ delete window.__spanaDragState;
4349
+ if (!st) return false;
4350
+ const dst = document.elementFromPoint(tx, ty) || document.body;
4351
+ dst.dispatchEvent(new DragEvent("dragenter", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: st.dt }));
4352
+ dst.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: st.dt }));
4353
+ dst.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: st.dt }));
4354
+ st.src.dispatchEvent(new DragEvent("dragend", { bubbles: true, cancelable: true, clientX: tx, clientY: ty, dataTransfer: st.dt }));
3238
4355
  return true;
3239
- })(${fromX}, ${fromY}, ${toX}, ${toY})`
3240
- ).catch(() => false);
3241
- if (didHtml5Drag) return;
4356
+ })(${toX}, ${toY})`
4357
+ );
4358
+ lastMouseX = toX;
4359
+ lastMouseY = toY;
4360
+ return;
4361
+ }
3242
4362
  const totalSteps = Math.max(1, Math.round(steps));
3243
- await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
3244
- type: "mouseMoved",
3245
- x: fromX,
3246
- y: fromY
3247
- });
3248
4363
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
3249
4364
  type: "mousePressed",
3250
4365
  x: fromX,
3251
4366
  y: fromY,
3252
4367
  button: "left",
3253
4368
  buttons: 1,
3254
- clickCount: 1
4369
+ clickCount: 1,
4370
+ modifiers: heldModifiers,
4371
+ pointerType: "mouse"
3255
4372
  });
3256
4373
  for (let i = 1; i <= totalSteps; i++) {
3257
4374
  const t = i / totalSteps;
@@ -3260,7 +4377,9 @@ function makeLightweightCdpDriver(options) {
3260
4377
  x: fromX + (toX - fromX) * t,
3261
4378
  y: fromY + (toY - fromY) * t,
3262
4379
  button: "left",
3263
- buttons: 1
4380
+ buttons: 1,
4381
+ modifiers: heldModifiers,
4382
+ pointerType: "mouse"
3264
4383
  });
3265
4384
  }
3266
4385
  await cdpChannel.sendCommand("Input.dispatchMouseEvent", {
@@ -3269,60 +4388,144 @@ function makeLightweightCdpDriver(options) {
3269
4388
  y: toY,
3270
4389
  button: "left",
3271
4390
  buttons: 0,
3272
- clickCount: 1
4391
+ clickCount: 1,
4392
+ modifiers: heldModifiers,
4393
+ pointerType: "mouse"
3273
4394
  });
4395
+ lastMouseX = toX;
4396
+ lastMouseY = toY;
3274
4397
  },
3275
4398
  catch: (e) => new DriverError({ message: `CDP dragAndDrop failed: ${e}` })
3276
4399
  }),
3277
- setViewport: (viewport) => Effect.tryPromise({
4400
+ setViewport: (viewport) => Effect_exports.tryPromise({
3278
4401
  try: async () => {
3279
4402
  width = viewport.width;
3280
4403
  height = viewport.height;
3281
- viewportMutated = true;
4404
+ const wasMobileOrTouch = currentMobile || currentHasTouch;
4405
+ const nextDpr = viewport.deviceScaleFactor ?? currentDeviceScaleFactor;
4406
+ const nextMobile = viewport.isMobile ?? viewport.mobile ?? currentMobile;
4407
+ const nextHasTouch = viewport.hasTouch ?? (viewport.isMobile !== void 0 || viewport.mobile !== void 0 ? nextMobile : currentHasTouch);
4408
+ currentDeviceScaleFactor = nextDpr;
4409
+ currentMobile = nextMobile;
4410
+ currentHasTouch = nextHasTouch;
4411
+ hasDeviceMetricsDirty = true;
4412
+ if (nextMobile !== initialMobile || nextHasTouch !== initialHasTouch || wasMobileOrTouch !== (initialMobile || initialHasTouch) || viewport.hasTouch !== void 0 || viewport.mobile !== void 0 || viewport.isMobile !== void 0) {
4413
+ hasTouchEmulationDirty = true;
4414
+ }
4415
+ if (wasMobileOrTouch && !nextMobile && !nextHasTouch) {
4416
+ await cdpChannel.sendCommand("Emulation.clearDeviceMetricsOverride", {}).catch(() => {
4417
+ });
4418
+ await cdpChannel.sendCommand("Emulation.setTouchEmulationEnabled", {
4419
+ enabled: false
4420
+ }).catch(() => {
4421
+ });
4422
+ await cdpChannel.sendCommand("Emulation.setEmitTouchEventsForMouse", {
4423
+ enabled: false,
4424
+ configuration: "desktop"
4425
+ }).catch(() => {
4426
+ });
4427
+ }
3282
4428
  await cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
3283
4429
  width: viewport.width,
3284
4430
  height: viewport.height,
3285
- deviceScaleFactor: viewport.deviceScaleFactor ?? 1,
3286
- mobile: viewport.mobile ?? false
4431
+ deviceScaleFactor: nextDpr,
4432
+ mobile: nextMobile
3287
4433
  });
4434
+ if (nextHasTouch) {
4435
+ await cdpChannel.sendCommand("Emulation.setTouchEmulationEnabled", {
4436
+ enabled: true,
4437
+ maxTouchPoints: 5
4438
+ }).catch(() => {
4439
+ });
4440
+ } else if (!wasMobileOrTouch && viewport.hasTouch === false) {
4441
+ await cdpChannel.sendCommand("Emulation.clearDeviceMetricsOverride", {}).catch(() => {
4442
+ });
4443
+ await cdpChannel.sendCommand("Emulation.setTouchEmulationEnabled", {
4444
+ enabled: false
4445
+ }).catch(() => {
4446
+ });
4447
+ await cdpChannel.sendCommand("Emulation.setEmitTouchEventsForMouse", {
4448
+ enabled: false,
4449
+ configuration: "desktop"
4450
+ }).catch(() => {
4451
+ });
4452
+ await cdpChannel.sendCommand("Emulation.setDeviceMetricsOverride", {
4453
+ width: viewport.width,
4454
+ height: viewport.height,
4455
+ deviceScaleFactor: nextDpr,
4456
+ mobile: nextMobile
4457
+ });
4458
+ }
3288
4459
  },
3289
4460
  catch: (e) => new DriverError({ message: `CDP setViewport failed: ${e}` })
3290
4461
  }),
3291
- setEmulation: (emulationOpts) => Effect.tryPromise({
4462
+ setEmulation: (emulationOpts) => Effect_exports.tryPromise({
3292
4463
  try: async () => {
3293
- emulationMutated = true;
3294
4464
  const features = [];
3295
4465
  if (emulationOpts.colorScheme !== void 0) {
4466
+ hasEmulatedMediaDirty = true;
3296
4467
  features.push({
3297
4468
  name: "prefers-color-scheme",
3298
4469
  value: emulationOpts.colorScheme === "no-preference" ? "" : emulationOpts.colorScheme
3299
4470
  });
3300
4471
  }
3301
4472
  if (emulationOpts.reducedMotion !== void 0) {
4473
+ hasEmulatedMediaDirty = true;
3302
4474
  features.push({
3303
4475
  name: "prefers-reduced-motion",
3304
4476
  value: emulationOpts.reducedMotion === "no-preference" ? "" : emulationOpts.reducedMotion
3305
4477
  });
3306
4478
  }
4479
+ const emuOps = [];
3307
4480
  if (features.length > 0) {
3308
- await cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features });
4481
+ emuOps.push(cdpChannel.sendCommand("Emulation.setEmulatedMedia", { features }));
4482
+ }
4483
+ if (emulationOpts.userAgent !== void 0) {
4484
+ hasUserAgentDirty = true;
4485
+ activeUserAgent = emulationOpts.userAgent;
3309
4486
  }
3310
4487
  if (emulationOpts.locale !== void 0) {
3311
- await applyLocaleOverride(activeSlot?.sessionId ?? null, emulationOpts.locale);
4488
+ hasLocaleDirty = true;
4489
+ hasUserAgentDirty = true;
4490
+ activeLocale = emulationOpts.locale;
4491
+ emuOps.push(
4492
+ cdpChannel.sendCommand("Emulation.setLocaleOverride", { locale: emulationOpts.locale }).catch(() => {
4493
+ })
4494
+ );
3312
4495
  }
3313
4496
  if (emulationOpts.timezoneId !== void 0) {
3314
- await cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
3315
- timezoneId: emulationOpts.timezoneId
3316
- }).catch(() => {
3317
- });
4497
+ hasTimezoneDirty = true;
4498
+ emuOps.push(
4499
+ cdpChannel.sendCommand("Emulation.setTimezoneOverride", {
4500
+ timezoneId: emulationOpts.timezoneId
4501
+ }).catch(() => {
4502
+ })
4503
+ );
4504
+ }
4505
+ if (emulationOpts.locale !== void 0 || emulationOpts.userAgent !== void 0) {
4506
+ const effectiveUa = await resolveEffectiveUserAgent(
4507
+ activeSlot?.sessionId ?? null,
4508
+ emulationOpts.userAgent
4509
+ );
4510
+ const acceptLanguage = buildAcceptLanguage(activeLocale);
4511
+ emuOps.push(
4512
+ cdpChannel.sendCommand("Emulation.setUserAgentOverride", {
4513
+ userAgent: effectiveUa,
4514
+ ...acceptLanguage ? { acceptLanguage } : {}
4515
+ }).catch(() => {
4516
+ })
4517
+ );
4518
+ }
4519
+ if (emuOps.length > 0) {
4520
+ await Promise.all(emuOps);
3318
4521
  }
3319
4522
  },
3320
4523
  catch: (e) => new DriverError({ message: `CDP setEmulation failed: ${e}` })
3321
4524
  }),
3322
- setDialogHandler: (handler) => Effect.sync(() => {
4525
+ setDialogHandler: (handler) => Effect_exports.sync(() => {
3323
4526
  dialogHandler = handler;
3324
4527
  }),
3325
- getClipboard: () => Effect.tryPromise({
4528
+ getClipboard: () => Effect_exports.tryPromise({
3326
4529
  try: async () => {
3327
4530
  if (activeSlot?.browserContextId) {
3328
4531
  permissionsMutated = true;
@@ -3351,7 +4554,7 @@ function makeLightweightCdpDriver(options) {
3351
4554
  },
3352
4555
  catch: (e) => new DriverError({ message: `CDP getClipboard failed: ${e}` })
3353
4556
  }),
3354
- setClipboard: (text) => Effect.tryPromise({
4557
+ setClipboard: (text) => Effect_exports.tryPromise({
3355
4558
  try: async () => {
3356
4559
  if (activeSlot?.browserContextId) {
3357
4560
  permissionsMutated = true;
@@ -3380,39 +4583,48 @@ function makeLightweightCdpDriver(options) {
3380
4583
  },
3381
4584
  catch: (e) => new DriverError({ message: `CDP setClipboard failed: ${e}` })
3382
4585
  }),
3383
- waitForDownload: (triggerFn, dlOpts) => Effect.tryPromise({
4586
+ waitForDownload: (triggerFn, dlOpts) => Effect_exports.tryPromise({
3384
4587
  try: async () => {
3385
4588
  const timeoutMs = dlOpts?.timeout ?? 15e3;
3386
- if (!downloadDir) {
3387
- downloadDir = mkdtempSync(join2(tmpdir(), "spana-cdp-dl-"));
3388
- await cdpChannel.sendCommand(
3389
- "Browser.setDownloadBehavior",
3390
- {
3391
- behavior: "allowAndName",
3392
- downloadPath: downloadDir,
3393
- eventsEnabled: true,
3394
- ...activeSlot?.browserContextId ? { browserContextId: activeSlot.browserContextId } : {}
3395
- },
3396
- null
3397
- );
3398
- }
4589
+ await ensureDownloadBehaviorForActiveContext();
4590
+ let timer;
4591
+ let waiterEntry;
4592
+ const cleanup = () => {
4593
+ if (timer !== void 0) {
4594
+ clearTimeout(timer);
4595
+ timer = void 0;
4596
+ }
4597
+ if (waiterEntry) {
4598
+ const idx = downloadWaiters.indexOf(waiterEntry);
4599
+ if (idx >= 0) downloadWaiters.splice(idx, 1);
4600
+ waiterEntry = void 0;
4601
+ }
4602
+ };
3399
4603
  const downloadPromise = new Promise((resolve2, reject) => {
3400
- const timer = setTimeout(() => {
4604
+ timer = setTimeout(() => {
4605
+ cleanup();
3401
4606
  reject(new Error(`Timed out waiting for download after ${timeoutMs}ms`));
3402
4607
  }, timeoutMs);
3403
- downloadWaiters.push({
4608
+ waiterEntry = {
3404
4609
  resolve: (entry2) => {
3405
- clearTimeout(timer);
4610
+ cleanup();
3406
4611
  resolve2(entry2);
3407
4612
  },
3408
4613
  reject: (err) => {
3409
- clearTimeout(timer);
4614
+ cleanup();
3410
4615
  reject(err);
3411
4616
  }
3412
- });
4617
+ };
4618
+ downloadWaiters.push(waiterEntry);
3413
4619
  });
3414
- await triggerFn();
3415
- const entry = await downloadPromise;
4620
+ downloadPromise.catch(handledByLaterAwait);
4621
+ let entry;
4622
+ try {
4623
+ await triggerFn();
4624
+ entry = await downloadPromise;
4625
+ } finally {
4626
+ cleanup();
4627
+ }
3416
4628
  return {
3417
4629
  suggestedFilename: entry.suggestedFilename,
3418
4630
  path: entry.filePath,
@@ -3426,7 +4638,7 @@ function makeLightweightCdpDriver(options) {
3426
4638
  },
3427
4639
  catch: (e) => new DriverError({ message: `CDP waitForDownload failed: ${e}` })
3428
4640
  }),
3429
- newTab: (url) => Effect.tryPromise({
4641
+ newTab: (url) => Effect_exports.tryPromise({
3430
4642
  try: async () => {
3431
4643
  if (!activeSlot) {
3432
4644
  throw new Error("newTab() requires browser-context mode (engine: 'cdp')");
@@ -3464,7 +4676,7 @@ function makeLightweightCdpDriver(options) {
3464
4676
  },
3465
4677
  catch: (e) => new DriverError({ message: `CDP newTab failed: ${e}` })
3466
4678
  }),
3467
- switchToTab: (index) => Effect.tryPromise({
4679
+ switchToTab: (index) => Effect_exports.tryPromise({
3468
4680
  try: async () => {
3469
4681
  if (!activeSlot || !activeSlot.tabs[index]) {
3470
4682
  throw new Error(`Tab index ${index} is out of range.`);
@@ -3478,7 +4690,7 @@ function makeLightweightCdpDriver(options) {
3478
4690
  },
3479
4691
  catch: (e) => new DriverError({ message: `CDP switchToTab failed: ${e}` })
3480
4692
  }),
3481
- closeTab: () => Effect.tryPromise({
4693
+ closeTab: () => Effect_exports.tryPromise({
3482
4694
  try: async () => {
3483
4695
  if (!activeSlot) return;
3484
4696
  if (activeSlot.tabs.length <= 1) {
@@ -3524,7 +4736,7 @@ function makeLightweightCdpDriver(options) {
3524
4736
  },
3525
4737
  catch: (e) => new DriverError({ message: `CDP closeTab failed: ${e}` })
3526
4738
  }),
3527
- getTabIds: () => Effect.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
4739
+ getTabIds: () => Effect_exports.sync(() => activeSlot ? activeSlot.tabs.map((t) => t.tabId) : ["tab-1"])
3528
4740
  };
3529
4741
  return service;
3530
4742
  });
@@ -3537,7 +4749,8 @@ export {
3537
4749
  runOAuthPopupFlow,
3538
4750
  buildDirectChromiumLaunchArgs,
3539
4751
  launchDirectCdpBrowser,
4752
+ mapPermissionToCdpDescriptor,
3540
4753
  UPLOAD_ATTACH_TIMEOUT_MS,
3541
4754
  makeLightweightCdpDriver
3542
4755
  };
3543
- //# sourceMappingURL=chunk-5WPPWTC3.js.map
4756
+ //# sourceMappingURL=chunk-E67QUGT3.js.map